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


Scala Charsets类代码示例

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


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

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

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

示例3: SignedIssueRequest

//设置package包名称以及导入依赖的类
package scorex.api.http.assets

import com.google.common.base.Charsets
import io.swagger.annotations.{ApiModel, ApiModelProperty}
import play.api.libs.json.{Format, Json}
import scorex.account.PublicKeyAccount
import scorex.api.http.BroadcastRequest
import scorex.transaction.TransactionParser.SignatureStringLength
import scorex.transaction.ValidationError
import scorex.transaction.assets.IssueTransaction


object SignedIssueRequest {
  implicit val assetIssueRequestReads: Format[SignedIssueRequest] = Json.format
}

@ApiModel(value = "Signed Asset issue transaction")
case class SignedIssueRequest(@ApiModelProperty(value = "Base58 encoded Issuer public key", required = true)
                             senderPublicKey: String,
                              @ApiModelProperty(value = "Base58 encoded name of Asset", required = true)
                             name: String,
                              @ApiModelProperty(value = "Base58 encoded description of Asset", required = true)
                             description: String,
                              @ApiModelProperty(required = true, example = "1000000")
                             quantity: Long,
                              @ApiModelProperty(allowableValues = "range[0,8]", example = "8", dataType = "integer", required = true)
                             decimals: Byte,
                              @ApiModelProperty(required = true)
                             reissuable: Boolean,
                              @ApiModelProperty(required = true)
                             fee: Long,
                              @ApiModelProperty(required = true)
                             timestamp: Long,
                              @ApiModelProperty(required = true)
                             signature: String) extends BroadcastRequest {
  def toTx: Either[ValidationError, IssueTransaction] = for {
    _sender <- PublicKeyAccount.fromBase58String(senderPublicKey)
    _signature <- parseBase58(signature, "invalid signature", SignatureStringLength)
    _t <- IssueTransaction.create(_sender, name.getBytes(Charsets.UTF_8), description.getBytes(Charsets.UTF_8),
      quantity, decimals, reissuable, fee, timestamp, _signature)
  } yield _t
} 
开发者ID:wavesplatform,项目名称:Waves,代码行数:43,代码来源:SignedIssueRequest.scala

示例4: Handshake

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

import java.net.{InetAddress, InetSocketAddress}

import com.google.common.base.Charsets
import io.netty.buffer.ByteBuf

case class Handshake(
    applicationName: String,
    applicationVersion: (Int, Int, Int),
    nodeName: String,
    nodeNonce: Long,
    declaredAddress: Option[InetSocketAddress]) {
  def encode(out: ByteBuf): out.type = {
    out.writeByte(applicationName.length)
    out.writeBytes(applicationName.getBytes(Charsets.UTF_8))
    out.writeInt(applicationVersion._1)
    out.writeInt(applicationVersion._2)
    out.writeInt(applicationVersion._3)
    out.writeByte(nodeName.length)
    out.writeBytes(nodeName.getBytes(Charsets.UTF_8))
    out.writeLong(nodeNonce)
    declaredAddress match {
      case None => out.writeInt(0)
      case Some(addr) =>
        val addressBytes = addr.getAddress.getAddress
        out.writeInt(addressBytes.length + 4)
        out.writeBytes(addressBytes)
        out.writeInt(addr.getPort)
    }
    out.writeLong(System.currentTimeMillis() / 1000)

    out
  }
}

object Handshake {
  def decode(in: ByteBuf): Handshake = {
    val appNameSize = in.readByte()
    val appName = in.readSlice(appNameSize).toString(Charsets.UTF_8)
    val appVersion = (in.readInt(), in.readInt(), in.readInt())
    val nodeNameSize = in.readByte()
    val nodeName = in.readSlice(nodeNameSize).toString(Charsets.UTF_8)
    val nonce = in.readLong()
    val declaredAddressLength = in.readInt()
    // 0 for no declared address, 8 for ipv4 address + port, 20 for ipv6 address + port
    require(declaredAddressLength == 0 || declaredAddressLength == 8 || declaredAddressLength == 20,
      s"invalid declared address length: $declaredAddressLength")
    val isa = if (declaredAddressLength == 0) None else {
      val addressBytes = new Array[Byte](declaredAddressLength - 4)
      in.readBytes(addressBytes)
      val address = InetAddress.getByAddress(addressBytes)
      val port = in.readInt()
      Some(new InetSocketAddress(address, port))
    }
    in.readLong() // time is ignored

    Handshake(appName, appVersion, nodeName, nonce, isa)
  }
} 
开发者ID:wavesplatform,项目名称:Waves,代码行数:61,代码来源:Handshake.scala

示例5: basic644

//设置package包名称以及导入依赖的类
package uk.gov.hmrc.fileupload.support

import com.google.common.base.Charsets
import com.google.common.io.BaseEncoding
import org.scalatest.Suite
import play.api.http.HeaderNames
import play.api.libs.ws.WSResponse
import play.utils.UriEncoding
import uk.gov.hmrc.fileupload.{EnvelopeId, FileId, FileRefId}

trait FileActions extends ActionsSupport {
  this: Suite =>

  def basic644(s:String): String = {
    BaseEncoding.base64().encode(s.getBytes(Charsets.UTF_8))
  }

  def urlEncode(fileId: FileId) = UriEncoding.encodePathSegment(fileId.value, "UTF-8")


  def upload(data: Array[Byte], envelopeId: EnvelopeId, fileId: FileId, fileRefId: FileRefId): WSResponse =
    client
      .url(s"$url/envelopes/$envelopeId/files/$fileId/$fileRefId")
      .withHeaders("Content-Type" -> "application/octet-stream")
      .put(data)
      .futureValue

  def delete(envelopeId: EnvelopeId, fileId: FileId): WSResponse =
    client
      .url(s"$url/envelopes/$envelopeId/files/${urlEncode(fileId)}")
      .delete()
      .futureValue

  def download(envelopeId: EnvelopeId, fileId: FileId): WSResponse =
    client
      .url(s"$url/envelopes/$envelopeId/files/${urlEncode(fileId)}/content").withHeaders(HeaderNames.AUTHORIZATION -> ("Basic " + basic644("yuan:yaunspassword")))
      .get()
      .futureValue

  def getFileMetadataFor(envelopeId: EnvelopeId, fileId: FileId): WSResponse =
    client
      .url(s"$url/envelopes/$envelopeId/files/${urlEncode(fileId)}/metadata")
      .get()
      .futureValue

  def downloadEnvelope(envelopeId: EnvelopeId): WSResponse =
    client
      .url(s"$fileTransferUrl/envelopes/$envelopeId")
      .get()
      .futureValue
} 
开发者ID:hmrc,项目名称:file-upload,代码行数:52,代码来源:FileActions.scala

示例6: SignalRollingSyncLogWriter

//设置package包名称以及导入依赖的类
package core.util
import java.io.{File, FileOutputStream, IOException, OutputStream}
import java.nio.charset.Charset

import com.google.common.base.Charsets
import org.slf4j.LoggerFactory
import utils.{SigHandler, Signals}


class SignalRollingSyncLogWriter(file: File, bufferSize: Int = 8192, charset: Charset = Charsets.UTF_8) {
  private val lock = new Object
  private var fileStream: FileOutputStream = null
  private var stream: OutputStream = null

  openWriter()

  Signals.install(Signals.USR2, new SigHandler {
    def handle(signal: String) {
      lock.synchronized {
        try {
          closeWriter()
          openWriter()
        } catch {
          case e: IOException =>
            // ?? ??????, ??? ??? ????????? ?????? ??????????. ????????, ??? ????? ??????????.
            LoggerFactory.getLogger(getClass).error("LogWriter(" + file.getAbsolutePath + ") RolloverFailure occurred. Deferring roll-over.")
        }
      }
    }
  })

  def closeWriter() {
    lock.synchronized {
      if (stream != null) {
        stream.flush()
        stream.close()
        fileStream.close()
      }
      stream = null
      fileStream = null

    }
  }

  def openWriter() {
    lock.synchronized {
      if (stream != null) sys.error("Already opened")
      fileStream = new FileOutputStream(file, true)
      stream = if (bufferSize == 0) fileStream else new FastBufferedOutputStream(fileStream, bufferSize)
    }
  }

  def write(bytes: Array[Byte]): Unit = lock synchronized stream.write(bytes)
  def write(str: String): Unit = lock synchronized stream.write(str.getBytes(charset))
  def writeLn(str: String): Unit = lock synchronized {
    stream.write(str.getBytes(charset))
    stream.write('\n')
  }
} 
开发者ID:citrum,项目名称:storage-server,代码行数:60,代码来源:SignalRollingSyncLogWriter.scala

示例7: SignalRollingSyncLogWriter

//设置package包名称以及导入依赖的类
package webby.commons.system.log

import java.io._
import java.nio.charset.Charset

import com.google.common.base.Charsets
import webby.api.Logger
import webby.commons.io.FastBufferedOutputStream
import webby.commons.system.{SigHandler, Signals}


class SignalRollingSyncLogWriter(file: File, bufferSize: Int = 8192, charset: Charset = Charsets.UTF_8) {
  private val lock = new Object
  private var fileStream: FileOutputStream = null
  private var stream: OutputStream = null

  openWriter()

  Signals.install(Signals.USR2, new SigHandler {
    def handle(signal: String) {
      lock.synchronized {
        try {
          closeWriter()
          openWriter()
        } catch {
          case e: IOException =>
            // ?? ??????, ??? ??? ????????? ?????? ??????????. ????????, ??? ????? ??????????.
            Logger.error("LogWriter(" + file.getAbsolutePath + ") RolloverFailure occurred. Deferring roll-over.")
        }
      }
    }
  })

  def closeWriter() {
    lock.synchronized {
      if (stream != null) {
        stream.flush()
        stream.close()
        fileStream.close()
      }
      stream = null
      fileStream = null

    }
  }

  def openWriter() {
    lock.synchronized {
      if (stream != null) sys.error("Already opened")
      fileStream = new FileOutputStream(file, true)
      stream = if (bufferSize == 0) fileStream else new FastBufferedOutputStream(fileStream, bufferSize)
    }
  }

  def write(bytes: Array[Byte]): Unit = lock synchronized stream.write(bytes)
  def write(str: String): Unit = lock synchronized stream.write(str.getBytes(charset))
  def writeLn(str: String): Unit = lock synchronized {
    stream.write(str.getBytes(charset))
    stream.write('\n')
  }
} 
开发者ID:citrum,项目名称:webby,代码行数:62,代码来源:SignalRollingSyncLogWriter.scala

示例8: ScriptCompiler

//设置package包名称以及导入依赖的类
package webby.mvc.script.compiler
import java.io.OutputStream
import java.nio.file.{Files, Path}
import javax.annotation.Nullable

import com.google.common.base.Charsets
import webby.commons.io.IOUtils

abstract class ScriptCompiler {

  def sourceFileExt: String
  def targetFileExt: String
  def targetContentType: String
  def sourceMapFileExt: Option[String] = None

  def compile(source: String, sourcePath: Path): Either[String, String]

  def compileFile(sourcePath: Path, outputPath: Path): Either[String, Unit] = {
    val source = new String(Files.readAllBytes(sourcePath), Charsets.UTF_8)
    compile(source, sourcePath).right.map {result =>
      Files.createDirectories(outputPath.getParent)
      Files.write(outputPath, result.getBytes(Charsets.UTF_8))
      Right(())
    }
  }

  protected def runCommonProcess(command: Seq[String],
                                 @Nullable input: String = null,
                                 env: Seq[String] = Nil): Either[String, String] = {
    val proc: Process = Runtime.getRuntime.exec(command.toArray, if (env.isEmpty) null else env.toArray)

    if (input != null) {
      val os: OutputStream = proc.getOutputStream
      os.write(input.getBytes)
      os.close()
    }
    val result: String = IOUtils.readString(proc.getInputStream)
    val errors: String = IOUtils.readString(proc.getErrorStream)
    proc.waitFor()
    if (proc.exitValue() == 0 && errors.isEmpty) Right(result)
    else Left(errors)
  }

  val sourceDotExt: String = "." + sourceFileExt
  val targetDotExt: String = "." + targetFileExt
  val sourceMapDotExt: Option[String] = sourceMapFileExt.map("." + _)

  def npmScriptPath = "script/npm/node_modules/.bin"

  
  def lazyCompiler = false
} 
开发者ID:citrum,项目名称:webby,代码行数:53,代码来源:ScriptCompiler.scala

示例9: basic644

//设置package包名称以及导入依赖的类
package uk.gov.hmrc.fileupload.support

import com.google.common.base.Charsets
import com.google.common.io.BaseEncoding
import org.scalatest.Suite
import play.api.http.HeaderNames
import play.api.libs.ws.WSResponse
import uk.gov.hmrc.fileupload.{EnvelopeId, FileId, FileRefId}

trait FileActions extends ActionsSupport {
  this: Suite =>

  def basic644(s:String): String = {
    BaseEncoding.base64().encode(s.getBytes(Charsets.UTF_8))
  }

  def upload(data: Array[Byte], envelopeId: EnvelopeId, fileId: FileId, fileRefId: FileRefId): WSResponse =
    client
      .url(s"$url/envelopes/$envelopeId/files/$fileId/$fileRefId")
      .withHeaders("Content-Type" -> "application/octet-stream")
      .put(data)
      .futureValue

  def delete(envelopeId: EnvelopeId, fileId: FileId): WSResponse =
    client
      .url(s"$url/envelopes/$envelopeId/files/$fileId")
      .delete()
      .futureValue

  def download(envelopeId: EnvelopeId, fileId: FileId): WSResponse =
    client
      .url(s"$url/envelopes/$envelopeId/files/$fileId/content").withHeaders(HeaderNames.AUTHORIZATION -> ("Basic " + basic644("yuan:yaunspassword")))
      .get()
      .futureValue

  def updateFileMetadata(data: String, envelopeId: EnvelopeId, fileId: FileId): WSResponse =
    client
      .url(s"$url/envelopes/$envelopeId/files/$fileId/metadata" )
      .withHeaders("Content-Type" -> "application/json")
      .put(data.getBytes)
      .futureValue

  def getFileMetadataFor(envelopeId: EnvelopeId, fileId: FileId): WSResponse =
    client
      .url(s"$url/envelopes/$envelopeId/files/$fileId/metadata")
      .get()
      .futureValue

  def downloadEnvelope(envelopeId: EnvelopeId): WSResponse =
    client
      .url(s"$fileTransferUrl/envelopes/$envelopeId")
      .get()
      .futureValue
} 
开发者ID:hmrc,项目名称:file-upload-nos3,代码行数:55,代码来源:FileActions.scala


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