本文整理汇总了Scala中akka.http.scaladsl.model.Uri.Query类的典型用法代码示例。如果您正苦于以下问题:Scala Query类的具体用法?Scala Query怎么用?Scala Query使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Query类的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: TokenResult
//设置package包名称以及导入依赖的类
package io.reco
import scala.concurrent.{ExecutionContext, Future}
import akka.actor.ActorSystem
import akka.http.scaladsl.model.Uri.Query
import akka.http.scaladsl.model._
import akka.http.scaladsl.Http
import akka.stream.Materializer
import akka.http.scaladsl.unmarshalling.Unmarshal
import spray.json.DefaultJsonProtocol._
import spray.json._
final case class TokenResult(access_token: String, token_type: String, expires_in: Long)
object TokenResultJsonSupport {
implicit val tokenFormat = jsonFormat3(TokenResult)
}
class Oauth(conf: Conf) {
private val AUTH_URI = "/v2.9/dialog/oauth"
private val AUTH_TOKEN_URI = "/v2.9/oauth/access_token"
private val params = Map(("client_id", conf.fbId),
("redirect_uri", "http://localhost:8080/callback"))
val uri = Uri(AUTH_URI).withHost(conf.fbUrl).withQuery(Query(params))
def getToken(code: String)(implicit sys: ActorSystem, mat: Materializer, ec: ExecutionContext): Future[JsValue] = {
val token_prams = params ++ Map(
("client_secret", conf.fbSecret),
("code", code))
val httpRequest = HttpRequest(uri = Uri(AUTH_TOKEN_URI).withHost("graph.facebook.com").withQuery(Query(token_prams)))
for {
response <- Http().singleRequest(httpRequest.copy(uri = s"https:${httpRequest.uri}"))
entity <- Unmarshal(response.entity).to[String]
} yield entity.parseJson
}
}
object Oauth {
def apply(conf: Conf): Oauth = new Oauth(conf)
}
示例2: disableUi
//设置package包名称以及导入依赖的类
package net.ruippeixotog.scalafbp.http
import java.net.URLDecoder
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._
import akka.http.scaladsl.model.StatusCodes._
import akka.http.scaladsl.model.Uri
import akka.http.scaladsl.model.Uri.Query
import akka.http.scaladsl.server.Directives._
import spray.json.DefaultJsonProtocol._
import spray.json._
trait UiHttpService {
def disableUi: Boolean
private[this] val dummyUser = "user"
private[this] val dummyUserName = "ScalaFBP Development Environment"
private[this] val dummyToken = "oauthToken"
// format: OFF
lazy val uiRoutes =
if(disableUi) reject
else {
pathPrefix("oauth") {
path("login" / "oauth" / "authorize") {
parameter("redirect_uri") { encodedUri =>
val uri = Uri(URLDecoder.decode(encodedUri, "UTF-8"))
redirect(uri.withQuery(Query("code" -> dummyUser)), Found)
}
} ~
path("authenticate" / dummyUser) {
complete(Map("token" -> dummyToken))
} ~
path("user") {
complete(JsObject(
"name" -> JsString(dummyUserName),
"github" -> JsObject.empty))
}
} ~
pathEndOrSingleSlash { getFromResource("ui/index.html") } ~
getFromResourceDirectory("ui")
}
// format: ON
}
示例3: CanonicalRequest
//设置package包名称以及导入依赖的类
package akka.stream.alpakka.s3.auth
import java.net.URLEncoder
import akka.http.scaladsl.model.Uri.{Path, Query}
import akka.http.scaladsl.model.{HttpHeader, HttpRequest}
// Documentation: http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html
private[alpakka] case class CanonicalRequest(method: String,
uri: String,
queryString: String,
headerString: String,
signedHeaders: String,
hashedPayload: String) {
def canonicalString: String = s"$method\n$uri\n$queryString\n$headerString\n\n$signedHeaders\n$hashedPayload"
}
private[alpakka] object CanonicalRequest {
def from(req: HttpRequest): CanonicalRequest = {
val hashedBody = req.headers.find(_.name == "x-amz-content-sha256").map(_.value).getOrElse("")
CanonicalRequest(
req.method.value,
pathEncode(req.uri.path),
canonicalQueryString(req.uri.query()),
canonicalHeaderString(req.headers),
signedHeadersString(req.headers),
hashedBody
)
}
def canonicalQueryString(query: Query): String =
query.sortBy(_._1).map { case (a, b) => s"${uriEncode(a)}=${uriEncode(b)}" }.mkString("&")
private def uriEncode(str: String) = URLEncoder.encode(str, "utf-8")
def canonicalHeaderString(headers: Seq[HttpHeader]): String = {
val grouped = headers.groupBy(_.lowercaseName())
val combined = grouped.mapValues(_.map(_.value.replaceAll("\\s+", " ").trim).mkString(","))
combined.toList.sortBy(_._1).map { case (k, v) => s"$k:$v" }.mkString("\n")
}
def signedHeadersString(headers: Seq[HttpHeader]): String =
headers.map(_.lowercaseName()).distinct.sorted.mkString(";")
private def pathEncode(path: Path): String =
if (path.isEmpty) "/"
else
path.toString().flatMap {
case ch if "!$&'()*+,;:=".contains(ch) => "%" + Integer.toHexString(ch.toInt).toUpperCase
case other => other.toString
}
}
示例4: getExtendedForecast
//设置package包名称以及导入依赖的类
package com.github.btesila.weather.monitor.accuweather
import akka.actor.ActorSystem
import akka.http.scaladsl.client.RequestBuilding._
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._
import akka.http.scaladsl.model.Uri.Query
import akka.http.scaladsl.model._
import akka.stream.ActorMaterializer
import com.github.btesila.weather.monitor.Fault.{LocationNotSupported, MissingWeatherInformation}
import com.github.btesila.weather.monitor.Settings
import com.github.btesila.weather.monitor.model._
import scala.concurrent.Future
def getExtendedForecast(locationKey: String): Future[ExtendedForecast] = {
val extendedForecastUri = Uri(settings.ExtendedForecastUri)
val uri = extendedForecastUri.copy(path = extendedForecastUri.path / locationKey).withQuery(Query("metric" -> "true"))
for {
resp <- send(Get(uri))
resp <- expect(resp, StatusCodes.OK, MissingWeatherInformation)
extendedForecast <- unmarshal[ExtendedForecast](resp)
} yield extendedForecast
}
}
object AccuWeatherClient {
def apply()(implicit as: ActorSystem, mat: ActorMaterializer) = new AccuWeatherClient {
override implicit val materializer: ActorMaterializer = mat
override implicit val system: ActorSystem = as
}
}
示例5: CanonicalRequest
//设置package包名称以及导入依赖的类
package edu.goldlok.minio_scala.auth
import akka.http.scaladsl.model.{HttpHeader, HttpRequest}
import akka.http.scaladsl.model.Uri.{Path, Query}
import java.net.URLEncoder
case class CanonicalRequest(method: String, uri: String,
queryString: String,
headerString: String,
signedHeaders: String,
hashedPayload: String) {
def canonicalString: String = {
s"$method\n$uri\n$queryString\n$headerString\n\n$signedHeaders\n$hashedPayload"
}
}
object CanonicalRequest {
private[this] val content_sha256 = "x-amz-content-sha256"
def from(req: HttpRequest): CanonicalRequest = {
val hashedBody = req.headers.find(_.name == content_sha256).map(_.value).getOrElse("")
CanonicalRequest(
req.method.value,
preprocessPath(req.uri.path),
canonicalQueryString(req.uri.query()),
canonicalHeaderString(req.headers),
signedHeadersString(req.headers),
hashedBody
)
}
def canonicalQueryString(query: Query): String = {
query.sortBy(_._1).map { case (a, b) => s"${uriEncode(a)}=${uriEncode(b)}" }.mkString("&")
}
def uriEncode(str: String): String = URLEncoder.encode(str, "utf-8")
def preprocessPath(path: Path): String = {
uriEncode(path.toString()).replace(":", "%3A").replace("%2F", "/")
}
def canonicalHeaderString(headers: Seq[HttpHeader]): String = {
val grouped = headers.groupBy(_.lowercaseName())
val combined = grouped.mapValues(_.map(_.value.replaceAll("\\s+", " ").trim).mkString(","))
combined.toList.sortBy(_._1).map { case (k, v) => s"$k:$v" }.mkString("\n")
}
def signedHeadersString(headers: Seq[HttpHeader]): String = {
headers.map(_.lowercaseName()).distinct.sorted.mkString(";")
}
}
示例6: host
//设置package包名称以及导入依赖的类
package com.github.notyy.client
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.model.Uri.{Path, Query}
import akka.http.scaladsl.model._
import akka.http.scaladsl.unmarshalling.Unmarshal
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.{Sink, Source}
import com.github.notyy.domain.Product
import com.typesafe.scalalogging.slf4j.StrictLogging
import spray.json.{DefaultJsonProtocol, RootJsonFormat}
import scala.concurrent.{ExecutionContextExecutor, Future}
trait ProductSerializer extends SprayJsonSupport with DefaultJsonProtocol with StrictLogging {
implicit val ProductFormat: RootJsonFormat[Product] = jsonFormat2(Product)
}
trait ProductClient extends ProductSerializer {
protected def host: String
protected def port: Int
implicit val system = ActorSystem("my-system")
implicit val materializer = ActorMaterializer()
implicit val executionContext: ExecutionContextExecutor = system.dispatcher
def queryProductByName(name: String): Future[Option[Product]] = {
val theUri = Uri(path = Path("/product/")).withQuery(Query(Map("name" -> s"$name")))
val source = Source.single(HttpRequest(uri = theUri))
val flow = Http().outgoingConnection(host, port).mapAsync(1) { rs =>
rs.status match {
case StatusCodes.OK => {
Unmarshal(rs.entity).to[Product].map(Some(_))
}
case StatusCodes.NotFound => Future(None)
case _ => Future(None)
}
}
source.via(flow).runWith(Sink.head)
}
}
示例7: HttpRequests
//设置package包名称以及导入依赖的类
package com.bluelabs.s3stream
import scala.concurrent.{ExecutionContext, Future}
import akka.http.scaladsl.marshallers.xml.ScalaXmlSupport._
import akka.http.scaladsl.marshalling.Marshal
import akka.http.scaladsl.model._
import akka.http.scaladsl.model.Uri.Query
import akka.http.scaladsl.model.headers.Host
import akka.util.ByteString
object HttpRequests {
def s3Request(s3Location: S3Location, method: HttpMethod = HttpMethods.GET, uriFn: (Uri => Uri) = identity): HttpRequest = {
HttpRequest(method)
.withHeaders(Host(requestHost(s3Location)))
.withUri(uriFn(requestUri(s3Location)))
}
def initiateMultipartUploadRequest(s3Location: S3Location): HttpRequest = {
s3Request(s3Location, HttpMethods.POST, _.withQuery(Query("uploads")))
}
def getRequest(s3Location: S3Location): HttpRequest = {
s3Request(s3Location)
}
def uploadPartRequest(upload: MultipartUpload, partNumber: Int, payload: ByteString): HttpRequest = {
s3Request(upload.s3Location,
HttpMethods.PUT,
_.withQuery(Query("partNumber" -> partNumber.toString, "uploadId" -> upload.uploadId))
).withEntity(payload)
}
def completeMultipartUploadRequest(upload: MultipartUpload, parts: Seq[(Int, String)])(implicit ec: ExecutionContext): Future[HttpRequest] = {
val payload = <CompleteMultipartUpload>
{
parts.map{case (partNumber, etag) => <Part><PartNumber>{partNumber}</PartNumber><ETag>{etag}</ETag></Part>}
}
</CompleteMultipartUpload>
for {
entity <- Marshal(payload).to[RequestEntity]
} yield {
s3Request(upload.s3Location,
HttpMethods.POST,
_.withQuery(Query("uploadId" -> upload.uploadId))
).withEntity(entity)
}
}
def requestHost(s3Location: S3Location): Uri.Host = Uri.Host(s"${s3Location.bucket}.s3.amazonaws.com")
def requestUri(s3Location: S3Location): Uri = Uri(s"/${s3Location.key}").withHost(requestHost(s3Location)).withScheme("https")
}
示例8: CanonicalRequest
//设置package包名称以及导入依赖的类
package com.bluelabs.akkaaws
import akka.http.scaladsl.model.Uri.Query
import akka.http.scaladsl.model.{HttpHeader, HttpRequest}
// Documentation: http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html
case class CanonicalRequest(method: String, uri: String, queryString: String, headerString: String, signedHeaders: String, hashedPayload: String) {
def canonicalString: String = {
s"$method\n$uri\n$queryString\n$headerString\n\n$signedHeaders\n$hashedPayload"
}
}
object CanonicalRequest {
def from(req: HttpRequest): CanonicalRequest = {
val hashedBody = req.headers.find(_.name == "x-amz-content-sha256").map(_.value()).getOrElse("")
CanonicalRequest(req.method.value,
req.uri.path.toString(),
canonicalQueryString(req.uri.query()),
canonicalHeaderString(req.headers),
signedHeadersString(req.headers),
hashedBody
)
}
def canonicalQueryString(query: Query): String = {
query.sortBy(_._1).map{case (a, b) => s"${uriEncode(a)}=${uriEncode(b)}" }.mkString("&")
}
private def uriEncode(str: String) = {
java.net.URLEncoder.encode(str, "utf-8")
}
def canonicalHeaderString(headers: Seq[HttpHeader]): String = {
val grouped: Map[String, Seq[HttpHeader]] = headers.groupBy(_.lowercaseName())
val combined = grouped.mapValues(_.map(_.value().replaceAll("\\s+", " ").trim).mkString(","))
combined.toList.sortBy(_._1).map{ case (k: String, v: String) => s"$k:$v" }.mkString("\n")
}
def signedHeadersString(headers: Seq[HttpHeader]): String = {
headers.map(_.lowercaseName()).distinct.sorted.mkString(";")
}
}
示例9: QueryTypeFormat
//设置package包名称以及导入依赖的类
package org.yashsriv.json
import scala.util.Try
import akka.http.scaladsl.model.Uri.Query
import spray.json._
import org.yashsriv.models._
import QueryType._, Plot._
trait MovieSupport extends DefaultJsonProtocol {
// Result Format
implicit val movieResultJsonFormat = jsonFormat(MovieResult, "Title", "Year", "Released",
"Director", "Plot", "imdbRating", "imdbId",
"Response", "Error")
implicit object QueryTypeFormat extends RootJsonFormat[QueryType] {
def write(qt: QueryType): JsString = JsString(qt.toString)
def read(value: JsValue): QueryType = value match {
case JsString("movie") ? movie
case JsString("episode") ? episode
case JsString("series") ? series
case _ ? throw new DeserializationException("QueryType Expected")
}
}
implicit object PlotFormat extends RootJsonFormat[Plot] {
def write(plot: Plot): JsString = JsString(plot.toString)
def read(value: JsValue): Plot = value match {
case JsString("short") ? short
case JsString("full") ? full
case _ ? throw new DeserializationException("Plot Expected")
}
}
implicit val movieQueryJsonFormat = jsonFormat(MovieQuery, "t", "type", "y", "plot")
def convertToQuery(mq: MovieQuery): Query = Query(
"t" ? mq.title,
"type" ? mq.qType.getOrElse(movie).toString,
"year" ? mq.year.getOrElse("").toString,
"plot" ? mq.plot.getOrElse(short).toString
)
}
示例10: FacebookClient
//设置package包名称以及导入依赖的类
package ch.becompany.social.facebook
import java.time.Instant
import akka.http.scaladsl.model.Uri.Query
import akka.http.scaladsl.model._
import ch.becompany.http.{CachingSupport, HttpClient, UnmarshallingHttpHandler}
import ch.becompany.social.Status
import com.typesafe.config.ConfigFactory
import scala.concurrent.{ExecutionContext, Future}
import com.typesafe.scalalogging.LazyLogging
object FacebookClient extends HttpClient with FacebookJsonSupport with CachingSupport with LazyLogging {
private val accessToken = ConfigFactory.load.getConfig("scalaSocialFeed.facebook")
private val baseUrl = Uri("https://graph.facebook.com")
private val graphVersion = "v2.8"
private implicit val handler = new UnmarshallingHttpHandler[List[(Instant, Status)]]()
private def getPageFeedUri(pageId: String): Uri = {
Uri("/" + graphVersion + "/" + pageId + "/feed").resolvedAgainst(baseUrl).withQuery(Query.apply(
"limit" -> s"${accessToken.getNumber("limit")}", "access_token" -> s"${accessToken.getString("appId")}|${accessToken.getString("appSecret")}"))
}
def posts(pageId: String)(implicit ec: ExecutionContext): Future[List[(Instant, Status)]] = {
logger.debug("Requesting latest updates from Facebook page. [pageId={}]", pageId)
val header = scala.collection.immutable.Seq(headers.`Accept`(MediaTypes.`application/json`))
req[List[(Instant, Status)]](HttpRequest(uri = getPageFeedUri(pageId), headers = header))
.recover {
case e => logger.error("Error building the Facebook status.", e); List.empty
}
}
}
示例11: WemoConnector
//设置package包名称以及导入依赖的类
package io.tardieu.netwemo.connectors
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.Uri.Query
import akka.http.scaladsl.model.{HttpMethods, HttpRequest, Uri}
import akka.http.scaladsl.unmarshalling.Unmarshal
import akka.stream.ActorMaterializer
import com.typesafe.config.ConfigFactory
import org.slf4j.LoggerFactory
import scala.util.{Failure, Success}
class WemoConnector(implicit val system: ActorSystem) {
private[this] val logger = LoggerFactory.getLogger(getClass)
private[this] implicit val materializer = ActorMaterializer()
private[this] implicit val executionContext = system.dispatcher
private[this] val conf = ConfigFactory.load.getConfig("wemo")
private[this] val wemoHost = conf.getString("host")
private[this] val wemoPort = conf.getInt("port")
def switchOn(device: String): Unit = switchState("on", device)
def switchOff(device: String): Unit = switchState("off", device)
def toggle(device: String): Unit = switchState("toggle", device)
private def switchState(state: String, device: String): Unit = {
val request = HttpRequest(
method = HttpMethods.POST,
uri = Uri(s"http://$wemoHost:$wemoPort/api/device/$device").withQuery(Query("state" -> state))
)
Http().singleRequest(request).onComplete {
case Success(response) =>
val message = Unmarshal(response.entity).to[String]
if (response.status.isFailure()) {
message.foreach(logger.error(s"HTTP error {}: {}", response.status.asInstanceOf[Any], _))
}
else {
logger.debug(
"Switch {} order for {} received with status {}",
state, device, response.status)
logger.trace(
"Switch {} order for {} received with status {}: {}",
state, device, response.status, message)
}
case Failure(e) =>
logger.error("Error contacting the wemo server", e)
}
}
}