• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala Uri类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Scala中akka.http.scaladsl.model.Uri的典型用法代码示例。如果您正苦于以下问题:Scala Uri类的具体用法?Scala Uri怎么用?Scala Uri使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Uri类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。

示例1: 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
} 
开发者ID:ruippeixotog,项目名称:scalafbp,代码行数:46,代码来源:UiHttpService.scala


示例2: MonitoringServer

//设置package包名称以及导入依赖的类
package com.scalaio.http.monitoring

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.ContentTypes._
import akka.http.scaladsl.model.{HttpEntity, HttpResponse, StatusCodes, Uri}
import akka.http.scaladsl.model.StatusCodes._
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server._
import akka.stream.Materializer
import com.typesafe.config.Config
import com.yammer.metrics.HealthChecks
import com.yammer.metrics.core.HealthCheckRegistry
import org.slf4j.LoggerFactory
import play.api.libs.json.{JsArray, Json}

import scala.util.{Failure, Success}
import scala.collection.convert.wrapAsScala._

object MonitoringServer {

  lazy val logger = LoggerFactory.getLogger(getClass)

  def handleHealthchecks(registry: HealthCheckRegistry): Route = {
    path("health") {
      get {
        complete {
          val checks = registry.runHealthChecks
          val payload = JsArray(checks.map {
            case (name, result) =>
              Json.obj(
                "name" -> name,
                "healthy" -> result.isHealthy,
                "message" -> result.getMessage
              )
          }.toSeq)
          val status = if (checks.values().forall(_.isHealthy)) OK else InternalServerError
          HttpResponse(entity = HttpEntity(`application/json`, Json.stringify(payload)), status = status)
        }
      }
    }
  }

  def start(serverConfig: Config, registry: HealthCheckRegistry = HealthChecks.defaultRegistry())
           (implicit system: ActorSystem, materializer: Materializer): Unit = {
    val host = serverConfig.getString("host")
    val port = serverConfig.getInt("port")
    logger.info(s"Starting monitoring server at: $host:$port")

    val routes = handleHealthchecks(registry) ~ redirect(Uri("/health"), StatusCodes.SeeOther)
    import system.dispatcher
    Http()
      .bindAndHandle(routes, host, port).onComplete {
      case Success(Http.ServerBinding(address)) =>
        logger.info(s"Monitoring server started at :$address")
      case Failure(t) =>
        logger.error("Error while trying to start monitoring server", t)
    }
  }
} 
开发者ID:fagossa,项目名称:scalaio_akka,代码行数:61,代码来源:MonitoringServer.scala


示例3: create

//设置package包名称以及导入依赖的类
package akka.stream.alpakka.ironmq

import akka.actor.ActorSystem
import akka.http.scaladsl.model.Uri
import akka.stream.alpakka.ironmq.ConfigIronMqSettings.ConfigConsumerSettings
import akka.stream.alpakka.ironmq.IronMqSettings.ConsumerSettings
import com.typesafe.config.Config

import scala.concurrent.duration.FiniteDuration


  def create(as: ActorSystem): IronMqSettings = apply()(as)
}

object ConfigIronMqSettings {

  class ConfigConsumerSettings(config: Config) extends ConsumerSettings {
    override val bufferMinSize: Int = config.getInt("buffer-min-size")
    override val bufferMaxSize: Int = config.getInt("buffer-max-size")
    override val fetchInterval: FiniteDuration = config.getDuration("fetch-interval").asScala
    override val pollTimeout: FiniteDuration = config.getDuration("poll-timeout").asScala
    override val reservationTimeout: FiniteDuration = config.getDuration("reservation-timeout").asScala
  }

}

class ConfigIronMqSettings(config: Config) extends IronMqSettings {
  override val endpoint: Uri = config.getString("endpoint")
  override val projectId: String = config.getString("credentials.project-id")
  override val token: String = config.getString("credentials.token")

  override def consumerSettings: ConsumerSettings = new ConfigConsumerSettings(config.getConfig("consumer"))
} 
开发者ID:akka,项目名称:alpakka,代码行数:34,代码来源:IronMqSettings.scala


示例4: ScrapingKitReactor

//设置package包名称以及导入依赖的类
package ru.fediq.scrapingkit

import akka.actor.{ActorSystem, Props}
import akka.http.scaladsl.model.Uri
import akka.routing.RoundRobinPool
import com.typesafe.scalalogging.StrictLogging
import net.ceedubs.ficus.Ficus._
import net.ceedubs.ficus.readers.ArbitraryTypeReader._
import ru.fediq.scrapingkit.backend.{FeedExporter, LinksHistory, LinksQueue, PageCache}
import ru.fediq.scrapingkit.model.PageRef
import ru.fediq.scrapingkit.platform._
import ru.fediq.scrapingkit.scraper.Scraper

import scala.util.Try

class ScrapingKitReactor(
  linksQueue: LinksQueue,
  linksHistory: LinksHistory,
  pageCache: PageCache,
  exporter: FeedExporter,
  scrapers: Map[String, Scraper],
  redirectFilter: Option[(PageRef, Uri) => Boolean] = None
)(implicit val system: ActorSystem)
  extends AnyRef with AutoCloseable with StrictLogging {

  val config = system.settings.config.as[ScrapingKitConfig]("scrapingkit")

  val queueingActor = system
    .actorOf(
      Props(new QueueingActor(linksQueue, linksHistory, config))
        .withDispatcher("pinnedDispatcher"),
      "queueing"
    )

  val downloadingActor = system
    .actorOf(
      Props(new DownloadingActor(pageCache, config, redirectFilter)),
      "downloading"
    )

  val scrapingActor = system
    .actorOf(
      RoundRobinPool(config.scrapingThreads, routerDispatcher = "pinnedDispatcher")
        .props(Props(new ScrapingActor(scrapers, exporter, config))),
      "scraping"
    )

  system.registerOnTermination(close())

  override def close() = {
    logger.info("Stopping ScarpingKit Reactor")
    Try(linksQueue.close())
    Try(linksHistory.close())
    Try(pageCache.close())
    Try(exporter.close())
    logger.info("Stopped")
  }
} 
开发者ID:fediq,项目名称:scraping-kit,代码行数:59,代码来源:ScrapingKitReactor.scala


示例5: LinksHistoryFiller

//设置package包名称以及导入依赖的类
package ru.fediq.scrapingkit.tools

import akka.http.scaladsl.model.Uri
import ru.fediq.scrapingkit.backend.LinksHistory

import scala.concurrent.{ExecutionContext, Future}

class LinksHistoryFiller(
  linksHistory: LinksHistory
) {
  def add(uri: Uri)(implicit ec: ExecutionContext): Future[Any] = {
    linksHistory.isKnown(uri).flatMap {
      case true => Future.successful()
      case false => linksHistory.addKnown(uri)
    }
  }

  def fill(uris: Traversable[Uri])(implicit ec: ExecutionContext): Future[Any] = {
    val futures = uris.map(add)
    Future.sequence(futures)
  }
} 
开发者ID:fediq,项目名称:scraping-kit,代码行数:23,代码来源:LinksHistoryFiller.scala


示例6: ScrapingKitReactorTest

//设置package包名称以及导入依赖的类
package ru.fediq.scrapingkit

import java.util.concurrent.TimeUnit

import akka.actor.ActorSystem
import akka.http.scaladsl.model.{HttpMethods, Uri}
import com.codahale.metrics.Slf4jReporter
import com.codahale.metrics.Slf4jReporter.LoggingLevel
import com.typesafe.config.ConfigFactory
import org.scalatest.FlatSpec
import org.slf4j.LoggerFactory
import ru.fediq.scrapingkit.backend.{InMemoryFifoLinksQueue, InMemoryLinksHistory, NoOpFeedExporter, NoOpPageCache}
import ru.fediq.scrapingkit.model.PageRef
import ru.fediq.scrapingkit.scraper.HtmlCrawlingScraper
import ru.fediq.scrapingkit.util.Metrics

class ScrapingKitReactorTest extends FlatSpec {

  "Reactor" should "crawl something" in {
    val scraperName = "crawl"
    val scrapers = Map(scraperName -> new HtmlCrawlingScraper(scraperName))

    val config = ConfigFactory.load()
    implicit val system = ActorSystem("reactor-test", config)

    val linksQueue = new InMemoryFifoLinksQueue()
    val linksHistory = new InMemoryLinksHistory()
    val pageCache = new NoOpPageCache()
    val exporter = new NoOpFeedExporter()

    val reactor = new ScrapingKitReactor(linksQueue, linksHistory, pageCache, exporter, scrapers)
    linksQueue.enqueue(PageRef(Uri("http://quotes.toscrape.com/"), HttpMethods.GET, scraperName))

    Slf4jReporter
      .forRegistry(Metrics.metricRegistry)
      .withLoggingLevel(LoggingLevel.INFO)
      .outputTo(LoggerFactory.getLogger("METRICS"))
      .convertDurationsTo(TimeUnit.MILLISECONDS)
      .convertRatesTo(TimeUnit.SECONDS)
      .build()
      .start(10, TimeUnit.SECONDS)

    Thread.sleep(10000)

    reactor.close()
  }
} 
开发者ID:fediq,项目名称:scraping-kit,代码行数:48,代码来源:ScrapingKitReactorTest.scala


示例7: PageRef

//设置package包名称以及导入依赖的类
package ru.fediq.scrapingkit.model

import akka.http.scaladsl.model.{HttpMethod, HttpMethods, Uri}

case class PageRef(
  uri: Uri,
  method: HttpMethod,
  scraperName: String,
  depth: Double = 1.0,
  context: Map[String, String] = Map.empty,
  redirectsChain: List[Uri] = Nil
) {
  def lastUri = redirectsChain.headOption.getOrElse(uri)

  def redirectSteps = if (redirectsChain.isEmpty) Nil else uri :: redirectsChain.tail

  def chain(nextLocation: Uri) = copy(
    method = HttpMethods.GET,
    redirectsChain = nextLocation :: redirectsChain
  )
} 
开发者ID:fediq,项目名称:scraping-kit,代码行数:22,代码来源:PageRef.scala


示例8: DownloadRequest

//设置package包名称以及导入依赖的类
package ru.fediq.scrapingkit.scraper

import akka.http.scaladsl.model.{HttpMethod, HttpMethods, Uri}
import ru.fediq.scrapingkit.util.Implicits._
import spray.json._

sealed trait Scraped

case class DownloadRequest(
  uri: Uri,
  scraperName: String,
  context: Map[String, String] = Map.empty,
  method: HttpMethod = HttpMethods.GET,
  depthInc: Double = 1.0
) extends Scraped

trait ScrapedEntity extends Scraped {
  def dump: String
}

case class MapScrapedEntity(map: Map[String, Any]) extends ScrapedEntity with DefaultJsonProtocol {
  override def dump = map.mapToJson.compactPrint
}

abstract class JsonScrapedEntity[T](format: JsonFormat[T]) extends ScrapedEntity {
  self: T =>
  override def dump = {
    self.asInstanceOf[T].toJson(format).compactPrint
  }
}

trait PrintableScrapedEntity extends ScrapedEntity {
  override def dump = toString
} 
开发者ID:fediq,项目名称:scraping-kit,代码行数:35,代码来源:Scraped.scala


示例9: RmqConstants

//设置package包名称以及导入依赖的类
package ru.fediq.scrapingkit.backend

import akka.http.scaladsl.model.{HttpMethods, Uri}
import ru.fediq.scrapingkit.model.PageRef

object RmqConstants {
  val connectorActorName = "links-queue"
  val channelActorName = "rmqchannel"
  val channelActorPath = "/user/links-queue/rmqchannel"

  case class SerializedPageRef(
    uri: String,
    method: String,
    scraper: String,
    depth: Double,
    context: Map[String, String]
  ) {
    def deserialize(): PageRef = PageRef(
      Uri(uri),
      HttpMethods.getForKey(method).getOrElse(HttpMethods.GET),
      scraper,
      depth,
      context
    )
  }

} 
开发者ID:fediq,项目名称:scraping-kit,代码行数:28,代码来源:RmqConstants.scala


示例10: AkkaBoom

//设置package包名称以及导入依赖的类
package com.github.basking2.sdsai.akka

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.{HttpMethods, HttpRequest, Uri}
import akka.stream.{ActorMaterializer, OverflowStrategy}
import akka.stream.scaladsl.Source

import scala.concurrent.Await
import scala.concurrent.duration._
import scala.util.{Failure, Success}


object AkkaBoom {

  def main(args: Array[String]):Unit = {
    implicit val actorSystem = ActorSystem("akkaboom")
    implicit val materializer = ActorMaterializer()
    implicit val dispatcher = actorSystem.dispatcher

    val uri = Uri("http://www.nhptv.org/wild/images/moosenpsJacobWFrank.jpg")
    val src = Source(0 to 100)

    val httpFlow = Http().cachedHostConnectionPool[Int](uri.authority.host.toString(), uri.authority.port)

    val f = src.map { i =>
      val req = HttpRequest(HttpMethods.GET, uri.path.toString())

      (req, i)
    }
      .via(httpFlow)
      .runForeach {
        case (Success(resp), i) =>
          Await.ready(resp.entity.discardBytes().future(), 10 seconds)
        case (Failure(t), i) =>
          t.printStackTrace()
      }

    Await.ready(f, 1 minute)

    Await.ready(actorSystem.terminate(), 1 minute)

    println("OK")
  }

} 
开发者ID:basking2,项目名称:akkaboom,代码行数:47,代码来源:AkkaBoom.scala


示例11: WolframServiceImpl

//设置package包名称以及导入依赖的类
package me.alexray.wolfram.impl

import java.net.URLEncoder

import akka.NotUsed
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.{HttpRequest, Uri}
import akka.http.scaladsl.unmarshalling.Unmarshal
import akka.stream.Materializer
import akka.util.ByteString
import com.lightbend.lagom.scaladsl.api.ServiceCall
import me.alexray.wolfram.api.WolframService
import play.api.Configuration

import scala.concurrent.{ExecutionContext, Future}


class WolframServiceImpl(config: Configuration)
                        (implicit system: ActorSystem, mat: Materializer, ec: ExecutionContext)
  extends WolframService
{

  val appID = config.underlying.getString("wolfram.appid")
  val apiUrl = s"http://api.wolframalpha.com/v2/"


  override def query(q: String): ServiceCall[NotUsed, String] = ServiceCall { _ =>

    val url = apiUrl + s"query?appid=$appID&input=" + URLEncoder.encode(q, "UTF-8")

    for {
      response <- Http().singleRequest(HttpRequest(uri = Uri(url)))
      if response.status.isSuccess()
      data <- Unmarshal(response).to[String]
    } yield data

  }

  override def simple(q: String): ServiceCall[NotUsed, Array[Byte]] = ServiceCall { _ =>

    println(s"quetions = '$q'")

    val url = apiUrl + s"simple?appid=$appID&input=" +  URLEncoder.encode(q, "UTF-8").replace("+", "%20")

    println(s"url = '$url'")

    for {
      response <- Http().singleRequest(HttpRequest(uri = Uri(url)))
      if response.status.isSuccess()
      bytes <- Unmarshal(response).to[ByteString]
    } yield {
      println(s"received image ${bytes.size} bytes long")
      bytes.toArray
    }

  }
} 
开发者ID:AlexanderRay,项目名称:lagom-on-kube,代码行数:59,代码来源:WolframServiceImpl.scala


示例12: Cert

//设置package包名称以及导入依赖的类
package run.cosy.crypto

import java.math.BigInteger
import java.security.KeyFactory
import java.security.interfaces.RSAPublicKey
import java.security.spec.RSAPublicKeySpec

import akka.http.scaladsl.model.Uri
import org.w3.banana.{PointedGraph, RDF, RDFOps, binder}
import org.w3.banana.binder.{PGBinder, RecordBinder, ToPG}

object Cert {
   def binderWithName[Rdf<:RDF](u: Uri)(implicit ops: RDFOps[Rdf]): PGBinder[Rdf, RSAPublicKey] =
      new Cert[Rdf].binderRootName(u.toString())
   
   def binder[Rdf<:RDF](implicit ops: RDFOps[Rdf]): PGBinder[Rdf, RSAPublicKey] =  new Cert[Rdf].binder

}

class Cert[Rdf<:RDF](implicit ops: RDFOps[Rdf]) {
   import org.w3.banana.{CertPrefix, RDF, RDFOps, binder}
   implicit val recordBinder = org.w3.banana.binder.RecordBinder[Rdf](ops)
   val cert = CertPrefix[Rdf]
   import org.w3.banana.binder._
   import recordBinder._

   implicit val rsaClassUri = recordBinder.classUrisFor[RSAPublicKey](cert.RSAPublicKey)
   val factory = KeyFactory.getInstance("RSA")
   val exponent = property[BigInteger](cert.exponent)
   val modulus = property[Array[Byte]](cert.modulus)
   
   val binder: PGBinder[Rdf, RSAPublicKey] =
      pgb[RSAPublicKey](modulus, exponent)(
         (m: Array[Byte], e: BigInteger) => factory.generatePublic(new RSAPublicKeySpec(new BigInteger(m), e)).asInstanceOf[RSAPublicKey],
         (key: RSAPublicKey) => Some((key.getModulus.toByteArray, key.getPublicExponent))
      ).withClasses(rsaClassUri)
   
   def binderRootName(uri: String)  =
      pgbWithConstId[RSAPublicKey](uri)(modulus, exponent)(
         (m: Array[Byte], e: BigInteger) => factory.generatePublic(new RSAPublicKeySpec(new BigInteger(m), e)).asInstanceOf[RSAPublicKey],
         (key: RSAPublicKey) => Some((key.getModulus.toByteArray, key.getPublicExponent))
      ).withClasses(rsaClassUri)
} 
开发者ID:read-write-web,项目名称:solid-client,代码行数:44,代码来源:Cert.scala


示例13: signRequest

//设置package包名称以及导入依赖的类
package im.actor.server.file.local

import java.net.URLEncoder

import akka.actor.ActorSystem
import akka.http.scaladsl.model.{ HttpMethod, Uri }
import im.actor.acl.ACLBase
import org.apache.commons.codec.digest.DigestUtils.sha256Hex
import org.apache.commons.codec.digest.HmacUtils

trait RequestSigning extends ACLBase {

  private val urlEncode: String ? String = URLEncoder.encode(_, "UTF-8")

  def signRequest(httpVerb: HttpMethod, uri: Uri, secret: String): Uri =
    uri.withQuery(("signature" ? calculateSignature(httpVerb, uri, secret)) +: uri.query())

  def calculateSignature(httpVerb: HttpMethod, uri: Uri)(implicit system: ActorSystem): String =
    calculateSignature(httpVerb, uri, secretKey())

  def calculateSignature(httpVerb: HttpMethod, uri: Uri, secret: String): String = {
    val resourcePath = uri.path
    val canonicalQueryString = uri.query() sortBy (_._1) map {
      case (name, value) ?
        s"${urlEncode(name)}=${urlEncode(value)}"
    } mkString "&"

    val canonicalRequest =
      s"""$httpVerb
         |$resourcePath
         |$canonicalQueryString""".stripMargin

    HmacUtils.hmacSha256Hex(secret, sha256Hex(canonicalRequest))
  }
} 
开发者ID:wex5,项目名称:dangchat-server,代码行数:36,代码来源:RequestSigning.scala


示例14: ConnectionActor

//设置package包名称以及导入依赖的类
package com.github.pvoznenko.newPackage

import akka.actor.{Actor, Props}
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.HttpMethods.GET
import akka.http.scaladsl.model.{HttpRequest, HttpResponse, Uri}

import scala.concurrent.Future
import scala.io.StdIn


class ConnectionActor extends Actor {

  case object StartConnection

  case class ConnectWebsite(s: String)

  override def receive = {
    case StartConnection => {
      val requestHandler: HttpRequest => Future[HttpResponse] = {
        case HttpRequest(GET, Uri.Path("/pintpin"), _, _, _) => {

          val c = context.system.actorOf(Props[RequestHandler], "child1")

          val a = c ? OneSlash
          a map { p =>
            p
          }
        }
        case HttpRequest(GET, Uri.Path("/ping"), _, _, _) =>
          Future {
            HttpResponse(entity = "PONG!")
          }
        case HttpRequest(GET, Uri.Path("/crash"), _, _, _) =>
          sys.error("BOOM!")

      }


      val bindingFuture = Http().bindAndHandleAsync(requestHandler, "localhost", 8080)
      println(s"Server online at http://localhost:8080/\nPress RETURN to stop...")
      StdIn.readLine() // let it run until user presses return
      bindingFuture
        .flatMap(_.unbind()) // trigger unbinding from the port
        .onComplete(_ => system.shutdown()) // and shutdown when done

    }
  }
} 
开发者ID:aarashfeyzi,项目名称:AkkaStuff,代码行数:50,代码来源:ConnectionActor.scala


示例15: QueueRouter

//设置package包名称以及导入依赖的类
package reactive.queue.router

import akka.actor.{Actor, Props}
import akka.http.scaladsl.model.Uri
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.{Sink, Source}
import io.scalac.amqp.Connection

object QueueRouter {
  def props(queueConnection: Connection, queueSubscription: QueueSubscription, queuePrefetchCount: Int): Props = {
    Props(classOf[QueueRouter], queueConnection, queueSubscription, queuePrefetchCount)
  }
}

class QueueRouter(queueConnection: Connection, queueSubscription: QueueSubscription, queuePrefetchCount: Int) extends Actor {
  implicit val materlizer = ActorMaterializer()
  val queuePublisher = QueuePublisher(queueConnection, queueSubscription.queueName, queuePrefetchCount).publisher
  val queueSubscriber = QueueSubscriber.props(queueConnection, queueSubscription.queueName, Uri(queueSubscription.queueSubscriberUrl))
  Source.fromPublisher(queuePublisher).map(_.message).runWith(Sink.actorSubscriber(queueSubscriber))

  def receive = Actor.emptyBehavior
} 
开发者ID:objektwerks,项目名称:reactive.queue.router,代码行数:23,代码来源:QueueRouter.scala


示例16: getOrders

//设置package包名称以及导入依赖的类
package com.example.order.client

import akka.http.scaladsl.HttpExt
import akka.http.scaladsl.model._
import akka.http.scaladsl.model.headers.OAuth2BearerToken
import akka.http.scaladsl.model.{DateTime, Uri}
import akka.stream.{ActorMaterializer, ActorMaterializerSettings, Materializer}
import com.example.Orders.OrderResponse
import com.example.order.client.OrderClientImpl.OrderClientConfig

import scala.concurrent.Future

trait OrderClient {
  def getOrders(page:Int = 1, since:DateTime)(implicit fm: Materializer): Future[HttpResponse]
}

class OrderClientImpl(orderClientConfig: OrderClientConfig, http:HttpExt) extends OrderClient{

  val ordersUri:Uri = s"https://sandbox.epages.com/rs/shops/${orderClientConfig.shopId}/orders?resultsPerPage=50"

  override def getOrders(page: Int=1, since: DateTime)(implicit fm: Materializer): Future[HttpResponse] = {

    val auth = headers.Authorization(OAuth2BearerToken(orderClientConfig.token))
    val accept = headers.Accept(MediaTypes.`application/json`)
    var uri = ordersUri + s"&page=$page"
    since match {
      case DateTime.MinValue =>
      case _ =>
        val createdAfter = since.toIsoDateTimeString()
        uri += s"&createdAfter=$createdAfter"
    }
    http.singleRequest(HttpRequest(HttpMethods.GET, uri, List(auth, accept)))
  }
}

object OrderClientImpl {
  case class OrderClientConfig(token:String, shopId:String)
} 
开发者ID:mduesterhoeft,项目名称:hack16-order-geo-statistics-akka-scala,代码行数:39,代码来源:OrderClient.scala


示例17: ConfigServiceResolver

//设置package包名称以及导入依赖的类
package csw.services.config.client.internal

import akka.http.scaladsl.model.Uri
import csw.services.config.client.commons.{ConfigClientLogger, ConfigServiceConnection}
import csw.services.location.scaladsl.LocationService

import scala.async.Async._
import scala.concurrent.Future
import scala.concurrent.duration.DurationDouble


class ConfigServiceResolver(locationService: LocationService, actorRuntime: ActorRuntime)
    extends ConfigClientLogger.Simple {

  import actorRuntime.ec

  def uri: Future[Uri] = async {
    val location = await(locationService.resolve(ConfigServiceConnection.value, 5.seconds)).getOrElse(
      throw new RuntimeException(
        s"config service connection=${ConfigServiceConnection.value.name} can not be resolved"
      )
    )
    Uri(location.uri.toString)
  }
} 
开发者ID:tmtsoftware,项目名称:csw-prod,代码行数:26,代码来源:ConfigServiceResolver.scala


示例18: Config

//设置package包名称以及导入依赖的类
package com.xantoria.auditorium.config

import scala.concurrent.duration.{Duration, FiniteDuration}

import akka.http.scaladsl.model.Uri
import com.typesafe.config.{Config => TypesafeConfig, ConfigFactory}

class Config {
  private val cfg: TypesafeConfig = ConfigFactory.load()
  val interface = cfg.getString("api.interface")
  val port = cfg.getInt("api.port")

  val esUri: Uri = {
    val es = cfg.getObject("elasticsearch").toConfig

    Uri(
      scheme = es.getString("scheme"),
      authority = Uri.Authority(
        host = Uri.NamedHost(es.getString("host")),
        port = es.getInt("port")
      )
    )
  }
  val esIndexPrefix = cfg.getString("elasticsearch.index_prefix")

  // The interval at which to ensure current and future indices have been created
  val createIndexInterval = Duration(
    cfg.getString("elasticsearch.create_index_interval")
  ).asInstanceOf[FiniteDuration]
} 
开发者ID:giftig,项目名称:auditorium,代码行数:31,代码来源:Config.scala


示例19: RichConfigTest

//设置package包名称以及导入依赖的类
package de.choffmeister.microserviceutils

import java.nio.file.Paths

import akka.http.scaladsl.model.Uri
import akka.util.ByteString
import com.typesafe.config.ConfigFactory
import de.choffmeister.microserviceutils.RichConfig._
import org.scalatest.{FlatSpec, Matchers}

import scala.concurrent.duration._

class RichConfigTest extends FlatSpec with Matchers {
  val config = ConfigFactory.parseString(
    """|string = "foo"
       |int = 42
       |finite-duration = 23s
       |path = "/a/b"
       |uri = "http://localhost"
       |byte-string = "dGVzdA=="
       |""".stripMargin)

  "RichConfig" should "get optional string" in {
    config.getOptionalString("string") should be(Some("foo"))
    config.getOptionalString("string2") should be(empty)
  }

  it should "get optional int" in {
    config.getOptionalInt("int") should be(Some(42))
    config.getOptionalInt("int2") should be(empty)
  }

  it should "get finite duration" in {
    config.getFiniteDuration("finite-duration") should be(23.seconds)
  }

  it should "get path" in {
    config.getPath("path") should be(Paths.get("/a/b"))
  }

  it should "get uri" in {
    config.getUri("uri") should be(Uri("http://localhost"))
  }

  it should "get byte string" in {
    config.getByteString("byte-string") should be(ByteString("test"))
  }
} 
开发者ID:choffmeister,项目名称:microservice-utils,代码行数:49,代码来源:RichConfigTest.scala


示例20: AuthenticationHeader

//设置package包名称以及导入依赖的类
package com.ulasakdeniz.hakker.ws

import akka.http.scaladsl.model.{HttpResponse, Uri}

package object auth {

  final case class AuthenticationHeader(
      httpMethod: String,
      uri: Uri,
      consumerKey: String,
      consumerSecret: String,
      tokenOpt: Option[(String, String)] = None
  )

  final case class OAuthInfo(
      consumerKey: String,
      consumerSecret: String,
      requestTokenUri: String,
      accessTokenUri: String,
      authenticationUri: String
  )

  sealed trait OAuthResponse
  sealed trait OAuthSuccessfulResponse extends OAuthResponse
  sealed trait OAuthFailedResponse     extends OAuthResponse

  final case class RedirectionSuccess(httpResponse: HttpResponse, tokens: Map[String, String])
      extends OAuthSuccessfulResponse
  final case class AccessTokenSuccess(tokens: Map[String, String]) extends OAuthSuccessfulResponse

  final case class CallbackFailed(httpResponse: HttpResponse)       extends OAuthFailedResponse
  final case class AuthenticationFailed(httpResponse: HttpResponse) extends OAuthFailedResponse
  final case class TokenFailed(httpResponse: HttpResponse)          extends OAuthFailedResponse
} 
开发者ID:ulasakdeniz,项目名称:hakker,代码行数:35,代码来源:package.scala



注:本文中的akka.http.scaladsl.model.Uri类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala Options类代码示例发布时间:2022-05-23
下一篇:
Scala ScalaObjectMapper类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap