本文整理汇总了Scala中java.net.URI类的典型用法代码示例。如果您正苦于以下问题:Scala URI类的具体用法?Scala URI怎么用?Scala URI使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了URI类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: URIUtilsSpec
//设置package包名称以及导入依赖的类
package com.pygmalios.reactiveinflux.impl
import java.net.URI
import org.junit.runner.RunWith
import org.scalatest.FlatSpec
import org.scalatest.junit.JUnitRunner
@RunWith(classOf[JUnitRunner])
class URIUtilsSpec extends FlatSpec {
behavior of "appendPath"
it should "strip /" in {
assert(URIUtils.appendPath(new URI("http://x/"), "/a").toString == "http://x/a")
}
behavior of "queryToString"
it should "create empty query string" in {
assert(URIUtils.queryToString() == "")
}
it should "create query string with single item" in {
assert(URIUtils.queryToString("a" -> "b") == "?a=b")
}
it should "create query string with two items" in {
assert(URIUtils.queryToString("a" -> "b", "c" -> "d") == "?a=b&c=d")
}
}
示例2: RabbitMQHelper
//设置package包名称以及导入依赖的类
package helper
import java.net.URI
import com.rabbitmq.client._
object RabbitMQHelper {
def setupConnection(rabbitmqUri: String): Connection = {
val factory = new ConnectionFactory()
val uri = new URI(rabbitmqUri)
factory.setUsername(uri.getUserInfo.split(":")(0));
factory.setPassword(uri.getUserInfo.split(":")(1));
factory.setHost(uri.getHost);
factory.setPort(uri.getPort);
factory.setVirtualHost(uri.getPath.substring(1));
val connection = factory.newConnection()
return connection
}
}
示例3: JSONHTTP
//设置package包名称以及导入依赖的类
package works.weave.socks.aws.orders.dataaccess.web
import com.amazonaws.util.IOUtils
import com.fasterxml.jackson.core.`type`.TypeReference
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type
import java.net.URI
import javax.xml.ws.http.HTTPException
import org.apache.http.client.methods.HttpGet
import org.apache.http.impl.client.HttpClientBuilder
import org.slf4j.LoggerFactory
import works.weave.socks.aws.orders.ProjectDefaultJacksonMapper
object JSONHTTP {
val Log = LoggerFactory.getLogger(getClass)
val objectMapper = ProjectDefaultJacksonMapper.build() // after (_.bla)
def get[T : Manifest : NotNothing](uri : URI) : T = {
val client = HttpClientBuilder.create.build
val get = new HttpGet(uri)
get.addHeader("Accept", "application/json")
val response = client.execute(get)
val responseString = IOUtils.toString(response.getEntity.getContent)
Log.info(s"Got status ${response.getStatusLine.getStatusCode}")
if (response.getStatusLine.getStatusCode == 200) {
Log.info(s"Got response from URI $uri: $responseString")
objectMapper.readValue(responseString, typeReference[T])
} else {
throw new HTTPException(response.getStatusLine.getStatusCode)
}
}
def typeReference[T : Manifest] = new TypeReference[T] {
override def getType = typeFromManifest(manifest[T])
}
def typeFromManifest(m : Manifest[_]) : Type = {
if (m.typeArguments.isEmpty) { m.runtimeClass }
else new ParameterizedType {
def getRawType = m.runtimeClass
def getActualTypeArguments = m.typeArguments.map(typeFromManifest).toArray
def getOwnerType = null
}
}
// Trick to disable nothign for type param
sealed trait NotNothing[-T]
object NotNothing {
implicit object notNothing extends NotNothing[Any]
implicit object `The error is because the missing type parameter was resolved to Nothing` extends NotNothing[Nothing]
}
}
示例4: RedisConnectionPool
//设置package包名称以及导入依赖的类
package com.kurz.services
import java.net.URI
import redis.clients.jedis.{JedisPool, JedisPoolConfig}
object RedisConnectionPool {
lazy val instance: JedisPool = {
new JedisPool(poolConfig, connectionURI, 10000)
}
lazy val poolConfig: JedisPoolConfig = {
val config = new JedisPoolConfig()
// Use ENV to set MAX/MIN/IDLE?
config.setMaxTotal(100)
config.setMinIdle(100)
config.setMaxIdle(100)
config.setMaxWaitMillis(10000)
config
}
lazy val connectionURI: URI = {
new URI(Option(System.getenv("REDIS_URL")).getOrElse("redis://127.0.0.1:6379"))
}
}
示例5: set
//设置package包名称以及导入依赖的类
package walfie.gbf.raidfinder.server.persistence
import com.trueaccord.scalapb.{GeneratedMessage, GeneratedMessageCompanion, Message}
import java.net.URI
import redis.clients.jedis.{BinaryJedis, Jedis}
trait ProtobufStorage {
type CacheItem[T] = GeneratedMessage with Message[T]
def set[T <: CacheItem[T]](key: String, value: T): Unit
def get[T <: CacheItem[T]](
key: String
)(implicit companion: GeneratedMessageCompanion[T]): Option[T]
def close(): Unit
}
object ProtobufStorage {
def redis(uri: URI): RedisProtobufStorage = {
new RedisProtobufStorage(new BinaryJedis(uri))
}
}
// TODO: Write integration test
class RedisProtobufStorage(redis: BinaryJedis) extends ProtobufStorage {
def set[T <: CacheItem[T]](key: String, value: T): Unit = {
redis.set(key.getBytes, value.toByteArray)
}
def get[T <: CacheItem[T]](
key: String
)(implicit companion: GeneratedMessageCompanion[T]): Option[T] = {
Option(redis.get(key.getBytes)).flatMap { bytes =>
companion.validate(bytes).toOption
}
}
def close(): Unit = redis.close()
}
object NoOpProtobufStorage extends ProtobufStorage {
def set[T <: CacheItem[T]](key: String, value: T): Unit = ()
def get[T <: CacheItem[T]](
key: String
)(implicit companion: GeneratedMessageCompanion[T]): Option[T] = None
def close(): Unit = ()
}
示例6: RobotsTxtLookUp
//设置package包名称以及导入依赖的类
package bridgeapp.crawler
import java.net.URI
import akka.actor.{ActorRef, ActorSystem, Cancellable}
import bridgeapp.crawler.execution._
import com.typesafe.scalalogging.LazyLogging
import scala.concurrent.duration._
import scala.util.control.NonFatal
class RobotsTxtLookUp(throttling: ActorRef) extends Runnable with LazyLogging {
override def run(): Unit = {
logger.warn(s" Lookup robots.txt")
val uri = new URI("https://rutracker.org/robots.txt")
val parser = new ResponseParser {
override def ->(response: Response): Unit = {
val body = new String(response.body)
Robots.parse(body) match {
case Left(error) =>
logger.error(s"Error parse robots txt file, $error ")
case Right(robots) =>
robots.nonGroupFields.map(s => (s.key, s.value)).toMap[String, String].get("Crawl-delay").fold() { delay =>
try {
val rate = Rate(1, delay.toFloat.second)
throttling ! SetRate(rate)
} catch {
case NonFatal(e) => logger.error("Error parse crawl delay directive in robots.txt. ", e)
}
}
}
}
}
val request = Request(uri, parser)
//throttling !! request
}
}
class RobotsTXTScheduleExecutor(robotsTxtLookUp: RobotsTxtLookUp)(implicit val actorSystem: ActorSystem) {
private implicit val prep = actorSystem.dispatcher.prepare()
private var instance: Cancellable = _
def execute(duration: FiniteDuration) = {
instance = actorSystem.scheduler.schedule(duration, duration, robotsTxtLookUp)
}
def cancel(): Unit = {
instance.cancel()
}
}
示例7: RichURL
//设置package包名称以及导入依赖的类
package apodemakeles.scaluty
import java.net.{URI, URL}
implicit class RichURL(url: URL)
{
final lazy val queryMap: Map[String, String] = evaluateQueryMap()
private def evaluateQueryMap(): Map[String, String] = {
Option(url.getQuery) match {
case None => Map.empty[String, String]
case Some(query) =>
query
.split("&")
.filter(p => p.trim != "" && p.exists(c => c == '='))
.map
{
p =>
val array = p.split('=')
if (array.length > 1) (array(0), array(1)) else (array(0), "")
}.toMap
}
}
def getQueryMap = queryMap
def getPathWithDefault = if (url.getPath == null || url.getPath == "") "/" else url.getPath
def appendQuery(tup: (String, String)): URL = {
var query = if (url.getQuery == null) "" else url.getQuery
if (query != "") query += "&"
query += (tup._1 + "=" + tup._2)
new URI(
url.getProtocol,
url.getUserInfo,
url.getHost,
url.getPort,
url.getPath,
query,
null).toURL
}
}
}
示例8: EventSubscriptionTests
//设置package包名称以及导入依赖的类
package uk.co.appministry.scathon.client
import java.net.URI
import uk.co.appministry.scathon.models.v2.EventSubscriptionSubscribeEvent
import com.twitter.finagle.http.Status
class EventSubscriptionTests extends TestBase {
"Event subscriptions operations" should {
val callbackUri = "http://callback-uri.com/some-path"
"create a subscription when requested" in {
whenReady( client.createEventSubscription(new URI(callbackUri)) ) { event =>
event shouldBe a[EventSubscriptionSubscribeEvent]
}
}
"get a subscription list when requested" in {
whenReady( client.getEventSubscriptions() ) { items =>
items shouldBe( List(callbackUri) )
}
}
"delete a subscription when requested" in {
whenReady( client.deleteEventSubscription(new URI(callbackUri)) ) { status =>
status shouldBe(Status.Ok)
whenReady( client.getEventSubscriptions() ) { items =>
items shouldBe( List.empty[String] )
}
}
}
}
}
示例9: ClientInteraction
//设置package包名称以及导入依赖的类
import java.net.URI
import org.java_websocket.client.WebSocketClient
import org.java_websocket.drafts.Draft_17
import org.java_websocket.handshake.ServerHandshake
import collection.JavaConversions._
import scala.collection.mutable.ListBuffer
class ClientInteraction(uri: String) {
val messages = ListBuffer[String]()
val client = new WebSocketClient(URI.create("ws://localhost:9000/" + uri),
new Draft_17()) {
def onError(p1: Exception) {
println("onError")
}
def onMessage(message: String) {
messages += message
println("onMessage, message = " + message)
}
def onClose(code: Int, reason: String, remote: Boolean) {
println("onClose")
}
def onOpen(handshakedata: ServerHandshake) {
println("onOpen")
}
}
}
示例10: LoadSettings
//设置package包名称以及导入依赖的类
package tech.artemisia.task.settings
import java.net.URI
import com.typesafe.config.{Config, ConfigFactory}
import tech.artemisia.util.HoconConfigUtil.Handler
import tech.artemisia.util.URIParser
case class LoadSettings(location: URI, skipRows: Int = 0, override val delimiter: Char = ',', override val quoting: Boolean = false,
override val quotechar: Char = '"', override val escapechar: Char = '\\', mode: String = "default",
rejectFile: Option[String] = None, errorTolerance: Float = -1) extends
CSVSettings(delimiter, quoting, quotechar, escapechar) {
}
object LoadSettings {
val default_config = ConfigFactory parseString
"""
|{
| header = no
| skip-lines = 0
| delimiter = ","
| quoting = no
| quotechar = "\""
| escapechar = "\\"
| mode = default
| error-file = null
| error-tolerence = 2
|}
""".stripMargin
def apply(inputConfig: Config): LoadSettings = {
val config = inputConfig withFallback default_config
LoadSettings (
location = URIParser.parse(config.as[String]("load-path")),
skipRows = if (config.as[Int]("skip-lines") == 0) if (config.as[Boolean]("header")) 1 else 0 else config.as[Int]("skip-lines"),
delimiter = config.as[Char]("delimiter"),
quoting = config.as[Boolean]("quoting"),
quotechar = config.as[Char]("quotechar"),
escapechar = config.as[Char]("escapechar"),
mode = config.as[String]("mode"),
rejectFile = if (config.getIsNull("error-file")) None else Some(config.as[String]("error-file"))
)
}
}
示例11: ExportSetting
//设置package包名称以及导入依赖的类
package tech.artemisia.task.settings
import java.net.URI
import com.typesafe.config.{Config, ConfigFactory}
import tech.artemisia.util.FileSystemUtil
import tech.artemisia.util.HoconConfigUtil.Handler
case class ExportSetting(file: URI, header: Boolean = false, override val delimiter: Char = ',',
override val quoting: Boolean = false, override val quotechar: Char = '"',
override val escapechar: Char = '\\')
extends CSVSettings(delimiter, quoting, quotechar, escapechar)
object ExportSetting {
val default_config = ConfigFactory parseString
"""
| {
| header = false
| delimiter = ","
| quoting = no,
| quotechar = "\""
| escapechar = "\\"
| }
|
""".stripMargin
def apply(inputConfig: Config): ExportSetting = {
val config = inputConfig withFallback default_config
ExportSetting(
file = FileSystemUtil.makeURI(config.as[String]("file")),
header = config.as[Boolean]("header"),
delimiter = config.as[Char]("delimiter"),
quoting = config.as[Boolean]("quoting"),
escapechar = config.as[Char]("escapechar"),
quotechar = config.as[Char]("quotechar")
)
}
}
示例12: HMACRequestTest
//设置package包名称以及导入依赖的类
package com.gu.hmac
import java.net.URI
import org.joda.time.DateTime
import org.scalatest.{Matchers, FlatSpec}
class HMACRequestTest extends FlatSpec with Matchers {
val uri = new URI("/signin?query=someData")
val date = new DateTime(1994, 11, 15, 8, 12)
"toString" should "include empty string for content MD5 if there is no content" in{
val request = HMACRequest(
httpVerb = HTTP.GET,
date = HMACDate(date),
uri = uri,
contentMd5 = HMACContentMD5(None)
)
request.toSeq.length should be(6)
request.toString should be("GET\n\n\nTue, 15 Nov 1994 08:12:00 GMT\n/signin\n")
}
"toString" should "include empty string for content type if there is no content type" in{
val request = HMACRequest(
httpVerb = HTTP.GET,
date = HMACDate(date),
uri = uri,
contentType = None,
contentMd5 = HMACContentMD5(Some("content"))
)
request.toSeq.length should be(6)
request.toString should be("GET\nmgNkuembtIDdJeHwKEyFVQ==\n\nTue, 15 Nov 1994 08:12:00 GMT\n/signin\n")
}
"toString" should "include empty string for additional headers if there are no additional headers" in{
val request = HMACRequest(
httpVerb = HTTP.GET,
date = HMACDate(date),
uri = uri,
contentType = HMACContentType("application/json"),
contentMd5 = HMACContentMD5(Some("content")),
additionalHeaders = None
)
request.toSeq.length should be(6)
request.toString should be("GET\nmgNkuembtIDdJeHwKEyFVQ==\napplication/json\nTue, 15 Nov 1994 08:12:00 GMT\n/signin\n")
}
}
示例13: ClassOps
//设置package包名称以及导入依赖的类
package com.github.stonexx.scala.util
import java.lang.annotation.Annotation
import java.net.URI
import java.util.{Date, Locale}
import org.apache.commons.lang3.ClassUtils
import scala.reflect.ClassTag
final class ClassOps[T](val self: Class[T]) extends AnyVal {
import cls._
def isSimpleType: Boolean = ClassUtils.isPrimitiveOrWrapper(self) ||
classOf[CharSequence].isAssignableFrom(self) ||
classOf[Number].isAssignableFrom(self) ||
classOf[Date].isAssignableFrom(self) ||
classOf[URI] == self ||
classOf[Locale] == self ||
classOf[Class[_]] == self ||
self.isEnum
def findAnnotation[A <: Annotation : ClassTag](annotationClass: Class[A]): Option[A] =
Option(self getAnnotation annotationClass).orElse {
self.getInterfaces.find(_ isAnnotationPresent annotationClass).flatMap(_.findAnnotation[A])
}.orElse {
if (classOf[Annotation] isAssignableFrom self) None
else self.getAnnotations.map(_.annotationType).find(_ isAnnotationPresent annotationClass).flatMap(_.findAnnotation[A])
}.orElse {
Option(self.getSuperclass).filter(_ != classOf[Object]).flatMap(_.findAnnotation[A])
}
@inline
def findAnnotation[A <: Annotation](implicit atag: ClassTag[A]): Option[A] =
findAnnotation(atag.runtimeClass.asInstanceOf[Class[A]])
}
trait ToClassOps {
implicit def toClassOps[T](x: Class[T]): ClassOps[T] = new ClassOps(x)
}
示例14: RemoteStrategy
//设置package包名称以及导入依赖的类
package prisoners_dilemma
import akka.actor.ActorContext
import java.net.URI
class RemoteStrategy(context:ActorContext, firstMove: URI)
extends Strategizer {
def newGame(): RoundStrategy = {
// call first URI
val (move, uri) = parseResponse("la la ala la ala")
new RemoteRoundStrategy(context, move, uri)
}
private def parseResponse(response: String ): (Move, URI) = ???
private class RemoteRoundStrategy(context:ActorContext, myMove: Move, nextURI: URI) extends RoundStrategy {
val currentMove = myMove
def next(m: Move) = {
// call URI
val (nextMove, laterURI) = parseResponse("bananas")
new RemoteRoundStrategy(context, nextMove, laterURI)
}
}
}
示例15: NotFoundException
//设置package包名称以及导入依赖的类
package info.armado.ausleihe.client.connection.exceptions
import javax.ws.rs.ProcessingException
import java.net.URI
import java.net.ConnectException
import info.armado.ausleihe.client.model.ConnectionProperties
import info.armado.ausleihe.client.model.Configuration
case class NotFoundException(val serverAddress: URI) extends Exception
case class BadRequestException(val serverAddress: URI) extends Exception
case class InternalServerErrorException(val serverAddress: URI) extends Exception
case class UnhandledStatusCodeException(val serverAddress: URI, val statusCode: Int) extends Exception
object ServerUnreachableException {
def unapply(connectException: ConnectException): Option[URI] = Some(new URI(Configuration.connectionProperties.baseURL))
}
object ProcessingExceptionWrapper {
def unapply(processException: ProcessingException): Option[Throwable] = Option(processException.getCause)
}