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

Scala StandardCharsets类代码示例

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

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



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

//设置package包名称以及导入依赖的类
package parsers

import java.io.{InputStream, InputStreamReader}
import java.nio.charset.StandardCharsets
import java.nio.file.{Files, Path, Paths}
import javax.script.ScriptEngineManager

import com.google.common.base.Charsets
import com.google.common.io.CharStreams
import org.luaj.vm2.{LuaTable, LuaValue}

import scala.collection.breakOut
import scala.io.Source

trait FactorioParser[T] {
  import FactorioParser._

  def parse(path: String): Seq[T] = commonParse(readAll(path))
  def parse(path: Path): Seq[T] = commonParse(readAll(path))
  def parse(is: InputStream): Seq[T] = {
    val str = CharStreams.toString(new InputStreamReader(is, Charsets.UTF_8))
    commonParse(str)
  }

  def transport(table: LuaTable): Option[T]

  private[this] def commonParse(target: String): Seq[T] = {
    val dataLua = Source.fromURL(getClass.getResource("/data.lua")).mkString
    val lua = dataLua + target
    val engine = manager.getEngineByName("luaj")
    engine.eval(lua)
    val array: LuaTable = engine.get("array").asInstanceOf[LuaTable]
    tableToSeq(array)(_.checktable()).flatMap(transport)
  }
}

object FactorioParser {
  private val manager = new ScriptEngineManager()

  def readAll(path: String): String = readAll(Paths.get(path))

  def readAll(path: Path): String =
    new String(Files.readAllBytes(path), StandardCharsets.UTF_8)

  def tableToSeq[T](table: LuaTable)(f: LuaValue => T): Seq[T] = {
    table.keys().map(table.get).map(f)(breakOut)
  }

  def tableToMap[K, V](table: LuaTable)(f: LuaValue => K)(g: LuaValue => V): Map[K, V] = {
    table.keys().map { key =>
      f(key) -> g(table.get(key))
    }(breakOut)
  }


} 
开发者ID:ponkotuy,项目名称:FactorioRecipe,代码行数:57,代码来源:FactorioParser.scala


示例3: PasswordHasherSHA256

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

import java.nio.charset.StandardCharsets

import com.mohiva.play.silhouette.api.util.{PasswordHasher, PasswordInfo}
import org.apache.directory.api.ldap.model.constants.LdapSecurityConstants
import org.apache.directory.api.ldap.model.password.PasswordUtil


class PasswordHasherSHA256 extends PasswordHasher{
  override def id: String = "SHA-256"

  override def hash(plainPassword: String): PasswordInfo = {
    PasswordInfo(hasher = id, password = plainPassword)
  }

  //TODO: Here might be an oversight. It seems to be to complicated.
  override def matches(passwordInfo: PasswordInfo, suppliedPassword: String): Boolean = {
    val suppliedStoragePW =  PasswordUtil.createStoragePassword(
      suppliedPassword,
      LdapSecurityConstants.getAlgorithm(passwordInfo.hasher)
    )

    val suppliedPW = new String(PasswordUtil.splitCredentials(suppliedStoragePW).getPassword,StandardCharsets.UTF_8)
    val storedPW = passwordInfo.password

    suppliedPW.equals(storedPW)
  }
} 
开发者ID:wirvomgut,项目名称:curo,代码行数:30,代码来源:PasswordHasherSHA256.scala


示例4: ExportModel

//设置package包名称以及导入依赖的类
package com.cloudera.datascience.cdsw.acme

import java.nio.charset.StandardCharsets
import java.nio.file.StandardOpenOption._
import java.nio.file.{Files, Paths}
import javax.xml.transform.stream.StreamResult

import org.dmg.pmml.Application
import org.jpmml.model.JAXBUtil
import org.jpmml.sparkml.ConverterUtil

import acme.ACMEModel

object ExportModel {
  
  def main(args: Array[String]): Unit = {
    val training = ACMEData.readData()
    val pipeline = ACMEModel.buildModel()
    
    val pmml = ConverterUtil.toPMML(training.schema, pipeline)
    pmml.getHeader.setApplication(new Application("ACME Occupancy Detection"))
    
    val modelPath = Paths.get("src", "main", "resources")
    if (!Files.exists(modelPath)) {
      Files.createDirectory(modelPath)
    }
    val pmmlFile = modelPath.resolve("model.pmml")
    val writer = Files.newBufferedWriter(pmmlFile, StandardCharsets.UTF_8, WRITE, CREATE, TRUNCATE_EXISTING)
    try {
      JAXBUtil.marshalPMML(pmml, new StreamResult(writer))
    } finally {
      writer.close()
    }
  }

} 
开发者ID:srowen,项目名称:cdsw-simple-serving,代码行数:37,代码来源:ExportModel.scala


示例5: MedicineProcess

//设置package包名称以及导入依赖的类
package cn.com.warlock.practice.ml

import java.io.BufferedReader
import java.nio.charset.StandardCharsets
import java.nio.file.{Files, Paths}

import org.apache.spark.ml.UnaryTransformer
import org.apache.spark.ml.param.ParamMap
import org.apache.spark.ml.util.Identifiable
import org.apache.spark.sql.types.{ArrayType, DataType, StringType}

import scala.collection.mutable.Set

class MedicineProcess(override val uid: String, private val dict: String)
  extends UnaryTransformer[Seq[String], Seq[String], MedicineProcess] {

  def this(dict: String) = this(Identifiable.randomUID("med"), dict)

  // ?????????
  private val wordsSet = loadDict

  // ????
  private def loadDict: Set[String] = {
    val br: BufferedReader = Files.newBufferedReader(Paths.get(dict), StandardCharsets.UTF_8)
    val words = Set[String]()

    var count = 0

    while (br.ready()) {
      words += br.readLine()
      count += 1
    }

    println(s"load med words: $count")

    words
  }

  override protected def createTransformFunc: Seq[String] => Seq[String] = (words: Seq[String]) => {
    // ?? "???", arr ?????????, c ??????? word
    words.foldLeft(List[String]())((arr, c) => {
      val newC = wordsSet.contains(c) match {
        case true => List(c, "_MED_")
        case false => List(c)
      }
      arr ++ newC
    })
  }

  override protected def validateInputType(inputType: DataType): Unit = {
    require(inputType.isInstanceOf[ArrayType],
      s"The input column must be ArrayType, but got $inputType.")
  }

  override protected def outputDataType: DataType = new ArrayType(StringType, true)

  override def copy(extra: ParamMap): MedicineProcess = defaultCopy(extra)
} 
开发者ID:warlock-china,项目名称:spark-meepo,代码行数:59,代码来源:MedicineProcess.scala


示例6: SalesforceCustomerRepoSpec

//设置package包名称以及导入依赖的类
package com.ovoenergy.comms.profiles.salesforce

import java.nio.charset.StandardCharsets
import java.nio.file.{Files, Paths}

import com.ovoenergy.comms.profiles.domain._
import okhttp3._
import org.scalatest.{EitherValues, FlatSpec, Matchers}

class SalesforceCustomerRepoSpec extends FlatSpec with Matchers with EitherValues {

  behavior of "SalesforceCustomerRepo"

  val request = new Request.Builder().url("http://google.com").get().build()

  def buildResponse(code: Int, body: String): (String) => Either[SalesforceError, Response] =
    (str: String) =>
      Right(
        new Response.Builder()
          .protocol(Protocol.HTTP_1_1)
          .code(code)
          .request(request)
          .body(ResponseBody.create(MediaType.parse("application/json"), body))
          .build()
    )

  it should "Successfull deserialise a valid customer json body" in {
    val json =
      new String(Files.readAllBytes(Paths.get("src/test/resources/customer_profile.json")), StandardCharsets.UTF_8)
    val makeAuthenticatedRequest = buildResponse(200, json)
    val profile                  = SalesforceCustomerRepo.getCustomerProfile(makeAuthenticatedRequest)("customer123")
    profile shouldBe Right(
      Customer(
        Name(Some("Mr"), "Gary", "Philpott", None),
        EmailAddresses(Some("[email protected]"), None),
        TelephoneNumbers(Some("+441285112233"), Some("+447834774651"), Some("+441285112233")),
        Embedded(
          List(
            CommunicationPreference("SERVICE", List("Sms", "Email", "POST")),
            CommunicationPreference("MARKETING", List.empty),
            CommunicationPreference("THIRDPARTY", List.empty)
          )
        )
      )
    )
  }

  it should "display an appropriate message if invalid json is returned" in {
    val makeAuthenticatedRequest = buildResponse(200, """{"some": "thing"}""")
    val profile                  = SalesforceCustomerRepo.getCustomerProfile(makeAuthenticatedRequest)("customer123")

    profile.left.value.message should startWith("Invalid JSON from salesforce api")
  }
} 
开发者ID:ovotech,项目名称:comms-profiles,代码行数:55,代码来源:SalesforceCustomerRepoSpec.scala


示例7: ProvisionUser

//设置package包名称以及导入依赖的类
// Copyright (c) 2017 Grier Forensics. All Rights Reserved.

package com.grierforensics.greatdane.connector

import java.net.URI
import java.nio.charset.StandardCharsets
import java.nio.file.{Files, Paths}

import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import org.apache.commons.io.IOUtils
import org.apache.http.HttpHeaders
import org.apache.http.client.methods.HttpPost
import org.apache.http.entity.StringEntity
import org.apache.http.impl.client.HttpClients


object ProvisionUser {
  def main(args: Array[String]): Unit = {

    def die = {
      println("Usage: provision-user <email-address> [<certificate file>]")
      sys.exit(1)
    }
    val (emailAddress, certPem) = args.toList match {
      case email :: tail => tail match {
        case Nil => (email, "")
        case certFile :: Nil => (email, new String(Files.readAllBytes(Paths.get(certFile)), StandardCharsets.UTF_8))
        case _ => die
      }
      case _ => die
    }

    val client = HttpClients.createDefault()
    val uri = new URI(s"http://${Settings.Host}:${Settings.Port}/api/v1/user/$emailAddress")
    val post = new HttpPost(uri)
    post.addHeader(HttpHeaders.CONTENT_TYPE, "application/json")
    post.addHeader(HttpHeaders.AUTHORIZATION, Settings.ApiKey)
    println(post.toString)

    val req = ProvisionRequest(None, if (certPem.length > 0) Some(Seq(certPem)) else None)
    val mapper = new ObjectMapper().registerModule(DefaultScalaModule)
    val json = mapper.writeValueAsString(req)
    println(json)

    post.setEntity(new StringEntity(json))

    val resp = client.execute(post)
    try {
      val entity = resp.getEntity
      println(resp.getStatusLine.getStatusCode, resp.getStatusLine.getReasonPhrase)
      println(IOUtils.toString(entity.getContent, StandardCharsets.UTF_8))
    } finally {
      resp.close()
    }

  }
} 
开发者ID:grierforensics,项目名称:Great-DANE-Connector,代码行数:59,代码来源:ProvisionUser.scala


示例8: SimpleKafkaProducerTest

//设置package包名称以及导入依赖的类
package com.example
import java.nio.charset.StandardCharsets

import kafka.consumer.ConsumerConfig
import kafka.utils.TestUtils
import org.scalatest.{FunSpec, Matchers}
//import org.junit.Assert._
import scala.collection.immutable.HashMap

class SimpleKafkaProducerTest extends FunSpec with Matchers{

  private val topic = "test"
  private val groupId = "group0"
  private val kafkaHelpers = new KafkaHelpers()


  case class MessageData(a: String, b: String)

  describe("The SimpleKafka Api") {
    it("Should send data using a producer") {
      //Send data to Kafka
      val kafkaApi = new SimpleKafkaProducer(kafkaHelpers.kafkaSocket(), topic)
      kafkaApi.send[MessageData](new MessageData("Hello", "World"))

      //Create consumer
      val consumerProperties = TestUtils.createConsumerProperties(kafkaHelpers.zookeeperSocket().toString(), groupId, "consumer0", -1)
      val consumer = kafka.consumer.Consumer.create(new ConsumerConfig(consumerProperties))

      val topicCountMap = HashMap(topic -> 1)
      val consumerMap = consumer.createMessageStreams(topicCountMap)
      val stream = consumerMap.get(topic).get(0)
      val iterator = stream.iterator()
      val msg = new String(iterator.next().message(), StandardCharsets.UTF_8)

      assert("{\"a\":\"Hello\",\"b\":\"World\"}" == msg)

      // cleanup
      consumer.shutdown()
    }
  }
} 
开发者ID:frossi85,项目名称:financial-statistics-crawler,代码行数:42,代码来源:SimpleKafkaProducerTest.scala


示例9: ScheduleDownloadActor

//设置package包名称以及导入依赖的类
package logic.actors.schedule

import java.nio.charset.StandardCharsets
import javax.inject._

import akka.actor.{Actor, ActorRef}
import helpers.SpiritHelper
import logic.actors.schedule.ScheduleDownloadActor.DownloadSchedule
import logic.actors.schedule.ScheduleParseActor._
import org.fhs.spirit.scheduleparser.enumerations.EScheduleKind
import org.jsoup.Jsoup
import play.api.libs.ws.WSClient

import scala.collection.JavaConversions._
import scala.concurrent.Await
import scala.concurrent.duration._


@Singleton
class ScheduleDownloadActor @Inject()(ws: WSClient, @Named("parseActor") parseActor: ActorRef) extends Actor with SpiritHelper {


  override def receive: Receive = {
    case DownloadSchedule =>

      val baseUrl = configuration.underlying.getString("schedule.baseUrl")

      val lectureResults = uncachedCourseNames.map {
        courseName =>
          val outcome = "s_" + courseName + ".html"
          val httpResult = Await.result(ws.url(baseUrl + outcome).get(), 10 seconds)
          if (httpResult.status != 404) {
            Some((httpResult.bodyAsBytes.decodeString(StandardCharsets.ISO_8859_1.toString), courseName))
          } else {
            None
          }
      }.filter(_.nonEmpty).map(rs => (Jsoup.parse(rs.get._1).toString, rs.get._2)).map(rs => (EScheduleKind.REGULAR, rs))

      val blockBaseResult = Await.result(ws.url(baseUrl + "bindex.html").get(), 10 seconds)
      val bindex = Jsoup.parse(blockBaseResult.bodyAsBytes.decodeString(StandardCharsets.ISO_8859_1.toString))
      val blockRefs = bindex.select("a").map(_.attr("href")).toSet

      val blockResult = blockRefs.map {
        block =>
          val httpResult = Await.result(ws.url(baseUrl + block).get(), 10 seconds)
          if (httpResult.status != 404) {
            Some((httpResult.bodyAsBytes.decodeString(StandardCharsets.ISO_8859_1.toString), block))
          } else {
            None
          }
      }.filter(_.nonEmpty).map(rs => (Jsoup.parse(rs.get._1).toString, rs.get._2)).map(rs => (EScheduleKind.BLOCK, rs))

      parseActor ! ParseSchedule(lectureResults ++ blockResult)
  }
} 
开发者ID:P1tt187,项目名称:spirit-play,代码行数:56,代码来源:ScheduleDownloadActor.scala


示例10: fromXmlGetReportListResponse

//设置package包名称以及导入依赖的类
package com.wegtam.amws.reports.adt

import java.io.ByteArrayInputStream
import java.nio.charset.StandardCharsets
import java.time.OffsetDateTime

import com.wegtam.amws.reports.ReportType
import eu.cdevreeze.yaidom.parse.DocumentParserUsingSax
import eu.cdevreeze.yaidom.queryapi.HasENameApi.withLocalName
import eu.cdevreeze.yaidom.simple.Elem

import scala.collection.immutable.Seq
import scala.util.Try


  def fromXmlGetReportListResponse(s: String): Seq[ReportInfo] = {
    val eo: Option[Elem] = for {
      p <- Try(DocumentParserUsingSax.newInstance()).toOption
      d <- Try(p.parse(new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8)))).toOption
      e <- d.documentElement.findChildElem(withLocalName("GetReportListResult"))
    } yield e
    eo.fold(Seq.empty[ReportInfo]) { e =>
      val it = for {
        c <- e.filterChildElems(withLocalName("ReportInfo"))
        r <- fromXmlElement(c)
      } yield r
      it
    }
  }

} 
开发者ID:wegtam,项目名称:amws-scala,代码行数:32,代码来源:ReportInfo.scala


示例11: SignRequest

//设置package包名称以及导入依赖的类
package com.wegtam.amws.common

import java.nio.charset.StandardCharsets
import java.util.Base64
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec

import com.wegtam.amws.common.Request.{ ParameterName, RequestParameters }

import scala.util.Try

object SignRequest {
  // The field name for the query parameter that will hold the signature.
  final val SignatureRequestFieldName: ParameterName = "Signature"
  // These fields are needed for signed requests and must be added accordingly.
  final val SignatureRequestFields: RequestParameters = Map(
    "SignatureMethod"  -> "HmacSHA256",
    "SignatureVersion" -> "2"
  )

  
  def sign(key: Array[Byte], data: Array[Byte]): Try[String] = Try {
    val algo = "HmacSHA256"
    val base = Base64.getEncoder
    val hmac = Mac.getInstance(algo)
    val skey = new SecretKeySpec(key, algo)
    hmac.init(skey)
    val sig = hmac.doFinal(data)
    new String(base.encode(sig), StandardCharsets.UTF_8)
  }

} 
开发者ID:wegtam,项目名称:amws-scala,代码行数:33,代码来源:SignRequest.scala


示例12: format

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

import java.nio.charset.{Charset, StandardCharsets}

import akka.NotUsed
import akka.stream.alpakka.csv.{javadsl, CsvFormatter}
import akka.stream.scaladsl.{Flow, Source}
import akka.util.ByteString

import scala.collection.immutable


  def format[T <: immutable.Iterable[String]](
      delimiter: Char = Comma,
      quoteChar: Char = DoubleQuote,
      escapeChar: Char = Backslash,
      endOfLine: String = "\r\n",
      quotingStyle: CsvQuotingStyle = CsvQuotingStyle.Required,
      charset: Charset = StandardCharsets.UTF_8,
      byteOrderMark: Option[ByteString] = None
  ): Flow[T, ByteString, NotUsed] = {
    val formatter =
      new CsvFormatter(delimiter, quoteChar, escapeChar, endOfLine, quotingStyle, charset)
    byteOrderMark.fold {
      Flow[T].map(formatter.toCsv).named("CsvFormatting")
    } { bom =>
      Flow[T].map(formatter.toCsv).named("CsvFormatting").prepend(Source.single(bom))
    }

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


示例13: PasswordHasherMD5

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

import java.nio.charset.StandardCharsets

import com.mohiva.play.silhouette.api.util.{PasswordHasher, PasswordInfo}
import org.apache.directory.api.ldap.model.constants.LdapSecurityConstants
import org.apache.directory.api.ldap.model.password.PasswordUtil


class PasswordHasherMD5 extends PasswordHasher{
  override def id: String = "MD5"

  override def hash(plainPassword: String): PasswordInfo = {
    PasswordInfo(hasher = id, password = plainPassword)
  }

  //TODO: Here might be an oversight. It seems to be to complicated.
  override def matches(passwordInfo: PasswordInfo, suppliedPassword: String): Boolean = {
    val suppliedStoragePW =  PasswordUtil.createStoragePassword(
      suppliedPassword,
      LdapSecurityConstants.getAlgorithm(passwordInfo.hasher)
    )

    val suppliedPW = new String(PasswordUtil.splitCredentials(suppliedStoragePW).getPassword,StandardCharsets.UTF_8)
    val storedPW = passwordInfo.password

    suppliedPW.equals(storedPW)
  }
} 
开发者ID:wirvomgut,项目名称:curo,代码行数:30,代码来源:PasswordHasherMD5.scala


示例14: encodePacket

//设置package包名称以及导入依赖的类
package roc

import roc.postgresql.transport.{PacketDecoder, PacketDecoderImplicits, Packet, PacketEncoder, 
  PacketEncoderImplicits}
import java.nio.charset.StandardCharsets

package object postgresql extends PacketEncoderImplicits with PacketDecoderImplicits {

  def encodePacket[A <: FrontendMessage: PacketEncoder](a: A): Packet = 
    implicitly[PacketEncoder[A]].apply(a)

  def decodePacket[A <: BackendMessage: PacketDecoder](p: Packet): PacketDecoder.Result[A] =
    implicitly[PacketDecoder[A]].apply(p)

  def lengthOfCStyleString(str: String): Int = {
    val bytes = str.getBytes(StandardCharsets.UTF_8)
    bytes.length + 1
  }

  def lengthOfCStyleStrings(xs: List[String]): Int = xs match {
    case h :: t => xs.map(lengthOfCStyleString).reduce(_ + _)
    case t      => 0
  }

} 
开发者ID:finagle,项目名称:roc,代码行数:26,代码来源:package.scala


示例15: MessagesSpec

//设置package包名称以及导入依赖的类
package roc
package postgresql

import java.nio.charset.StandardCharsets
import java.security.MessageDigest
import org.scalacheck.Arbitrary.arbitrary
import org.scalacheck.Prop.forAll
import org.scalacheck.{Arbitrary, Gen}
import org.specs2._

final class MessagesSpec extends Specification with ScalaCheck { def is = s2"""

  PasswordMessage
    should MD5 encrypt a password with given salt           $pmEncrypt
                                                                            """

  val pmEncrypt = forAll { (user: String, pm: PasswordMessage, salt: Array[Byte]) =>
    val md = MessageDigest.getInstance("MD5")
    md.update((pm.password+ user).getBytes(StandardCharsets.UTF_8))
    val unsaltedHexStr = md.digest().map(x => "%02x".format(x.byteValue)).foldLeft("")(_ + _)
    val saltedBytes = unsaltedHexStr.getBytes ++ salt
    md.reset()
    md.update(saltedBytes)
    val passwd = md.digest().map(x => "%02x".format(x.byteValue)).foldLeft("md5")(_ + _)
    passwd must_== PasswordMessage.encryptMD5Passwd(user, pm.password, salt)
  }
  
  lazy val genByte: Gen[Byte] = arbitrary[Byte]
  lazy val genSalt: Gen[Array[Byte]] = Gen.containerOfN[Array, Byte](4, genByte)
  lazy val genPasswordMessage: Gen[PasswordMessage] = for {
    password    <-  arbitrary[String]
  } yield new PasswordMessage(password)
  implicit lazy val implicitPasswordMessage: Arbitrary[PasswordMessage] = 
    Arbitrary(genPasswordMessage)
} 
开发者ID:finagle,项目名称:roc,代码行数:36,代码来源:MessageSpec.scala


示例16:

//设置package包名称以及导入依赖的类
package roc
package postgresql

import java.nio.charset.StandardCharsets
import org.scalacheck.Arbitrary._
import org.scalacheck.Arbitrary.arbitrary
import org.scalacheck.Prop.forAll
import org.scalacheck.{Arbitrary, Gen}
import org.specs2._


trait PostgresqlLexicalGen extends ScalaCheck {
  // see http://www.postgresql.org/docs/current/static/sql-syntax-lexical.html
  // for more on what constitues a valid SQL Identifier
  protected val UnicodeCapitalEnglish = '\u0041' to '\u005A'
  protected val UnicodeLowerEnglish   = '\u0061' to '\u007A'
  protected val UnicodeNonLatin       = '\u0400' to '\u1FFE'
  protected val UnicodeUnderscore     = "_".getBytes(StandardCharsets.UTF_8).map(_.toChar).head
  protected val UnicodeDollarSign     = "$".getBytes(StandardCharsets.UTF_8).map(_.toChar).head
  protected val UnicodeNumbers        = '\u0030' to '\u0039'
  protected val BeginningChars = UnicodeUnderscore :: List(UnicodeCapitalEnglish, 
    UnicodeLowerEnglish, UnicodeNonLatin).flatten
  protected val SubsequentChars = UnicodeDollarSign :: BeginningChars ::: UnicodeNumbers.toList

  protected lazy val genValidBeginningIdentifier: Gen[Char] = for {
    char    <-  Gen.oneOf(BeginningChars)
  } yield char
  protected lazy val genValidSubsequentIdentifier: Gen[Char] = for {
    char    <-  Gen.oneOf(SubsequentChars)
  } yield char

  protected lazy val genValidSQLIdentifier: Gen[String] = for {
    firstChar   <-  genValidBeginningIdentifier
    chars       <-  Gen.listOf(genValidSubsequentIdentifier)
  } yield {
    val xs = firstChar :: chars
    xs.map(_.toString).reduce(_ + _)
  }

  protected lazy val genValidNumberOfShortColumns: Gen[Short] = 
    Gen.chooseNum[Short](0, 1663) // the maximum number of Postgresql columns is 1663
  protected lazy val genValidNumberOfIntColumns: Gen[Int] =
    genValidNumberOfShortColumns.map(_.toInt)
  protected lazy val genValidNonZeroNumberOfShortColumns: Gen[Short] =
    Gen.chooseNum[Short](1, 1663) // the maximum number of Postgresql columns is 1663
} 
开发者ID:finagle,项目名称:roc,代码行数:47,代码来源:PostgresqlLexicalGen.scala


示例17: Response

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

import java.io.{ByteArrayInputStream, InputStream}
import java.nio.charset.StandardCharsets


sealed trait Response

object Response {

  case class Http(status: Status,
                  body: Option[InputStream] = None,
                  headers: Seq[(String, String)] = Seq.empty)
      extends Response

  object Http {
    def apply(status: Status, message: String): Http = {
      val bytes = message.getBytes(StandardCharsets.UTF_8)
      val body = new ByteArrayInputStream(bytes)
      Http(status, Some(body))
    }
  }

  case class WebSocket(publish: String => Unit,
                       subscribe: (String => Unit) => Unit,
                       destroyHandler: () => Unit)
      extends Response

  sealed trait Status {
    def code: Int
    def phrase: String
  }

  object Status {
    case object Ok extends Status {
      val code = 200
      val phrase = "OK"
    }
    case object BadRequest extends Status {
      val code = 400
      val phrase = "Bad Request"
    }
    case object Gone extends Status {
      val code = 410
      val phrase = "Gone"
    }
  }
} 
开发者ID:techyogillc,项目名称:ServerSideScalaCode,代码行数:49,代码来源:Response.scala


示例18: FormDataCodecSpec

//设置package包名称以及导入依赖的类
import java.nio.ByteBuffer
import java.nio.charset.StandardCharsets

import korolev.server.FormDataCodec
import org.scalatest.{FlatSpec, Matchers}


class FormDataCodecSpec extends FlatSpec with Matchers {
  "decode" should "parse valid multipart/form-data body" in {
    val body = """--Asrf456BGe4h
      |Content-Disposition: form-data; name="DestAddress"
      |
      |[email protected]
      |--Asrf456BGe4h
      |Content-Disposition: form-data; name="MessageTitle"
      |
      |I'm indignant
      |--Asrf456BGe4h
      |Content-Disposition: form-data; name="MessageText"
      |
      |Hello, Vasily! Your hand lion, which you left with me
      |last week, tore my whole sofa. Please take it away
      |soon! In the attachment, two pictures with consequences.
      |--Asrf456BGe4h
      |Content-Disposition: form-data; name="AttachedFile1"; filename="horror-photo-1.jpg"
      |Content-Type: image/jpeg
      |
      |<blob1>
      |--Asrf456BGe4h
      |Content-Disposition: form-data; name="AttachedFile2"; filename="horror-photo-2.jpg"
      |Content-Type: image/jpeg
      |
      |<blob2>
      |--Asrf456BGe4h--
    """.stripMargin

    val bodyBuffer = ByteBuffer.wrap(body.getBytes(StandardCharsets.US_ASCII))
    val codec = new FormDataCodec(100500)
    val formData = codec.decode(bodyBuffer, "Asrf456BGe4h")

    formData.text("DestAddress") should be ("[email protected]")
    formData.text("MessageTitle") should be ("I'm indignant")
    formData.bytes("AttachedFile2") should be {
      ByteBuffer.wrap("<blob2>".getBytes)
    }
  }
} 
开发者ID:techyogillc,项目名称:ServerSideScalaCode,代码行数:48,代码来源:FormDataCodecSpec.scala


示例19: FormData

//设置package包名称以及导入依赖的类
package korolev

import java.nio.ByteBuffer
import java.nio.charset.StandardCharsets

import korolev.FormData.Entry


final case class FormData(content: Seq[Entry]) {

  def text(name: String): String = {
    val array = bytes(name).array()
    new String(array, StandardCharsets.UTF_8)
  }

  def bytes(name: String): ByteBuffer = bytesOpt(name).get

  def bytesOpt(name: String): Option[ByteBuffer] = {
    apply(name).map(_.content)
  }

  def contentType(name: String): Option[String] = {
    apply(name) flatMap { entry =>
      entry.headers collectFirst {
        case (k, v) if k.toLowerCase == "content-type" => v
      }
    }
  }

  def apply(name: String): Option[Entry] =
    content.find(_.name == name)
}

object FormData {

  case class Entry(
      name: String,
      content: ByteBuffer,
      headers: Seq[(String, String)]
  )
} 
开发者ID:techyogillc,项目名称:ServerSideScalaCode,代码行数:42,代码来源:FormData.scala


示例20: TestPutObject

//设置package包名称以及导入依赖的类
package edu.goldlok.minio_scala.s3v4

import java.io.ByteArrayInputStream
import java.nio.charset.StandardCharsets

import akka.stream.scaladsl.Source
import akka.util.ByteString
import com.squareup.okhttp.mockwebserver.{MockResponse, MockWebServer}
import edu.goldlok.minio_scala.mio.MioClient
import org.scalatest.mockito.MockitoSugar
import org.scalatest.{FlatSpec, Matchers}

import scala.concurrent.Await


class TestPutObject extends FlatSpec with Matchers with MockitoSugar {
  import edu.goldlok.minio_scala.s3v4.TestElem._

  private def obtPutObjectServer(): MockWebServer = {
    val server = new MockWebServer()
    val response = new MockResponse()
    response.addHeader("Date", MON_29_JUN_2015_22_01_10_GMT)
    response.addHeader(LAST_MODIFIED, MON_04_MAY_2015_07_58_51_GMT)
    response.addHeader("ETag", MD5_HASH_STRING)
    response.setResponseCode(200)
    server.enqueue(response)
    server.start()
    server
  }

  private def testPutObject() =  {
    val server = obtPutObjectServer()
    val source = Source.single(ByteString(HELLO_WORLD))
    val response = MioClient(server.getHostName, server.getPort, keys).putObject(BUCKET, OBJECT, source, HELLO_WORLD.length)
    val uploadResult = Await.result(response, timeout)
    uploadResult.isSuccess should be (true)
    server.shutdown()
  }

  private def testPutObjectByStream() = {
    val server = obtPutObjectServer()
    val stream = new ByteArrayInputStream(HELLO_WORLD.getBytes(StandardCharsets.UTF_8))
    val response = MioClient(server.getHostName, server.getPort, keys).putObject(BUCKET, OBJECT, stream, HELLO_WORLD.length)
    val uploadResult = Await.result(response, timeout)
    uploadResult.isSuccess should be (true)
    server.shutdown()
  }

  "put object " should "return" in {
    testPutObject()
    testPutObjectByStream()
  }
} 
开发者ID:TopSpoofer,项目名称:minio-scala,代码行数:54,代码来源:TestPutObject.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Scala defaultContext类代码示例发布时间:2022-05-23
下一篇:
Scala Locale类代码示例发布时间: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