akka.http.scaladsl.model.Uri.Path Scala Examples
The following examples show how to use akka.http.scaladsl.model.Uri.Path.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
Example 1
Source File: LinkDescriptionSpec.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.kg.resources import akka.http.scaladsl.model.Uri.Path import akka.http.scaladsl.model.{ContentType, ContentTypes} import ch.epfl.bluebrain.nexus.commons.test.{EitherValues, Randomness} import ch.epfl.bluebrain.nexus.kg.TestHelper import ch.epfl.bluebrain.nexus.kg.resources.ProjectIdentifier.ProjectRef import ch.epfl.bluebrain.nexus.kg.resources.Rejection.InvalidResourceFormat import ch.epfl.bluebrain.nexus.kg.resources.file.File.{FileDescription, LinkDescription} import ch.epfl.bluebrain.nexus.rdf.implicits._ import io.circe.Json import io.circe.syntax._ import org.scalatest.OptionValues import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpecLike class LinkDescriptionSpec extends AnyWordSpecLike with Matchers with TestHelper with Randomness with EitherValues with OptionValues { abstract private class Ctx { val id = Id(ProjectRef(genUUID), genIri) val p = genString() + "/" + genString() val f = genString() val m = "application/json" def jsonLink(mediaType: String = m, filename: String = f, path: String = p): Json = Json.obj("filename" -> filename.asJson, "path" -> path.asJson, "mediaType" -> mediaType.asJson) } "A Link Description" should { "be decoded correctly" in new Ctx { LinkDescription(id, jsonLink()).rightValue shouldEqual LinkDescription(Path(p), Some(f), ContentType.parse(m).toOption) LinkDescription(id, Json.obj("path" -> p.asJson)).rightValue shouldEqual LinkDescription(Path(p), None, None) } "accept missing filename" in new Ctx { LinkDescription(id, jsonLink().removeKeys("filename")).rightValue shouldEqual LinkDescription(Path(p), None, ContentType.parse(m).toOption) } "reject empty filename" in new Ctx { LinkDescription(id, jsonLink(filename = "")).leftValue shouldBe a[InvalidResourceFormat] } "accept missing mediaType" in new Ctx { LinkDescription(id, jsonLink().removeKeys("mediaType")).rightValue shouldEqual LinkDescription(Path(p), Some(f), None) } "reject wrong mediaType format" in new Ctx { LinkDescription(id, jsonLink(mediaType = genString())).leftValue shouldBe a[InvalidResourceFormat] } "reject missing path" in new Ctx { LinkDescription(id, jsonLink().removeKeys("path")).leftValue shouldBe a[InvalidResourceFormat] } "be converted to a FileDescription correctly" in new Ctx { val fileDesc1 = FileDescription.from(LinkDescription(Path("/foo/bar/file.ext"), None, None)) fileDesc1.filename shouldEqual "file.ext" fileDesc1.mediaType shouldEqual None fileDesc1.defaultMediaType shouldEqual ContentTypes.`application/octet-stream` val fileDesc2 = FileDescription.from(LinkDescription(Path("/foo/bar/somedir/"), None, ContentType.parse(m).toOption)) fileDesc2.filename shouldEqual "somedir" fileDesc2.mediaType.value shouldEqual ContentTypes.`application/json` val fileDesc3 = FileDescription.from(LinkDescription(Path("/foo/bar/baz"), Some("file.json"), ContentType.parse(m).toOption)) fileDesc3.filename shouldEqual "file.json" fileDesc3.mediaType.value shouldEqual ContentTypes.`application/json` } } }
Example 2
Source File: LinkDescriptionSpec.scala From nexus-kg with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.kg.resources import akka.http.scaladsl.model.Uri.Path import akka.http.scaladsl.model.{ContentType, ContentTypes} import ch.epfl.bluebrain.nexus.commons.test.{EitherValues, Randomness} import ch.epfl.bluebrain.nexus.kg.TestHelper import ch.epfl.bluebrain.nexus.kg.resources.ProjectIdentifier.ProjectRef import ch.epfl.bluebrain.nexus.kg.resources.Rejection.InvalidResourceFormat import ch.epfl.bluebrain.nexus.kg.resources.file.File.{FileDescription, LinkDescription} import ch.epfl.bluebrain.nexus.rdf.implicits._ import io.circe.Json import io.circe.syntax._ import org.scalatest.OptionValues import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpecLike class LinkDescriptionSpec extends AnyWordSpecLike with Matchers with TestHelper with Randomness with EitherValues with OptionValues { private abstract class Ctx { val id = Id(ProjectRef(genUUID), genIri) val p = genString() + "/" + genString() val f = genString() val m = "application/json" def jsonLink(mediaType: String = m, filename: String = f, path: String = p): Json = Json.obj("filename" -> filename.asJson, "path" -> path.asJson, "mediaType" -> mediaType.asJson) } "A Link Description" should { "be decoded correctly" in new Ctx { LinkDescription(id, jsonLink()).rightValue shouldEqual LinkDescription(Path(p), Some(f), ContentType.parse(m).toOption) LinkDescription(id, Json.obj("path" -> p.asJson)).rightValue shouldEqual LinkDescription(Path(p), None, None) } "accept missing filename" in new Ctx { LinkDescription(id, jsonLink().removeKeys("filename")).rightValue shouldEqual LinkDescription(Path(p), None, ContentType.parse(m).toOption) } "reject empty filename" in new Ctx { LinkDescription(id, jsonLink(filename = "")).leftValue shouldBe a[InvalidResourceFormat] } "accept missing mediaType" in new Ctx { LinkDescription(id, jsonLink().removeKeys("mediaType")).rightValue shouldEqual LinkDescription(Path(p), Some(f), None) } "reject wrong mediaType format" in new Ctx { LinkDescription(id, jsonLink(mediaType = genString())).leftValue shouldBe a[InvalidResourceFormat] } "reject missing path" in new Ctx { LinkDescription(id, jsonLink().removeKeys("path")).leftValue shouldBe a[InvalidResourceFormat] } "be converted to a FileDescription correctly" in new Ctx { val fileDesc1 = FileDescription.from(LinkDescription(Path("/foo/bar/file.ext"), None, None)) fileDesc1.filename shouldEqual "file.ext" fileDesc1.mediaType shouldEqual None fileDesc1.defaultMediaType shouldEqual ContentTypes.`application/octet-stream` val fileDesc2 = FileDescription.from(LinkDescription(Path("/foo/bar/somedir/"), None, ContentType.parse(m).toOption)) fileDesc2.filename shouldEqual "somedir" fileDesc2.mediaType.value shouldEqual ContentTypes.`application/json` val fileDesc3 = FileDescription.from(LinkDescription(Path("/foo/bar/baz"), Some("file.json"), ContentType.parse(m).toOption)) fileDesc3.filename shouldEqual "file.json" fileDesc3.mediaType.value shouldEqual ContentTypes.`application/json` } } }
Example 3
Source File: PathDirectives.scala From nexus-kg with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.kg.directives import akka.http.scaladsl.model.Uri.Path import akka.http.scaladsl.server.PathMatcher.{Matched, Unmatched} import akka.http.scaladsl.server.PathMatchers.Segment import akka.http.scaladsl.server.directives.PathDirectives.pathPrefix import akka.http.scaladsl.server.{Directive0, PathMatcher, PathMatcher1} import ch.epfl.bluebrain.nexus.admin.client.types.Project import ch.epfl.bluebrain.nexus.rdf.Iri.AbsoluteIri import ch.epfl.bluebrain.nexus.rdf.{Curie, Iri} object PathDirectives { def isIdSegment(iri: AbsoluteIri)(implicit project: Project): Directive0 = { val matcher = new PathMatcher[Unit] { def apply(path: Path) = path match { case Path.Segment(segment, tail) => toIri(segment) match { case Some(`iri`) => Matched(tail, ()) case _ => Unmatched } case _ => Unmatched } } pathPrefix(matcher) } }
Example 4
Source File: ServiceRegistrySpec.scala From squbs with Apache License 2.0 | 5 votes |
package org.squbs.unicomplex import akka.actor.ActorSystem import akka.http.scaladsl.model.Uri.Path import akka.testkit.TestKit import org.scalatest.{FlatSpecLike, Matchers} import org.squbs.unicomplex.FlowHandler._ class ServiceRegistrySpec extends TestKit(ActorSystem("ServiceRegistrySpec")) with FlatSpecLike with Matchers { "merge" should "work" in { val serviceRegistry = new ServiceRegistry(system.log) import serviceRegistry.merge val pipelineSetting = (None, None, None) val result = merge(Seq(), "abc", "old", pipelineSetting) result should have size 1 result(0)._2 should be ("old") val result1 = merge(result, "", "empty", pipelineSetting) result1 should have size 2 result1(0)._2 should be ("old") result1(1)._2 should be ("empty") val result2 = merge(result1, "abc/def", "abc/def", pipelineSetting) result2 should have size 3 result2(0)._2 should be ("abc/def") result2(1)._2 should be ("old") result2(2)._2 should be ("empty") val result3 = merge(result2, "abc", "new", pipelineSetting) result3 should have size 3 result3(0)._2 should be ("abc/def") result3(1)._2 should be ("new") result3(2)._2 should be ("empty") val finding = result3 find { entry => pathMatch(Path("abc"), entry._1) } finding should not be None finding.get._2 should be ("new") val finding2 = result3 find { entry => pathMatch(Path("abc/def"), entry._1) } finding2 should not be None finding2.get._2 should be ("abc/def") val finding3 = result3 find { entry => pathMatch(Path("aabc/def"), entry._1) } finding3 should not be None finding3.get._2 should be ("empty") val finding4 = result3 find { entry => pathMatch(Path("abc/defg"), entry._1) } finding4 should not be None finding4.get._2 should be ("new") val finding5 = result3 find { entry => pathMatch(Path("abcd/a"), entry._1) // abcd should not match either abc/def nor abc } finding5.get._2 should be ("empty") } }
Example 5
Source File: RegisterContextSpec.scala From squbs with Apache License 2.0 | 5 votes |
package org.squbs.unicomplex import akka.http.scaladsl.model.Uri import akka.http.scaladsl.model.Uri.Path import akka.http.scaladsl.model.Uri.Path.{Empty, Segment, Slash} import org.scalatest.{FlatSpecLike, Matchers} class RegisterContextSpec extends FlatSpecLike with Matchers { "Path matching" should "work" in { val emptyPath = Path("") emptyPath shouldBe empty emptyPath should have length 0 emptyPath.charCount should be (0) println(emptyPath.getClass.getName) emptyPath should be (Empty) emptyPath should not be 'startsWithSegment emptyPath should not be 'startsWithSlash emptyPath.startsWith(Empty) should be (true) val root = Path("/") root should not be empty root should have length 1 root.charCount should be (1) println(root.getClass.getName) root shouldBe a [Slash] root should not be 'startsWithSegment root shouldBe 'startsWithSlash root.startsWith(Empty) should be (true) root.head should be ('/') root.tail should be (Empty) val single = Path("/abc") single should not be empty single should have length 2 single.charCount should be (4) println(single.getClass.getName) single shouldBe a[Slash] single should not be 'startsWithSegment single shouldBe 'startsWithSlash single.startsWith(Path("/")) should be (true) single.startsWith(Path("")) should be (true) single.startsWith(Path("abc")) should be (false) single.head should be ('/') single.tail should be (Path("abc")) val simple = Path("abc") simple should not be empty simple should have length 1 simple.charCount should be (3) println(simple.getClass.getName) simple shouldBe a[Segment] simple shouldBe 'startsWithSegment simple should not be 'startsWithSlash simple.startsWith(Path("/")) should be (false) simple.startsWith(Path("")) should be (true) simple.startsWith(Path("abc")) should be (true) simple.head should be ("abc") simple.tail should be (Empty) val multi = Path("abc/def") multi should not be empty multi should have length 3 multi.charCount should be (7) println(multi.getClass.getName) multi shouldBe a[Segment] multi shouldBe 'startsWithSegment multi should not be 'startsWithSlash multi.startsWith(Path("/")) should be (false) multi.startsWith(Path("")) should be (true) multi.startsWith(Path("abc")) should be (true) multi.head should be ("abc") multi.tail shouldBe a [Slash] multi.startsWith(Path("abc/de")) should be (true) } "request path matching" should "work" in { Uri("http://www.ebay.com").path should not be 'startsWithSlash Uri("http://www.ebay.com").path should not be 'startsWithSegment Uri("http://www.ebay.com").path.startsWith(Empty) should be (true) Uri("http://www.ebay.com/").path shouldBe 'startsWithSlash Uri("http://www.ebay.com/").path should not be 'startsWithSegment Uri("http://www.ebay.com/").path.startsWith(Empty) should be (true) Uri("http://www.ebay.com").path should be (Path("")) Uri("http://www.ebay.com/").path should be (Path("/")) Uri("http://127.0.0.1:8080/abc").path shouldBe 'startsWithSlash Uri("http://www.ebay.com/").path.startsWith(Path("")) should be (true) Uri("http://www.ebay.com").path.startsWith(Path("")) should be (true) Uri("http://www.ebay.com/abc").path.startsWith(Path("")) should be (true) Uri("http://www.ebay.com/abc").path.tail.startsWith(Path("")) should be (true) Uri("http://www.ebay.com/abc").path.tail.startsWith(Path("abc")) should be (true) Uri("http://www.ebay.com/abc/def").path.tail.startsWith(Path("abc")) should be (true) Uri("http://www.ebay.com/abc/def").path.tail.startsWith(Path("abc/def")) should be (true) } }
Example 6
Source File: FlowDefinitionSpec.scala From squbs with Apache License 2.0 | 5 votes |
package org.squbs.unicomplex import akka.actor.ActorSystem import akka.http.scaladsl.model.Uri.Path import akka.http.scaladsl.model._ import akka.pattern._ import akka.stream.ActorMaterializer import akka.stream.scaladsl.Flow import akka.testkit.{ImplicitSender, TestKit} import com.typesafe.config.ConfigFactory import org.scalatest.{BeforeAndAfterAll, FlatSpecLike, Matchers} import org.squbs.lifecycle.GracefulStop import org.squbs.unicomplex.Timeouts._ import scala.concurrent.Await object FlowDefinitionSpec { val dummyJarsDir = getClass.getClassLoader.getResource("classpaths").getPath val classPath = dummyJarsDir + "/FlowDefinitionSpec/META-INF/squbs-meta.conf" val config = ConfigFactory.parseString( s""" |squbs { | actorsystem-name = FlowDefinitionSpec | ${JMX.prefixConfig} = true |} |default-listener.bind-port = 0 """.stripMargin ) val boot = UnicomplexBoot(config) .createUsing {(name, config) => ActorSystem(name, config)} .scanResources(withClassPath = false, classPath) .initExtensions.start() } class TestFlowDefinition extends FlowDefinition with WebContext { val firstPath = s"/$webContext/first" val secondPath = s"/$webContext/second" val thirdPath = s"/$webContext/third" @volatile var count = 0 def flow = Flow[HttpRequest].map { case HttpRequest(HttpMethods.GET, Uri(_, _, Path(`firstPath`), _, _), _, _, _) => count += 1 HttpResponse(StatusCodes.OK, entity = count.toString) case HttpRequest(HttpMethods.GET, Uri(_, _, Path(`secondPath`), _, _), _, _, _) => count += 1 HttpResponse(StatusCodes.OK, entity = count.toString) case HttpRequest(HttpMethods.GET, Uri(_, _, Path(`thirdPath`), _, _), _, _, _) => HttpResponse(StatusCodes.OK, entity = {count += 1; count.toString}) } } class FlowDefinitionSpec extends TestKit( FlowDefinitionSpec.boot.actorSystem) with FlatSpecLike with Matchers with ImplicitSender with BeforeAndAfterAll { implicit val am = ActorMaterializer() val portBindings = Await.result((Unicomplex(system).uniActor ? PortBindings).mapTo[Map[String, Int]], awaitMax) val port = portBindings("default-listener") override def afterAll(): Unit = { Unicomplex(system).uniActor ! GracefulStop } "The test actor" should "return correct count value" in { // The behaviour is different than Spray. Not caching anymore. Await.result(entityAsString(s"http://127.0.0.1:$port/flowdef/first"), awaitMax) should be ("1") Await.result(entityAsString(s"http://127.0.0.1:$port/flowdef/first"), awaitMax) should be ("2") Await.result(entityAsString(s"http://127.0.0.1:$port/flowdef/second"), awaitMax) should be ("3") Await.result(entityAsString(s"http://127.0.0.1:$port/flowdef/third"), awaitMax) should be ("4") Await.result(entityAsString(s"http://127.0.0.1:$port/flowdef/third"), awaitMax) should be ("5") } }
Example 7
Source File: DummyFlowSvc.scala From squbs with Apache License 2.0 | 5 votes |
package org.squbs.unicomplex.dummyflowsvc import akka.http.scaladsl.model.HttpEntity.{ChunkStreamPart, Chunked} import akka.http.scaladsl.model.Uri.Path import akka.http.scaladsl.model._ import akka.stream.scaladsl.{Flow, Source} import org.squbs.unicomplex.{FlowDefinition, WebContext} class DummyFlowSvc extends FlowDefinition with WebContext { val prefix = if (webContext.isEmpty) "" else '/' + webContext val pingPath = s"$prefix/ping" val chunkPath = s"$prefix/chunks" val exceptionPath = s"$prefix/throwit" def flow = Flow[HttpRequest].map { case HttpRequest(_, Uri(_, _, Path(`pingPath`), _, _), _, _, _) => HttpResponse(StatusCodes.OK, entity = "pong") case req @ HttpRequest(_, Uri(_, _, Path(`chunkPath`), _, _), _, _, _) => val responseChunks = req.entity.dataBytes.filter(_.nonEmpty) .map { b => (1, b.length) } .reduce { (a, b) => (a._1 + b._1, a._2 + b._2) } .map { case (chunkCount, byteCount) => ChunkStreamPart(s"Received $chunkCount chunks and $byteCount bytes.\r\n") } .concat(Source.single(ChunkStreamPart("This is the last chunk!"))) HttpResponse(StatusCodes.OK, entity = Chunked(ContentTypes.`text/plain(UTF-8)`, responseChunks)) case HttpRequest(_, Uri(_, _, Path(`exceptionPath`), _, _), _, _, _) => throw new IllegalArgumentException("This path is supposed to throw this exception!") case _ => HttpResponse(StatusCodes.NotFound, entity = "Path not found!") } }
Example 8
Source File: AdminSvc.scala From squbs with Apache License 2.0 | 5 votes |
package org.squbs.admin import java.net.URLEncoder import akka.http.scaladsl.model.Uri.Path import akka.http.scaladsl.model._ import org.json4s.JsonAST.{JObject, JString} import org.json4s.jackson.JsonMethods._ import org.squbs.unicomplex.{RouteDefinition, WebContext} import org.squbs.util.ConfigUtil._ class AdminSvc extends RouteDefinition with WebContext { val prefix = if (webContext == "") "/bean" else s"/$webContext/bean" val exclusions = context.system.settings.config.get[Seq[String]]("squbs.admin.exclusions", Seq.empty[String]).toSet val (exBeans, exFieldSet) = exclusions partition { !_.contains("::") } val exFields = exFieldSet map { fieldSpec => val fields = fieldSpec split "::" fields(0) -> fields(1) } groupBy (_._1) mapValues { _.map(_._2) } val route = get { pathEndOrSingleSlash { extractUri { uri => complete { val kv = MBeanUtil.allObjectNames collect { case name if !(exBeans contains name) => val resource = Path(s"$prefix/${URLEncoder.encode(name.replace('=', '~'), "UTF-8")}") name -> JString(uri.withPath(resource).toString()) } HttpResponse(entity = HttpEntity(ContentTypes.`application/json`, pretty(render(JObject(kv))))) } } } ~ path("bean" / Segment) { encName => complete { val name = encName.replace('~', '=').replace('%', '/') val response: HttpResponse = if (exBeans contains name) HttpResponse(StatusCodes.NotFound, entity = StatusCodes.NotFound.defaultMessage) else MBeanUtil.asJSON(name, exFields getOrElse (name, Set.empty)) .map { json => HttpResponse(entity = json) } .getOrElse (HttpResponse(StatusCodes.NotFound, entity = StatusCodes.NotFound.defaultMessage)) response } } } }
Example 9
Source File: PublicApi.scala From affinity with Apache License 2.0 | 5 votes |
import akka.http.scaladsl.model.HttpMethods._ import akka.http.scaladsl.model.HttpResponse import akka.http.scaladsl.model.StatusCodes._ import akka.http.scaladsl.model.Uri.{Path, Query} import io.amient.affinity.avro.record.AvroRecord import io.amient.affinity.core.actor.GatewayHttp import io.amient.affinity.core.http.Encoder import io.amient.affinity.core.http.RequestMatchers.{HTTP, PATH} import io.amient.affinity.core.state.KVStore import scala.concurrent.Promise case class ProtectedProfile(hello: String = "world") extends AvroRecord trait PublicApi extends GatewayHttp { private val settings: KVStore[String, ConfigEntry] = global[String, ConfigEntry]("settings") abstract override def handle: Receive = super.handle orElse { case HTTP(GET, uri@PATH("profile", _), query, response) => AUTH_DSA(uri, query, response) { (sig: String) => Encoder.json(OK, Map( "signature" -> sig, "profile" -> ProtectedProfile() )) } case HTTP(GET, uri@PATH("verify"), query, response) => AUTH_DSA(uri, query, response) { _ => Encoder.json(OK, Some(ProtectedProfile())) } } object AUTH_DSA { def apply(path: Path, query: Query, response: Promise[HttpResponse])(code: (String) => HttpResponse): Unit = { try { query.get("signature") match { case None => throw new IllegalAccessError case Some(sig) => sig.split(":") match { case Array(k, clientSignature) => settings(k) match { case None => throw new IllegalAccessError(s"Invalid api key $k") case Some(configEntry) => if (configEntry.crypto.verify(clientSignature, path.toString)) { val serverSignature = configEntry.crypto.sign(clientSignature) response.success(code(serverSignature)) } else { throw new IllegalAccessError(configEntry.crypto.sign(path.toString)) } } case _ => throw new IllegalAccessError } } } catch { case _: IllegalAccessError => response.success(Encoder.json(Unauthorized, "Unauthorized")) case e: Throwable => response.success(handleException(headers = List())(e)) } } } }
Example 10
Source File: Rejection.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.storage import akka.http.scaladsl.model.StatusCodes import akka.http.scaladsl.model.Uri.Path import akka.http.scaladsl.server.{Rejection => AkkaRejection} import ch.epfl.bluebrain.nexus.storage.routes.StatusFrom import scala.annotation.nowarn import io.circe.generic.extras.Configuration import io.circe.generic.extras.semiauto.deriveConfiguredEncoder import io.circe.{Encoder, Json} final case class EmptyFilename(name: String) implicit def statusCodeFrom: StatusFrom[Rejection] = StatusFrom { case _: PathContainsLinks => StatusCodes.BadRequest case _: PathAlreadyExists => StatusCodes.Conflict case _: BucketNotFound => StatusCodes.NotFound case _: PathNotFound => StatusCodes.NotFound } @nowarn("cat=unused") implicit val rejectionEncoder: Encoder[Rejection] = { implicit val rejectionConfig: Configuration = Configuration.default.withDiscriminator("@type") val enc = deriveConfiguredEncoder[Rejection].mapJson(jsonError) Encoder.instance(r => enc(r) deepMerge Json.obj("reason" -> Json.fromString(r.msg))) } }
Example 11
Source File: StorageError.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.storage import akka.http.scaladsl.model.StatusCodes import akka.http.scaladsl.model.Uri.Path import ch.epfl.bluebrain.nexus.storage.routes.StatusFrom import io.circe.generic.extras.Configuration import io.circe.generic.extras.semiauto.deriveConfiguredEncoder import io.circe.{Encoder, Json} import scala.annotation.nowarn final case class OperationTimedOut(override val msg: String) extends StorageError(msg) @nowarn("cat=unused") implicit private val config: Configuration = Configuration.default.withDiscriminator("@type") private val derivedEncoder = deriveConfiguredEncoder[StorageError].mapJson(jsonError) implicit val storageErrorEncoder: Encoder[StorageError] = Encoder.instance(r => derivedEncoder(r) deepMerge Json.obj("reason" -> Json.fromString(r.msg))) implicit val storageErrorStatusFrom: StatusFrom[StorageError] = { case _: PathNotFound => StatusCodes.NotFound case _: PathInvalid => StatusCodes.BadRequest case AuthenticationFailed => StatusCodes.Unauthorized case AuthorizationFailed => StatusCodes.Forbidden case _ => StatusCodes.InternalServerError } }
Example 12
Source File: StorageDirectives.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.storage.routes import akka.http.scaladsl.model.Uri import akka.http.scaladsl.model.Uri.Path import akka.http.scaladsl.model.Uri.Path._ import akka.http.scaladsl.server.Directives.{extractUnmatchedPath, failWith, pass, provide, reject} import akka.http.scaladsl.server._ import ch.epfl.bluebrain.nexus.storage.Rejection.{BucketNotFound, PathAlreadyExists, PathNotFound} import ch.epfl.bluebrain.nexus.storage.StorageError.PathInvalid import ch.epfl.bluebrain.nexus.storage.Storages import ch.epfl.bluebrain.nexus.storage.Storages.PathExistence.{PathDoesNotExist, PathExists} import ch.epfl.bluebrain.nexus.storage.Storages.BucketExistence.BucketExists import scala.annotation.tailrec object StorageDirectives { def extractRelativeFilePath(name: String): Directive1[Path] = extractRelativePath(name).flatMap { case path if path.reverse.startsWithSegment => provide(path) case path => failWith(PathInvalid(name, path)) } @tailrec private def relativize(path: Path): Path = path match { case Slash(rest) => relativize(rest) case rest => rest } }
Example 13
Source File: PathMatchers.scala From matcher with MIT License | 5 votes |
package com.wavesplatform.dex.api.routes import akka.http.scaladsl.model.Uri.Path import akka.http.scaladsl.server.PathMatcher.{Matched, Unmatched} import akka.http.scaladsl.server.{PathMatcher, PathMatcher1, PathMatchers => AkkaMatchers} import com.wavesplatform.dex.domain.account.{Address, PublicKey} import com.wavesplatform.dex.domain.asset.{Asset, AssetPair} import com.wavesplatform.dex.domain.bytes.ByteStr import com.wavesplatform.dex.domain.error.ValidationError object PathMatchers { class Base58[A](f: String => Option[A]) extends PathMatcher1[A] { def apply(path: Path): PathMatcher.Matching[Tuple1[A]] = path match { case Path.Segment(segment, tail) => f(segment).fold[PathMatcher.Matching[Tuple1[A]]](Unmatched)(v => Matched(tail, Tuple1(v))) case _ => Unmatched } } val AssetPairPM: PathMatcher1[AssetPair] = AkkaMatchers.Segments(2).flatMap { case a1 :: a2 :: Nil => AssetPair.createAssetPair(a1, a2).toOption case _ => None } val AssetPM: PathMatcher1[Asset] = AkkaMatchers.Segment.flatMap { s => AssetPair.extractAsset(s).toOption } object ByteStrPM extends Base58[ByteStr](ByteStr.decodeBase58(_).toOption) object PublicKeyPM extends Base58[PublicKey](PublicKey.fromBase58String(_).toOption) object AddressPM extends Base58[Either[ValidationError.InvalidAddress, Address]](s => Option(Address fromString s)) }
Example 14
Source File: PathDirectives.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.kg.directives import akka.http.scaladsl.model.Uri.Path import akka.http.scaladsl.server.PathMatcher.{Matched, Unmatched} import akka.http.scaladsl.server.PathMatchers.Segment import akka.http.scaladsl.server.directives.PathDirectives.pathPrefix import akka.http.scaladsl.server.{Directive0, PathMatcher, PathMatcher1} import ch.epfl.bluebrain.nexus.admin.client.types.Project import ch.epfl.bluebrain.nexus.rdf.Iri.AbsoluteIri import ch.epfl.bluebrain.nexus.rdf.{Curie, Iri} object PathDirectives { def isIdSegment(iri: AbsoluteIri)(implicit project: Project): Directive0 = { val matcher = new PathMatcher[Unit] { def apply(path: Path) = path match { case Path.Segment(segment, tail) => toIri(segment) match { case Some(`iri`) => Matched(tail, ()) case _ => Unmatched } case _ => Unmatched } } pathPrefix(matcher) } }
Example 15
Source File: YetAnotherAkkaClient.scala From telegram with Apache License 2.0 | 5 votes |
package com.bot4s.telegram.clients import akka.actor.ActorSystem import akka.http.scaladsl.Http import akka.http.scaladsl.marshalling.Marshal import akka.http.scaladsl.model.Uri.Path import akka.http.scaladsl.model._ import akka.http.scaladsl.unmarshalling.Unmarshal import akka.stream.Materializer import akka.stream.scaladsl.{Sink, Source} import cats.instances.future._ import com.bot4s.telegram.api.RequestHandler import com.bot4s.telegram.methods.{Request, Response} import io.circe.{Decoder, Encoder} import slogging.StrictLogging import com.bot4s.telegram.marshalling.responseDecoder import scala.concurrent.{ExecutionContext, Future} class YetAnotherAkkaClient(token: String, telegramHost: String = "api.telegram.org") (implicit system: ActorSystem, materializer: Materializer, ec: ExecutionContext) extends RequestHandler[Future] with StrictLogging { private val flow = Http().outgoingConnectionHttps(telegramHost) import com.bot4s.telegram.marshalling.AkkaHttpMarshalling._ override def sendRequest[R, T <: Request[_]](request: T)(implicit encT: Encoder[T], decR: Decoder[R]): Future[R] = { Source.fromFuture( Marshal(request).to[RequestEntity] .map { re => HttpRequest(HttpMethods.POST, Uri(path = Path(s"/bot$token/" + request.methodName)), entity = re) }) .via(flow) .mapAsync(1)(r => Unmarshal(r.entity).to[Response[R]]) .runWith(Sink.head) .map(processApiResponse[R]) } }
Example 16
Source File: SelfHosted2048Bot.scala From telegram with Apache License 2.0 | 5 votes |
import akka.http.scaladsl.model.Uri import akka.http.scaladsl.model.Uri.{Path, Query} import akka.http.scaladsl.server.Directives._ import akka.http.scaladsl.server.Route import cats.instances.future._ import cats.syntax.functor._ import com.bot4s.telegram.api.declarative.{Callbacks, Commands} import com.bot4s.telegram.api.{AkkaDefaults, GameManager, Payload} import com.bot4s.telegram.future.Polling import com.bot4s.telegram.methods.SendGame import scala.concurrent.Future class SelfHosted2048Bot(token: String, gameManagerHost: String) extends ExampleBot(token) with Polling with AkkaDefaults with Callbacks[Future] with GameManager with Commands[Future] { override val port: Int = 8080 val Play2048 = "play_2048" onCommand(Play2048 or "2048" or "start") { implicit msg => request( SendGame(msg.source, Play2048) ).void } onCallbackQuery { implicit cbq => val acked = cbq.gameShortName.collect { case Play2048 => val payload = Payload.forCallbackQuery(gameManagerHost) val url = Uri(gameManagerHost) .withPath(Path(s"/$Play2048/index.html")) .withQuery(Query("payload" -> payload.base64Encode)) ackCallback(url = Some(url.toString())) } acked.getOrElse(ackCallback()).void } override def routes: Route = super.routes ~ gameManagerRoute ~ { pathPrefix(Play2048) { getFromResourceDirectory(Play2048) } } }
Example 17
Source File: GitHubHosted2048Bot.scala From telegram with Apache License 2.0 | 5 votes |
import akka.http.scaladsl.model.Uri import akka.http.scaladsl.model.Uri.{Path, Query} import akka.http.scaladsl.model.headers.{HttpOrigin, HttpOriginRange} import ch.megard.akka.http.cors.scaladsl.model.{HttpHeaderRange, HttpOriginMatcher} import akka.http.scaladsl.server.Directives._ import akka.http.scaladsl.server.Route import cats.instances.future._ import cats.syntax.functor._ import ch.megard.akka.http.cors.scaladsl.CorsDirectives.cors import ch.megard.akka.http.cors.scaladsl.settings.CorsSettings import com.bot4s.telegram.api.declarative.{Callbacks, Commands} import com.bot4s.telegram.api.{GameManager, Payload} import com.bot4s.telegram.future.Polling import com.bot4s.telegram.methods.SendGame import scala.concurrent.Future class GitHubHosted2048Bot(token: String, gameManagerHost: String) extends AkkaExampleBot(token) with Polling with Commands[Future] with Callbacks[Future] with GameManager { override val port: Int = 8080 val Play2048 = "play_2048" val GitHubPages = Uri("https://mukel.github.io") onCommand(Play2048 or "2048" or "start") { implicit msg => request( SendGame(msg.source, Play2048) ).void } onCallbackQuery { implicit cbq => val acked = cbq.gameShortName.collect { case Play2048 => val payload = Payload.forCallbackQuery(gameManagerHost) val url = GitHubPages .withPath(Path(s"/$Play2048/index.html")) .withQuery(Query("payload" -> payload.base64Encode)) ackCallback(url = Some(url.toString())) } acked.getOrElse(ackCallback()).void } // Enable CORS for GitHub Pages. // Allows GitHub Pages to call cross-domain getScores and setScore. private val allowGitHub = CorsSettings.defaultSettings .withAllowedOrigins(HttpOriginMatcher(HttpOrigin(GitHubPages.toString()))) override def routes: Route = super.routes ~ cors(allowGitHub) { gameManagerRoute } }
Example 18
Source File: package.scala From wix-http-testkit with MIT License | 5 votes |
package com.wix.e2e.http.client import java.net.URLEncoder import akka.http.scaladsl.model.Uri import akka.http.scaladsl.model.Uri.Path import com.wix.e2e.http.BaseUri package object internals { implicit class `BaseUri --> akka.Uri`(private val u: BaseUri) extends AnyVal { def asUri: Uri = asUriWith("") def asUriWith(relativeUrl: String): Uri = if (relativeUrl.contains('?')) urlWithoutParams(relativeUrl).withRawQueryString( extractParamsFrom(relativeUrl) ) else urlWithoutParams(relativeUrl) private def fixPath(url: Option[String]) = { url.map( _.trim ) .map( u => s"/${u.stripPrefix("/")}" ) .filterNot( _.equals("/") ) .map( Path(_) ) .getOrElse( Path.Empty ) } private def buildPath(context: Option[String], relativePath: Option[String]) = { val c = fixPath(context) val r = fixPath(relativePath) c ++ r } private def urlWithoutParams(relativeUrl: String) = Uri(scheme = "http").withHost(u.host) .withPort(u.port) .withPath( buildPath(u.contextRoot, Option(extractPathFrom(relativeUrl))) ) private def extractPathFrom(relativeUrl: String) = relativeUrl.split('?').head private def extractParamsFrom(relativeUrl: String) = rebuildAndEscapeParams(relativeUrl.substring(relativeUrl.indexOf('?') + 1)) private def rebuildAndEscapeParams(p: String) = p.split("&") .map( _.split("=") ) .map( { case Array(k, v) => s"$k=${URLEncoder.encode(v, "UTF-8")}" case Array(k) => k } ) .mkString("&") } }
Example 19
Source File: MediaServer.scala From wix-http-testkit with MIT License | 5 votes |
package com.wix.e2e.http.examples import akka.http.scaladsl.model.HttpMethods.{GET, PUT} import akka.http.scaladsl.model.MediaTypes.`image/png` import akka.http.scaladsl.model.StatusCodes.NotFound import akka.http.scaladsl.model.Uri.Path import akka.http.scaladsl.model._ import com.wix.e2e.http.RequestHandler import com.wix.e2e.http.client.extractors._ import com.wix.e2e.http.server.WebServerFactory.aMockWebServerWith import scala.collection.concurrent.TrieMap class MediaServer(port: Int, uploadPath: String, downloadPath: String) { private val mockWebServer = aMockWebServerWith( { case HttpRequest(PUT, u, headers, entity, _) if u.path.tail == Path(uploadPath) => handleMediaPost(u, headers.toList, entity) case HttpRequest(GET, u, headers, _, _) if u.path.tail.toString().startsWith(downloadPath) => handleMediaGet(u, headers.toList) } : RequestHandler).onPort(port) .build.start() def stop() = mockWebServer.stop() private def handleMediaPost(uri: Uri, headers: List[HttpHeader], entity: HttpEntity): HttpResponse = { val fileName = headers.find( _.name == "filename").map( _.value ).orElse( uri.query().toMap.get("f") ).get val media = entity.extractAsBytes files.put(fileName, media) HttpResponse() } private def handleMediaGet(uri: Uri, headers: List[HttpHeader]): HttpResponse = { val fileName = uri.path.reverse .head.toString .stripPrefix("/") files.get(fileName) .map( i => HttpResponse(entity = HttpEntity(`image/png`, i)) ) .getOrElse( HttpResponse(status = NotFound) ) } private val files = TrieMap.empty[String, Array[Byte]] }
Example 20
Source File: CloudFrontSignerTests.scala From openwhisk with Apache License 2.0 | 5 votes |
package org.apache.openwhisk.core.database.s3 import akka.http.scaladsl.model.Uri.Path import com.typesafe.config.ConfigFactory import java.time.Instant import org.apache.openwhisk.core.ConfigKeys import org.apache.openwhisk.core.database.s3.S3AttachmentStoreProvider.S3Config import org.junit.runner.RunWith import org.scalatest.junit.JUnitRunner import org.scalatest.{FlatSpec, Matchers, OptionValues} import pureconfig._ import pureconfig.generic.auto._ @RunWith(classOf[JUnitRunner]) class CloudFrontSignerTests extends FlatSpec with Matchers with OptionValues { val qt = "\"\"\"" val privateKey = """-----BEGIN RSA PRIVATE KEY----- |MIIBPAIBAAJBAOY+Q7vyH1SnCUoFIpzqmZe1TNCxiE6zuiMRmjuJqiAzQWdb5hEA |ZaC+f7Lcu53IvczZR0KsP4JndzG23rVg/y0CAwEAAQJBAMK+F3x4ppdrUSgSf9xJ |cfAnoPlDsA8hZWcUFGgXYJYqKYw3NqoYG5fwyZ7xrwdMhpbdgD++nsBC/JMwUhEB |h+ECIQDzj5Tbd7WvfaKGjozwQgHA9u3f53kxCWovpFEngU6VNwIhAPIAkAPnzuDr |q3cEyAbM49ozjyc6/NOV6QK65HQj1gC7AiBrax/Ty3At/dL4VVaDgBkV6dHvtj8V |CXnzmRzRt43Y8QIhAIzrvPE5RGP/eEqHUz96glhm276Zf+5qBlTbpfrnf0/PAiEA |r1vFsvC8+KSHv7XGU1xfeiHHpHxEfDvJlX7/CxeWumQ= |-----END RSA PRIVATE KEY----- |""".stripMargin val keyPairId = "OPENWHISKISFUNTOUSE" val configString = s"""whisk { | s3 { | bucket = "openwhisk-test" | prefix = "dev" | cloud-front-config { | domain-name = "foo.com" | key-pair-id = "$keyPairId" | private-key = $qt$privateKey$qt | timeout = 10 m | } | } |}""".stripMargin behavior of "CloudFront config" it should "generate a signed url" in { val config = ConfigFactory.parseString(configString).withFallback(ConfigFactory.load()) val s3Config = loadConfigOrThrow[S3Config](config, ConfigKeys.s3) val signer = CloudFrontSigner(s3Config.cloudFrontConfig.get) val expiration = Instant.now().plusSeconds(s3Config.cloudFrontConfig.get.timeout.toSeconds) val uri = signer.getSignedURL("bar") val query = uri.query() //A signed url is of format //https://<domain-name>/<object key>?Expires=xxx&Signature=xxx&Key-Pair-Id=xxx uri.scheme shouldBe "https" uri.path.tail shouldBe Path("bar") query.get("Expires") shouldBe Some(expiration.getEpochSecond.toString) query.get("Signature") shouldBe defined query.get("Key-Pair-Id").value shouldBe keyPairId } }
Example 21
Source File: CacheRulesV1Spec.scala From rokku with Apache License 2.0 | 5 votes |
package com.ing.wbaa.rokku.proxy.cache import akka.actor.ActorSystem import akka.http.scaladsl.model.Uri.Path import akka.http.scaladsl.model.{ HttpMethod, HttpMethods, HttpRequest, Uri } import com.ing.wbaa.rokku.proxy.config.StorageS3Settings import com.ing.wbaa.rokku.proxy.data.RequestId import com.ing.wbaa.rokku.proxy.handler.parsers.RequestParser import org.scalatest.diagrams.Diagrams import org.scalatest.wordspec.AnyWordSpec class CacheRulesV1Spec extends AnyWordSpec with Diagrams with CacheRulesV1 with RequestParser { private implicit val id = RequestId("testRequestId") val system: ActorSystem = ActorSystem.create("test-system") override val storageS3Settings: StorageS3Settings = new StorageS3Settings(system.settings.config) { override val storageS3Authority: Uri.Authority = Uri.Authority(Uri.Host("1.2.3.4"), 1234) } override def getMaxEligibleCacheObjectSizeInBytes(implicit id: RequestId): Long = 5242880L override def getEligibleCachePaths(implicit id: RequestId): Array[String] = "/home/,/test/".trim.split(",") override def getHeadEnabled(implicit id: RequestId): Boolean = true private val uri = Uri("http", Uri.Authority(Uri.Host("1.2.3.4")), Path(""), None, None) private val methods = Seq(HttpMethods.GET, HttpMethods.PUT, HttpMethods.POST, HttpMethods.DELETE, HttpMethods.HEAD) "Cache rules v1 set isEligibleToBeCached " should { methods.foreach { method => testIsEligibleToBeCached(method, "/home/test", HttpRequest.apply(method = method, uri = uri.copy(path = Path("/home/test")))) testIsEligibleToBeCached(method, "/home2/test", HttpRequest.apply(method = method, uri = uri.copy(path = Path("/home2/test")))) testIsEligibleToBeCached(method, "/test/abc", HttpRequest.apply(method = method, uri = uri.copy(path = Path("/test/abc")))) testIsEligibleToBeCached(method, "/testtest/test", HttpRequest.apply(method = method, uri = uri.copy(path = Path("/testtest/test")))) } } private def testIsEligibleToBeCached(method: HttpMethod, path: String, request: HttpRequest): Unit = { method match { case HttpMethods.GET | HttpMethods.HEAD if storageS3Settings.eligibleCachePaths.exists(path.startsWith) => s"for method=$method and path=$path to true" in { assert(isEligibleToBeCached(request)) } case _ => s"for method=$method and path=$path to false" in { assert(!isEligibleToBeCached(request)) } } } "Cache rules v1 set isEligibleToBeInvalidated" should { methods.foreach { method => val request = HttpRequest.apply(method = method, uri) method match { case HttpMethods.POST | HttpMethods.PUT | HttpMethods.DELETE => s"for method=$method to true" in { assert(isEligibleToBeInvalidated(request)) } case _ => s"for method=$method to false" in { assert(!isEligibleToBeInvalidated(request)) } } } } }
Example 22
Source File: S3Request.scala From rokku with Apache License 2.0 | 5 votes |
package com.ing.wbaa.rokku.proxy.data import akka.http.scaladsl.model.RemoteAddress.Unknown import akka.http.scaladsl.model.Uri.Path import akka.http.scaladsl.model.{ HttpMethod, MediaType, MediaTypes, RemoteAddress } import com.ing.wbaa.rokku.proxy.util.S3Utils import com.typesafe.scalalogging.LazyLogging case class S3Request( credential: AwsRequestCredential, s3BucketPath: Option[String], s3Object: Option[String], accessType: AccessType, clientIPAddress: RemoteAddress = Unknown, headerIPs: HeaderIPs = HeaderIPs(), mediaType: MediaType = MediaTypes.`text/plain` ) { def userIps: UserIps = UserIps(clientIPAddress, headerIPs) } object S3Request extends LazyLogging { def apply(credential: AwsRequestCredential, path: Path, httpMethod: HttpMethod, clientIPAddress: RemoteAddress, headerIPs: HeaderIPs, mediaType: MediaType): S3Request = { val pathString = path.toString() val s3path = S3Utils.getS3PathWithoutBucketName(pathString) val s3Object = S3Utils.getS3FullObjectPath(pathString) val accessType = httpMethod.value match { case "GET" => Read(httpMethod.value) case "HEAD" => Head(httpMethod.value) case "PUT" => Put(httpMethod.value) case "POST" => Post(httpMethod.value) case "DELETE" => Delete(httpMethod.value) case _ => logger.debug("HttpMethod not supported") NoAccess } S3Request(credential, s3path, s3Object, accessType, clientIPAddress, headerIPs, mediaType) } }
Example 23
Source File: HydraDirectives.scala From hydra with Apache License 2.0 | 5 votes |
package hydra.core.http import akka.http.scaladsl.marshalling.ToResponseMarshallable import akka.http.scaladsl.model.StatusCode import akka.http.scaladsl.model.Uri.Path import akka.http.scaladsl.model.headers.Location import akka.http.scaladsl.server._ import hydra.common.config.ConfigSupport import scala.concurrent.Promise trait HydraDirectives extends Directives with ConfigSupport { def imperativelyComplete(inner: ImperativeRequestContext => Unit): Route = { ctx: RequestContext => val p = Promise[RouteResult]() inner(new ImperativeRequestContextImpl(ctx, p)) p.future } def completeWithLocationHeader[T](status: StatusCode, resourceId: T): Route = extractRequestContext { requestContext => val request = requestContext.request val location = request.uri.withPath(Path("/" + resourceId.toString)) respondWithHeader(Location(location)) { complete(status) } } } trait ImperativeRequestContext { def complete(obj: ToResponseMarshallable): Unit def failWith(error: Throwable): Unit } // an imperative wrapper for request context final class ImperativeRequestContextImpl( val ctx: RequestContext, promise: Promise[RouteResult] ) extends ImperativeRequestContext { private implicit val ec = ctx.executionContext def complete(obj: ToResponseMarshallable): Unit = ctx.complete(obj).onComplete(promise.complete) def failWith(error: Throwable): Unit = ctx.fail(error).onComplete(promise.complete) }