当前位置: 首页>>代码示例>>Scala>>正文


Scala URLEncoder类代码示例

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


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

示例1: RequestNormalization

//设置package包名称以及导入依赖的类
package com.lookout.ratelimitingfilter

import java.nio.charset.StandardCharsets
import java.util.UUID
import java.net.URLEncoder
import com.twitter.finagle.http.Request
import shapeless.tag._
import cats.implicits._
import com.lookout.ratelimitingfilter.models._


object RequestNormalization {
  def apply(
    serviceLookup: Request => Option[String @@ ServiceName],
    claimLookup: Request => Option[(UUID @@ EntClaim, UUID @@ SubClaim)],
    request: Request
  ): List[String] = {
    val method = request.method
    val path = encodePath(request.path)
    val serviceBuckets: Option[List[String]] = serviceLookup(request).map {
      serviceName => s"$method::$serviceName" :: s"$method::$path::$serviceName" :: Nil
    }
    val idBuckets: Option[List[String]] = claimLookup(request).map {
      case (entUuid, subUuid) =>
        s"$method::$path::$entUuid" :: s"$method::$path::$subUuid" :: Nil
    }

    (serviceBuckets |+| idBuckets).getOrElse(Nil)
  }

  def encodePath(path: String): String =
    URLEncoder.encode(path, StandardCharsets.UTF_8.toString).toLowerCase
} 
开发者ID:lookout,项目名称:rate-limiting-strategy,代码行数:34,代码来源:RequestNormalization.scala

示例2: MCWhitelistHelper

//设置package包名称以及导入依赖的类
package com.amadornes.modcast.bot.helpers

import java.net.URLEncoder

import com.amadornes.modcast.bot.Actors
import com.amadornes.modcast.bot.database.{DB, UserMCAccount}
import com.amadornes.modcast.bot.servers.MCWhitelistServer
import com.google.gson.{Gson, JsonObject}
import sx.blah.discord.handle.obj.IUser

import scalaj.http.Http


object MCWhitelistHelper {
	def associateMCAccountWithUser(user: IUser, account: String): Unit = {
		val id = getMCAccountUUID(account)
		if (DB.query[UserMCAccount].whereEqual("user", user.getID).exists())
			deassociateMCAccountWithUser(user)
		Actors.servers.MCWhitelistServer ! MCWhitelistServer.WhitelistUser(id)
		DB.save(UserMCAccount(user.getID, id))
	}
	
	def deassociateMCAccountWithUser(user: IUser): Unit = {
		val account = DB.query[UserMCAccount].whereEqual("user", user.getID).fetchOne()
		if (account.isDefined) {
			Actors.servers.MCWhitelistServer ! MCWhitelistServer.UnWhitelistUser(account.get.account)
			DB.delete(account.get)
		}
	}
	
	def getMCAccountUUID(name: String): String = {
		val http = Http("http://mcapi.ca/profile/" + URLEncoder.encode(name)).asString
		if (http.code != 200)
			throw new IllegalArgumentException()
		new Gson().fromJson(http.body, classOf[JsonObject]).get("uuid_formatted").getAsString
	}
} 
开发者ID:Modcast,项目名称:ModcastBot,代码行数:38,代码来源:MCWhitelistHelper.scala

示例3: TempasWaybackSpec

//设置package包名称以及导入依赖的类
package de.l3s.archivespark.specific.warc.tempas

import java.net.URLEncoder

import de.l3s.archivespark.dataspecs.DataSpec
import org.apache.http.client.methods.HttpGet
import org.apache.http.impl.client.HttpClients
import org.apache.spark.SparkContext
import org.apache.spark.rdd.RDD

import scala.io.Source

class TempasWaybackSpec private (query: String, from: Option[Int] = None, to: Option[Int] = None, pages: Int, resultsPerPage: Int) extends DataSpec[TempasYearResult, TempasWaybackRecord] {
  import TempasWaybackSpec._

  def searchUrl(page: Int): String = {
    val queryEncoded = URLEncoder.encode(query, "UTF-8")
    var url = TempasSearchUrl.replace("$r", resultsPerPage.toString).replace("$p", page.toString).replace("$q", queryEncoded)
    if (from.isDefined) url += "&from=" + from.get
    if (to.isDefined) url += "&to=" + to.get
    url
  }

  override def load(sc: SparkContext, minPartitions: Int): RDD[TempasYearResult] = {
    sc.parallelize(1 to pages, minPartitions).flatMap { page =>
      @transient val client = HttpClients.createDefault
      @transient val get = new HttpGet(searchUrl(page))
      get.setHeader("Accept", AcceptType)
      val in = client.execute(get).getEntity.getContent
      try {
        Source.fromInputStream(in).getLines().toList.flatMap { line =>
          TempasYearResult.resultsFromTsv(line)
        }
      } finally {
        in.close()
      }
    }.repartition(minPartitions)
  }

  override def parse(result: TempasYearResult): Option[TempasWaybackRecord] = {
    Some(new TempasWaybackRecord(result))
  }
}

object TempasWaybackSpec {
  val TempasSearchUrl = "http://tempas.l3s.de/v2/query?resultsPerPage=$r&page=$p&q=$q"
  val DefaultResultsPerPage = 100
  val DefaultPages = 100
  val AcceptType = "text/tab-separated-values"

  def apply(query: String, from: Int = -1, to: Int = -1, pages: Int = DefaultPages, resultsPerPage: Int = DefaultResultsPerPage): TempasWaybackSpec = {
    val fromOpt = if (from < 0) None else Some(from)
    val toOpt = if (to < 0) None else Some(to)
    new TempasWaybackSpec(query, fromOpt, toOpt, pages, resultsPerPage)
  }
} 
开发者ID:helgeho,项目名称:Tempas2ArchiveSpark,代码行数:57,代码来源:TempasWaybackSpec.scala

示例4: lurlEncode

//设置package包名称以及导入依赖的类
package com.levent.hive.udfs

import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.UDF
import java.net.URLEncoder

@Description(
        name = "lurlEncode",
        value = "_FUNC_(string) URLEncode - encodes a string into application/x-www-form-urlencoded type (UTF-8)",
        extended = "SELECT lurlEncode(url) FROM test LIMIT 1;")
class lurlEncode extends UDF {
  def evaluate(url: String ): String= {
	if (url == null )
	   return null
	val encodedURL= java.net.URLEncoder.encode(url, "UTF-8");
	return (encodedURL)
	
  }

} 
开发者ID:lserinol,项目名称:Hive-udfs,代码行数:21,代码来源:lurlencode.scala

示例5: RelativeActorPathSpec

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

import org.scalatest.WordSpec
import org.scalatest.Matchers
import java.net.URLEncoder
import scala.collection.immutable

class RelativeActorPathSpec extends WordSpec with Matchers {

  def elements(path: String): immutable.Seq[String] = RelativeActorPath.unapply(path).getOrElse(Nil)

  "RelativeActorPath" must {
    "match single name" in {
      elements("foo") should be(List("foo"))
    }
    "match path separated names" in {
      elements("foo/bar/baz") should be(List("foo", "bar", "baz"))
    }
    "match url encoded name" in {
      val name = URLEncoder.encode("akka://[email protected]:2552", "UTF-8")
      elements(name) should be(List(name))
    }
    "match path with uid fragment" in {
      elements("foo/bar/baz#1234") should be(List("foo", "bar", "baz#1234"))
    }
  }
} 
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:28,代码来源:RelativeActorPathSpec.scala

示例6: 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
      }

} 
开发者ID:akka,项目名称:alpakka,代码行数:54,代码来源:CanonicalRequest.scala

示例7: 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(";")
  }
} 
开发者ID:TopSpoofer,项目名称:minio-scala,代码行数:54,代码来源:CanonicalRequest.scala

示例8: valueStream

//设置package包名称以及导入依赖的类
package com.zhranklin.homepage.notice

import java.net.URLEncoder
import java.util.Date

import com.zhranklin.homepage.blog.Article

import scala.util.Try

trait IndexService {
  protected val template: String
  protected val firstIndex: Int = 1
  protected def valueStream(i: Int): Stream[Int] = i #:: valueStream(i + 1)
  protected def indexNums: Iterable[Any] = valueStream(firstIndex)
  protected def interpolate(value: Any): String = template.replaceAll("<index>", value.toString)
  def indexUrls: Iterable[String] = indexNums map interpolate
}

case class Notice(url: String, title: String, html: String, date: Date)
case class NoticeEntry(url: String, title: Option[String] = None)

abstract class NoticeService(val source: String) extends UrlService with IndexService with NoticeFetcher {
  def getUrls: Iterable[NoticeEntry] = indexUrls.map(u ? Try(noticeUrlsFromUrl(u))).takeWhile(_.isSuccess).flatMap(_.get)
  def notices(after: Date = new Date(0)): Iterable[Notice] = getUrls.map(n ? Try(fetch(n))).filter(_.isSuccess).take(30).map(_.get).takeWhile(_.date.after(after))
  def toArticle(notice: Notice) = new Article(notice.title, source, "notice", None, notice.html, "", Nil, notice.date) {
    override val itemLink = s"/notice/$source?url=" + URLEncoder.encode(notice.url, "utf-8")
  }
} 
开发者ID:zhranklin,项目名称:Private_Blog,代码行数:29,代码来源:NoticeService.scala

示例9: URIUtils

//设置package包名称以及导入依赖的类
package com.pygmalios.reactiveinflux.impl

import java.net.{URI, URLEncoder}

import com.google.common.base.Charsets
import play.utils.UriEncoding

object URIUtils {
  private val sep = "/"

  def appendPath(uri: URI, path: String): URI = {
    val encodedPath = UriEncoding.encodePathSegment(path.stripPrefix(sep), Charsets.UTF_8.name())
    new URI(uri.toString.stripSuffix(sep) + sep + encodedPath)
  }

  def appendQuery(uri: URI, qs: (String, String)*): URI =
    new URI(uri.toString + queryToString(qs:_*))

  def queryToString(qs: (String, String)*): String =
    qs.map { case(k, v) =>
      k + "=" + URLEncoder.encode(v, Charsets.UTF_8.name()).replaceAll(" ", "%20")
    }.mkString(if (qs.isEmpty) "" else "?", "&", "")
} 
开发者ID:pygmalios,项目名称:reactiveinflux,代码行数:24,代码来源:URIUtils.scala

示例10: RemoteBot

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

import java.net.URLEncoder

import akka.stream.scaladsl.{ Sink, Source }
import akka.stream.{ ActorMaterializer, OverflowStrategy }
import akka.util.Timeout
import im.actor.bots.BotMessages
import im.actor.concurrent.ActorFutures
import upickle.default._

import scala.concurrent.duration._

object RemoteBot {
  val DefaultEndpoint = "wss://api.actor.im"

  private object StreamComplete
}

abstract class RemoteBot(token: String, endpoint: String) extends BotBase with ActorFutures {

  import BotMessages._
  import RemoteBot._

  override protected implicit val timeout: Timeout = Timeout(30.seconds)
  private implicit val mat = ActorMaterializer()

  initFlow()

  def onReceive(message: Object): Unit = {}

  def receive: Receive = internalReceive orElse {
    case message ?
      onReceive(message.asInstanceOf[Object])
  }

  override protected def onStreamFailure(cause: Throwable): Unit = {
    log.error(cause, "Stream failure")
    initFlow()
  }

  private final def internalReceive: Receive = workingBehavior.orElse({
    case StreamComplete ?
      log.warning("Disconnected, reinitiating flow")
      initFlow()
  })

  private def initFlow(): Unit = {
    val (wsSource, wsSink) = WebsocketClient.sourceAndSink(s"$endpoint/v1/bots/${URLEncoder.encode(token, "UTF-8")}")

    wsSource.map(read[BotMessageOut]).to(Sink.actorRef(self, StreamComplete)).run()

    val rqSource = Source.actorRef(bufferSize = 100, overflowStrategy = OverflowStrategy.fail)
      .map(write[BotRequest])
      .to(wsSink)
      .run()

    setRqSource(rqSource)
  }
} 
开发者ID:wex5,项目名称:dangchat-server,代码行数:61,代码来源:RemoteBot.scala

示例11: 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

示例12: MovieNameToIMDBPipeline

//设置package包名称以及导入依赖的类
package com.stacktrace.yo.scrapeline.imdb.pipelines

import java.net.URLEncoder
import java.nio.file.Paths

import akka.stream.scaladsl.{FileIO, Flow, Framing, Source}
import akka.stream.{ActorMaterializer, IOResult}
import akka.util.ByteString
import akka.{Done, NotUsed}
import com.stacktrace.yo.scrapeline.imdb.Domain.MovieNameAndDetailUrl

import scala.concurrent.{ExecutionContext, Future}

class MovieNameToIMDBPipeline(implicit val m: ActorMaterializer, implicit val ec: ExecutionContext) {

  private def getPipelineSource: Source[String, Future[IOResult]] = {
    FileIO.fromPath(Paths.get("movie.txt"))
      .via(Framing.delimiter(ByteString("\n"), 256)
        .map(_.utf8String)
      )
  }

  private def getDetailUrlFlow: Flow[String, MovieNameAndDetailUrl, NotUsed] = {
    Flow[String]
      .mapAsyncUnordered(100)(mapPipeToImdbSearch)
  }


  private def mapPipeToImdbSearch(in: String): Future[MovieNameAndDetailUrl] = Future {
    val encodedString: String = URLEncoder.encode(in, "UTF-8")
    MovieNameAndDetailUrl(in, "http://www.imdb.com/find?ref_=nv_sr_fn&q=" + encodedString + "&s=tt")
  }


  def getOutput: Future[Done] = {
    getPipelineSource
      .via(getDetailUrlFlow)
      .via(new IMDBSearchSubPipe().getSubFlow)
      .runForeach(x => println(x.name + ":" + x.url))
  }

} 
开发者ID:StackTraceYo,项目名称:scrapeline,代码行数:43,代码来源:MovieNameToIMDBPipeline.scala

示例13: Config

//设置package包名称以及导入依赖的类
package com.catinthedark.server

import java.net.URLEncoder

import com.catinthedark.common.Const

object Config {
  val pb = new ProcessBuilder()

  def gameTick: Int = try {
      pb.environment().getOrDefault("GAME_TICK", Const.Networking.tickDelay.toString).toInt
    } catch {
      case e: Exception => Const.Networking.tickDelay
    }

  def port: Int = try {
      pb.environment().getOrDefault("PORT", "9000").toInt
    } catch {
      case e: Exception => 9000
    }

  def notificationURL(message: String): String = {
    val key = pb.environment.get("TELEGRAM_KEY")
    val chatId = pb.environment.get("TELEGRAM_CHAT_ID")
    val msg = URLEncoder.encode(message, "UTF-8")
    s"https://api.telegram.org/bot$key/sendMessage?chat_id=$chatId&disable_web_page_preview=1&text=$msg"
  }

  def jdbcUser = pb.environment().getOrDefault("JDBC_DATABASE_USERNAME", "postgres")
  def jdbcPassword = pb.environment().getOrDefault("JDBC_DATABASE_PASSWORD", "")
  def jdbcURL = pb.environment().getOrDefault("JDBC_DATABASE_URL", "jdbc:postgresql://localhost:5432/postgres")
} 
开发者ID:cat-in-the-dark,项目名称:old48_36_game,代码行数:33,代码来源:Config.scala

示例14: PlainQueryConverter

//设置package包名称以及导入依赖的类
package com.hypertino.hyperbus.model.hrl

import java.net.{URLDecoder, URLEncoder}

import com.hypertino.binders.value.{Null, Obj, Text, Value}

object PlainQueryConverter extends QueryConverter {
  final val encoding = "UTF-8"

  override def parseQueryString(queryString: String): Value = {
    if (queryString == null || queryString.isEmpty) {
      Null
    } else {

      Obj(queryString.split('&').map { s ?
        val i = s.indexOf('=')
        if (i>0) {
          val left = s.substring(0, i)
          val right = Text(URLDecoder.decode(s.substring(i+1), encoding))
          left ? right
        }
        else {
          s ? Null
        }
      }.toMap)
    }
  }

  override def toQueryString(value: Value): String = {
    value match {
      case Null ? ""
      case Text(s) ? s
      case Obj(elements) ? elements.map { case (k, v) ?
        if (v.isNull) {
          k
        }
        else {
          k + "=" + URLEncoder.encode(v.toString, encoding)
        }
      } mkString "&"
      case other ? throw new IllegalArgumentException(s"$other is not an Obj or Text")
    }
  }
} 
开发者ID:hypertino,项目名称:hyperbus,代码行数:45,代码来源:PlainQueryConverter.scala

示例15: queryStringLocalDateBinder

//设置package包名称以及导入依赖的类
package controllers.support

import java.text.SimpleDateFormat
import java.util.Date

import play.api.mvc.QueryStringBindable

trait DateBinders {
  implicit def queryStringLocalDateBinder = new QueryStringBindable[Date] {

    val format = "yyyyMMdd"

    override def bind(key: String, params: Map[String, Seq[String]]): Option[Either[String, Date]] = {
      params(key).headOption map { dateString =>
        try {
          val sdf = new SimpleDateFormat(format)
          Right(sdf.parse(dateString))
        } catch {
          case e: IllegalArgumentException => Left("Failed to parse query string as Date.")
        }
      }
    }
    override def unbind(key: String, date: Date): String = {
      import java.net.URLEncoder
      URLEncoder.encode(key, "utf-8") + "&" + URLEncoder.encode(date.toString, "utf-8")
    }
  }
}

object Binders extends DateBinders 
开发者ID:takat0-h0rikosh1,项目名称:play_boilerplate,代码行数:31,代码来源:Binders.scala


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