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

Scala Base64类代码示例

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

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



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

示例1: EncryptionUtility

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

import java.util.Base64
import javax.crypto.Cipher
import javax.crypto.spec.{IvParameterSpec, SecretKeySpec}

object EncryptionUtility {
  private val Algorithm = "AES/CBC/PKCS5Padding"
  private val Key = new SecretKeySpec(Base64.getDecoder.decode("DxVnlUlQSu3E5acRu7HPwg=="), "AES")
  private val IvSpec = new IvParameterSpec(new Array[Byte](16))

  val AdminKey = "Dx$V!nl%Ul^QS&u3*[email protected]=="

  def encrypt(text: String): String = {
    val cipher = Cipher.getInstance(Algorithm)
    cipher.init(Cipher.ENCRYPT_MODE, Key, IvSpec)

    new String(Base64.getEncoder.encode(cipher.doFinal(text.getBytes("utf-8"))), "utf-8")
  }

  def decrypt(text: String): String = {
    val cipher = Cipher.getInstance(Algorithm)
    cipher.init(Cipher.DECRYPT_MODE, Key, IvSpec)

    new String(cipher.doFinal(Base64.getDecoder.decode(text.getBytes("utf-8"))), "utf-8")
  }
} 
开发者ID:knoldus,项目名称:knolx-portal,代码行数:28,代码来源:EncryptionUtility.scala


示例2: SecurityUtil

//设置package包名称以及导入依赖的类
package com.qingstor.sdk.util

import java.security.MessageDigest
import java.util.Base64
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec

object SecurityUtil {
  def getMD5(string: String): Array[Byte] = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"))

  def getHmacSHA256(key: String, content: String): Array[Byte] = {
    val secret = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256")
    val mac = Mac.getInstance("HmacSHA256")
    mac.init(secret)
    mac.doFinal(content.getBytes("UTF-8"))
  }

  def encodeToBase64String(bytes: Array[Byte]): String = Base64.getEncoder.encodeToString(bytes)
} 
开发者ID:yunify,项目名称:qingstor-sdk-scala,代码行数:20,代码来源:SecurityUtil.scala


示例3: ConsulStoreActorMapper

//设置package包名称以及导入依赖的类
package io.vamp.persistence.consul

import java.util.Base64

import akka.http.scaladsl.model.ContentTypes
import io.vamp.common.{ ClassMapper, Config }
import io.vamp.persistence.KeyValueStoreActor

import scala.concurrent.Future

class ConsulStoreActorMapper extends ClassMapper {
  val name = "consul"
  val clazz = classOf[ConsulStoreActor]
}

class ConsulStoreActor extends KeyValueStoreActor {

  private lazy val url = Config.string("vamp.persistence.key-value-store.consul.url")()

  override protected def info(): Future[Any] = httpClient.get[Any](s"$url/v1/agent/self") map { consul ?
    Map("type" ? "consul", "consul" ? consul)
  }

  override protected def all(path: List[String]): Future[List[String]] = {
    val key = pathToString(path)
    checked[List[String]](httpClient.get[List[String]](urlOf(path, keys = true), logError = false) recover { case _ ? Nil }) map { list ?
      list.map(_.substring(key.length))
    }
  }

  override protected def get(path: List[String]): Future[Option[String]] = {
    httpClient.get[List[_]](urlOf(path), logError = false) recover { case _ ? None } map {
      case head :: Nil ? Option(result(head.asInstanceOf[Map[_, _]]))
      case _           ? None
    }
  }

  override protected def set(path: List[String], data: Option[String]): Future[Any] = data match {
    case None        ? httpClient.delete(urlOf(path), logError = false)
    case Some(value) ? httpClient.put[Any](urlOf(path), value, contentType = ContentTypes.`text/plain(UTF-8)`)
  }

  private def urlOf(path: List[String], keys: Boolean = false) = {
    s"$url/v1/kv${pathToString(path)}${if (keys) "?keys" else ""}"
  }

  private def result(map: Map[_, _]): String = map.asInstanceOf[Map[String, _]].get("Value") match {
    case Some(value) if value != null ? new String(Base64.getDecoder.decode(value.asInstanceOf[String]))
    case _                            ? ""
  }
} 
开发者ID:magneticio,项目名称:vamp-consul,代码行数:52,代码来源:ConsulStoreActor.scala


示例4: Player

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

import java.time.format.DateTimeFormatter
import java.time.temporal.ChronoUnit
import java.time.{Clock, LocalDateTime}
import java.util.{Base64, UUID}
import javax.crypto.spec.SecretKeySpec
import javax.crypto.{KeyGenerator, Mac}

@SerialVersionUID(1L)
class Player(val id: UUID, val name: String, val secret: String) extends Serializable {
  override def hashCode = id.hashCode()

  override def equals(other: Any) = other match {
    case that: Player => this.id == that.id
    case _ => false
  }

  override def toString = s"$name ($id)"

  def identity = PlayerIdentity(id, name)

  def isAuthorized(time: LocalDateTime, signature: String): Boolean = {
    val seconds = ChronoUnit.SECONDS.between(time, LocalDateTime.now(Clock.systemUTC()))

    if (seconds < -300 || seconds > 300) {
      false
    } else {
      val secretKeySpec = new SecretKeySpec(secret.getBytes, "HmacSHA256")
      val mac = Mac.getInstance("HmacSHA256")
      mac.init(secretKeySpec)

      val message = id.toString.toLowerCase + "|" + time.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
      val hmac = mac.doFinal(message.getBytes("UTF-8"))

      val encoded = Base64.getEncoder.encodeToString(hmac)

      encoded.equalsIgnoreCase(signature)
    }
  }
}

object Player {
  def apply(name: String) = new Player(UUID.randomUUID(), name, generateKey)

  def apply(id: UUID, name: String) = new Player(id, name, generateKey)

  private def generateKey: String = {
    val keyGenerator: KeyGenerator = KeyGenerator.getInstance("HmacSHA256")
    Base64.getEncoder.encodeToString(keyGenerator.generateKey().getEncoded)
  }

  def apply(id: UUID, name: String, secret: String) = new Player(id, name, secret)

  def apply(identity: PlayerIdentity) = new Player(identity.id, identity.name, generateKey)

  def apply(identity: PlayerIdentity, secret: String) = new Player(identity.id, identity.name, secret)
}

case class PlayerIdentity(id: UUID, name: String) 
开发者ID:Morgan-Stanley,项目名称:proton,代码行数:61,代码来源:Player.scala


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


示例6: TrackingController

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

import java.security.MessageDigest

import play.api._
import play.api.libs.Codecs
import play.api.mvc._
// Java8 lib
import java.util.Base64

class TrackingController extends Controller {

  val COOKIE_KEY = "Z_SYSTEM_3RD_PARTY_COOKIE_ID_SCALA"
  val COOKIE_MAX_AFTER_AGE = Some(31622400 + 31622400)

  //ref https://css-tricks.com/snippets/html/base64-encode-of-1x1px-transparent-gif/
  val onePixelGifBase64 = "R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"
  val onePixelGifBytes = Base64.getDecoder().decode(onePixelGifBase64)

  def pixelTracking = Action {request =>
    val cookies = request.cookies
    val cookieValue = cookies.get(COOKIE_KEY).map { cookie =>
      Logger.debug(s"Cookie Exist! ${cookie.value}")
      cookie.value
    }.getOrElse {
      val newValue = uniqueIdGenerator()
      Logger.debug("Cookie Generate! $newValue")
      newValue
    }
    Ok(onePixelGifBytes).withCookies(Cookie(COOKIE_KEY, cookieValue, COOKIE_MAX_AFTER_AGE)).as("image/gif")
  }

  val uniqueIdGenerator = () => {
    val milliTime = System.currentTimeMillis()
    val nanoTime = System.nanoTime()
    val baseString = s"$milliTime $nanoTime"
    Logger.debug(baseString)

    val md = MessageDigest.getInstance("SHA-256")
    md.update(baseString.getBytes())

    val id = Codecs.toHexString(md.digest())
    Logger.debug(id)
    id
  }
} 
开发者ID:uryyyyyyy,项目名称:adReferenceImplementation,代码行数:47,代码来源:TrackingController.scala


示例7: SauceLabsClient

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

import java.nio.ByteBuffer
import java.util.Base64
import javax.net.ssl.SSLContext

import org.http4s.blaze.channel.nio2.ClientChannelFactory
import org.http4s.blaze.http.{HttpClient, HttpResponse}
import org.http4s.blaze.util.{Execution, GenericSSLContext}

import scala.concurrent.{Await, Future}
import scala.concurrent.duration._


class SauceLabsClient(userName: String, accessKey: String, jobId: String) extends HttpClient {

  import scala.concurrent.ExecutionContext.Implicits.global

  override lazy val connectionManager = new ClientChannelFactory()
  override protected val sslContext: SSLContext = GenericSSLContext.clientSSLContext()

  def setName(name: String): Unit = {
    putToJob(s"""{"name": "$name"}""")
  }

  def setPassed(passed: Boolean): Unit = {
    putToJob(s"""{"passed": $passed}""")
  }

  def putToJob(data: String): Unit = {
    val authorization = {
      val s = s"$userName:$accessKey"
      Base64.getEncoder.encodeToString(s.getBytes)
    }
    val headers = Seq(
      "content-type" -> "application/json",
      "authorization" -> s"Basic $authorization"
    )
    val response = PUT(
      url = s"https://saucelabs.com/rest/v1/$userName/jobs/$jobId", headers,
      body = ByteBuffer.wrap(data.getBytes),
      5 seconds
    )
    Await.result(response, 10 seconds)
  }

  // Cause blaze client doesn't support anything else GET!
  def PUT(url: String, headers: Seq[(String, String)], body: ByteBuffer,timeout: Duration): Future[HttpResponse] = {
    val r = runReq("PUT", url, headers, body, timeout)
    r.flatMap {
      case r: HttpResponse => Future.successful(r)
      case r => Future.failed(new Exception(s"Received invalid response type: ${r.getClass}"))
    }(Execution.directec)
  }
} 
开发者ID:techyogillc,项目名称:ServerSideScalaCode,代码行数:56,代码来源:SauceLabsClient.scala


示例8: UuidUtil

//设置package包名称以及导入依赖的类
package com.dbrsn.datatrain.util

import java.nio.ByteBuffer
import java.util.Base64
import java.util.UUID

object UuidUtil {
  private val encoder: Base64.Encoder = Base64.getUrlEncoder
  private val decoder: Base64.Decoder = Base64.getUrlDecoder

  private val lastRedundantCharacters: String = "=="

  def toBase64(uuid: UUID): String = {
    val uuidBytes = ByteBuffer.wrap(new Array[Byte](16))
    uuidBytes.putLong(uuid.getMostSignificantBits)
    uuidBytes.putLong(uuid.getLeastSignificantBits)
    val result = encoder.encodeToString(uuidBytes.array())
    if (result.endsWith(lastRedundantCharacters)) {
      result.substring(0, result.length - lastRedundantCharacters.length)
    } else {
      result
    }
  }

  def toUuid(str: String): UUID = try {
    UUID.fromString(str)
  } catch {
    case e: IllegalArgumentException =>
      val uuidBytes = ByteBuffer.wrap(decoder.decode(str))
      val result = new UUID(uuidBytes.getLong, uuidBytes.getLong)
      if (uuidBytes.hasRemaining) {
        throw new IllegalArgumentException("Invalid UUID string: " + str)
      }
      result
  }
} 
开发者ID:dborisenko,项目名称:data-train,代码行数:37,代码来源:UuidUtil.scala


示例9: MsgPack

//设置package包名称以及导入依赖的类
package com.taxis99.amazon.serializers

import java.util.Base64

import com.typesafe.scalalogging.Logger
import msgpack4z.{MsgOutBuffer, _}
import org.slf4j.LoggerFactory
import play.api.libs.json.{JsValue, Json}

object MsgPack extends ISerializer {
  protected val logger: Logger =
    Logger(LoggerFactory.getLogger(getClass.getName))

  protected val jsonVal = Play2Msgpack.jsValueCodec(PlayUnpackOptions.default)
  protected val b64encoder = Base64.getEncoder
  protected val b64decoder = Base64.getDecoder

  
  override def decode(value: String): JsValue = {
    val bytes: Array[Byte] = b64decoder.decode(value)
    val unpacker = MsgInBuffer.apply(bytes)
    val unpacked = jsonVal.unpack(unpacker)
    unpacked.valueOr { e =>
      logger.error("Could not decode message", e)
      new ClassCastException("Could not decode message")
      Json.obj()
    }
  }
} 
开发者ID:99Taxis,项目名称:common-sqs,代码行数:30,代码来源:MsgPack.scala


示例10: SauceLabsClient

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

import java.nio.ByteBuffer
import java.util.Base64
import javax.net.ssl.SSLContext

import org.http4s.blaze.channel.nio2.ClientChannelFactory
import org.http4s.blaze.http.{HttpClient, HttpResponse}
import org.http4s.blaze.util.{Execution, GenericSSLContext}

import scala.concurrent.{Await, Future}
import scala.concurrent.duration._

class SauceLabsClient(userName: String, accessKey: String, jobId: String) extends HttpClient {

  import scala.concurrent.ExecutionContext.Implicits.global

  override lazy val connectionManager = new ClientChannelFactory()
  override protected val sslContext: SSLContext = GenericSSLContext.clientSSLContext()

  def setName(name: String): Unit = {
    putToJob(s"""{"name": "$name"}""")
  }

  def setPassed(passed: Boolean): Unit = {
    putToJob(s"""{"passed": $passed}""")
  }

  def putToJob(data: String): Unit = {
    val authorization = {
      val s = s"$userName:$accessKey"
      Base64.getEncoder.encodeToString(s.getBytes)
    }
    val headers = Seq(
      "content-type" -> "application/json",
      "authorization" -> s"Basic $authorization"
    )
    val response = PUT(
      url = s"https://saucelabs.com/rest/v1/$userName/jobs/$jobId", headers,
      body = ByteBuffer.wrap(data.getBytes),
      5 seconds
    )
    Await.result(response, 10 seconds)
    ()
  }

  // Cause blaze client doesn't support anything else GET!
  def PUT(url: String, headers: Seq[(String, String)], body: ByteBuffer,timeout: Duration): Future[HttpResponse] = {
    val r = runReq("PUT", url, headers, body, timeout)
    r.flatMap {
      case r: HttpResponse => Future.successful(r)
      case _ => Future.failed(new Exception(s"Received invalid response type: ${r.getClass}"))
    }(Execution.directec)
  }
} 
开发者ID:fomkin,项目名称:korolev,代码行数:56,代码来源:SauceLabsClient.scala


示例11: Ecr

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

import java.util.Base64

import com.amazonaws.regions.Region
import com.amazonaws.services.ecr.AmazonECRClient
import com.amazonaws.services.ecr.model._
import sbt.Logger

import scala.collection.JavaConverters._

private[sbtecr] object Ecr extends Aws {

  def domain(region: Region, accountId: String) = s"${accountId}.dkr.ecr.${region}.amazonaws.com"

  def createRepository(region: Region, repositoryName: String)(implicit logger: Logger): Unit = {
    val request = new CreateRepositoryRequest()
    request.setRepositoryName(repositoryName)

    try {
      val result = ecr(region).createRepository(request)
      logger.info(s"Repository created in ${region}: arn=${result.getRepository.getRepositoryArn}")
    } catch {
      case e: RepositoryAlreadyExistsException =>
        logger.info(s"Repository exists: ${region}/${repositoryName}")
    }
  }

  def dockerCredentials(region: Region)(implicit logger: Logger): (String, String) = {
    val request = new GetAuthorizationTokenRequest()
    val response = ecr(region).getAuthorizationToken(request)

    response
      .getAuthorizationData
      .asScala
      .map(_.getAuthorizationToken)
      .map(Base64.getDecoder.decode(_))
      .map(new String(_, "UTF-8"))
      .map(_.split(":"))
      .headOption match {
        case Some(creds) if creds.size == 2 =>
          (creds(0), creds(1))
        case _ =>
          throw new IllegalStateException("Authorization token not found.")
      }
  }

  private def ecr(region: Region) = client(classOf[AmazonECRClient], region)
} 
开发者ID:sbilinski,项目名称:sbt-ecr,代码行数:50,代码来源:Ecr.scala


示例12: Keys

//设置package包名称以及导入依赖的类
package com.malliina.aws.cognito

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

object Keys {
  val keyFactory = KeyFactory.getInstance("RSA")

  def publicKey(key: JWTKey): RSAPublicKey =
    publicKey(toBigInt(key.n), toBigInt(key.e))

  private def publicKey(modulus: BigInteger, exponent: BigInteger): RSAPublicKey = {
    val keySpec = new RSAPublicKeySpec(modulus, exponent)
    keyFactory.generatePublic(keySpec).asInstanceOf[RSAPublicKey]
  }

  private def toBigInt(enc: String): BigInteger =
    new BigInteger(1, Base64.getUrlDecoder.decode(enc))
} 
开发者ID:malliina,项目名称:cognito-utils,代码行数:23,代码来源:Keys.scala


示例13: Plist

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

import java.security.{PrivateKey, Signature}
import java.util.Base64

import org.bouncycastle.pkcs.PKCS10CertificationRequest

case class Plist(csr: PKCS10CertificationRequest, chain: String, privateKey: PrivateKey) {

  def toXml = {
    val csrString = Base64.getEncoder.encodeToString(csr.getEncoded)
    val signature = Signature.getInstance("SHA1WithRSA")
    signature.initSign(privateKey)
    signature.update(csr.getEncoded)
    val signatureString = Base64.getEncoder.encodeToString(signature.sign)

    s"""<?xml version="1.0" encoding="UTF-8"?>
       |<!DOCTYPE plist PUBLIC "-//Apple Inc//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
       |<plist version="1.0">
       |<dict>
       |<key>PushCertRequestCSR</key>
       |<string>
       |$csrString
       |</string>
       |<key>PushCertCertificateChain</key>
       |<string>
       |$chain
       |</string>
       |<key>PushCertSignature</key>
       |<string>
       |$signatureString
       |</string>
       |</dict>
       |</plist>
     """.stripMargin
  }

} 
开发者ID:takesection,项目名称:apple-mdm-certificate,代码行数:39,代码来源:Plist.scala


示例14: PlistFactory

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

import java.security.PrivateKey
import java.util.Base64

import org.bouncycastle.pkcs.PKCS10CertificationRequest

object PlistFactory {

  def generate(csr: PKCS10CertificationRequest,
                    vendorCertificate: String,
                    appleCertificate: String,
                    appleRootCertificate: String,
                    vendorPrivateKey: PrivateKey) = {
    val plist = generatePlist(csr, vendorCertificate + "\n" + appleCertificate + "\n" + appleRootCertificate, vendorPrivateKey)
    Base64.getEncoder.encodeToString(plist.getBytes())
  }

  def generatePlist(csr: PKCS10CertificationRequest,
                    chain: String,
                    vendorPrivateKey: PrivateKey) = {
    val plist = Plist(csr, chain, vendorPrivateKey)
    plist.toXml
  }

} 
开发者ID:takesection,项目名称:apple-mdm-certificate,代码行数:27,代码来源:PlistFactory.scala


示例15: CryptoOperations

//设置package包名称以及导入依赖的类
package io.clouderite.commons.scala.berries.crypto

import java.util.Base64
import javax.crypto.Cipher
import javax.crypto.spec.{IvParameterSpec, SecretKeySpec}

class CryptoOperations(text: String) {
  private val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")

  def encrypt(key: String, iv: String): String = {
    cipher.init(Cipher.ENCRYPT_MODE, keySpec(key), paramSpec(iv))
    Base64.getEncoder.encodeToString(cipher.doFinal(text.getBytes()))
  }

  def decrypt(key: String, iv: String): String = {
    cipher.init(Cipher.DECRYPT_MODE, keySpec(key), paramSpec(iv))
    new String(cipher.doFinal(Base64.getDecoder.decode(text)))
  }

  def keySpec(key: String) = new SecretKeySpec(key.getBytes(), "AES")
  def paramSpec(iv: String) = new IvParameterSpec(iv.getBytes())
}

object CryptoOperations {
  implicit def toCryptoOperations(text: String): CryptoOperations = new CryptoOperations(text)
} 
开发者ID:clouderite,项目名称:scala-berries,代码行数:27,代码来源:CryptoOperations.scala


示例16: UrlReader

//设置package包名称以及导入依赖的类
// UrlReader.scala
package com.peopledesigned.askrtd.util
import java.util.Base64

object UrlReader {
  @throws(classOf[java.io.IOException])
  @throws(classOf[java.net.SocketTimeoutException])
  def get(url: String,
      connectTimeout: Int = 5000,
      readTimeout: Int = 5000,
      requestMethod: String = "GET") = getWithAuthentication(url, connectTimeout, readTimeout, requestMethod)

  def getAuthenticated(url: String,
      connectTimeout: Int = 5000,
      readTimeout: Int = 5000,
      requestMethod: String = "GET",
      authStr: Option[String] = None) = getWithAuthentication(url, connectTimeout, readTimeout, requestMethod, authStr)

  def getAuthenticatedStream(url: String,
      connectTimeout: Int = 5000,
      readTimeout: Int = 5000,
      requestMethod: String = "GET") = getWithAuthenticationStream(url, connectTimeout, readTimeout, requestMethod, Some("RTDgtfsRT:realT!m3Feed"))

  def getWithAuthentication(url: String,
      connectTimeout: Int = 5000,
      readTimeout: Int = 5000,
      requestMethod: String = "GET",
      authStr: Option[String] = None) =
  {
    val inputStream = getWithAuthenticationStream(url, connectTimeout, readTimeout, requestMethod, authStr)
    val content = io.Source.fromInputStream(inputStream).mkString
    if (inputStream != null) inputStream.close
    content
  }

  def getWithAuthenticationStream(url: String,
      connectTimeout: Int = 5000,
      readTimeout: Int = 5000,
      requestMethod: String = "GET",
      authStr: Option[String] = None) =
  {
    import java.net.{URL, HttpURLConnection}
    val connection = (new URL(url)).openConnection.asInstanceOf[HttpURLConnection]
    if (!authStr.isEmpty) {
      val bytesEncoded = Base64.getEncoder().encodeToString(authStr.get.getBytes());
      connection.setRequestProperty("Authorization", "Basic "+bytesEncoded);
    }
    connection.setConnectTimeout(connectTimeout)
    connection.setReadTimeout(readTimeout)
    connection.setRequestMethod(requestMethod)
    connection.getInputStream
  }
} 
开发者ID:Java1Guy,项目名称:alexa-askrtd-skill,代码行数:54,代码来源:UrlReader.scala


示例17: UploadLogFileSimulation

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

import java.io.StringWriter
import java.nio.charset.StandardCharsets
import java.util.{Base64, UUID}

import com.fasterxml.jackson.databind.ObjectMapper
import io.gatling.core.Predef._
import io.gatling.http.Predef._

class UploadLogFileSimulation extends Simulation {

	val httpProtocol = http
		.baseURL("http://192.168.10.56:9610")
		.inferHtmlResources()
		.acceptHeader("*/*")
		.authorizationHeader("bearer 864a39eb-6acb-4816-84c4-66344a46e156")
		.contentTypeHeader("multipart/form-data; boundary=----------------------507d18cf8b72b879")

	val mapper = new ObjectMapper()

	val users = 10

    def genHeader : Map[String, String] = {
    	val fid = UUID.randomUUID.toString.replace("-", "").toLowerCase

    	val map = new java.util.HashMap[String, Object]()
	    map.put("uid", "08a0e07727c744cfb1685e5ca9d44890")
	    map.put("bid", "com.getui.logful.sample")
	    map.put("sum", "d59e7bd21724afffb4af97ea6b3e46cb")
	    map.put("aid", "57ac4fe045cea34392ac4fbc")
	    map.put("ver", "0.4.2")
	    map.put("plt", new Integer(1))
	    map.put("fid", fid)

	    val writer = new StringWriter
	    mapper.writeValue(writer, map)
	    val extra = writer.toString()

	    val xExtra = Base64.getEncoder.encodeToString(extra.getBytes(StandardCharsets.UTF_8))

	    return Map("Charsert" -> "UTF-8", "X-EXTRA" -> xExtra)
    }

    val headerFeeder = new Array[Map[String, String]](users)
    for ( i <- 0 to (headerFeeder.length - 1)) {
    	headerFeeder(i) = genHeader
    }

    val uri1 = "http://demo.logful.aoapp.com:9600/v1/log/file/upload"

	val scn = scenario("UploadLogFileSimulation")
	    .feed(headerFeeder)
		.exec(http("uploadLogFile")
		.post("/v1/log/file/upload")
		.headers(Map("Charsert" -> "${Charsert}", "X-EXTRA" -> "${X-EXTRA}"))
		.body(RawFileBody("RecordedSimulation_0000_request.txt"))
		.check(status.is(202)))
	setUp(scn.inject(atOnceUsers(users)).protocols(httpProtocol))
} 
开发者ID:foxundermoon,项目名称:gatling-test,代码行数:61,代码来源:UploadLogFileSimulation.scala


示例18: genHeader

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

import java.io.StringWriter
import java.nio.charset.StandardCharsets
import java.util.{Base64, UUID}

import com.fasterxml.jackson.databind.ObjectMapper
import io.gatling.core.Predef._
import io.gatling.http.Predef._

*")
    .authorizationHeader("bearer 4accb24d-729c-47a2-8a28-49d507da3771")
    .contentTypeHeader("multipart/form-data; boundary=------------------------6f0a94c2837b005a")

  val mapper = new ObjectMapper()

  def genHeader: Map[String, String] = {
    val fid = UUID.randomUUID.toString.replace("-", "").toLowerCase

    val map = new java.util.HashMap[String, Object]()
    map.put("uid", "9941dda1623c4170b8fab36e0c447596")
    map.put("bid", "com.getui.logful.sample")
    map.put("sum", "8a511dd405209a10210cb4e1579a892c")
    map.put("aid", "57b56c5045ce1a6089f81d84")
    map.put("ver", "0.4.2")
    map.put("plt", new Integer(1))
    map.put("fid", fid)

    val writer = new StringWriter
    mapper.writeValue(writer, map)
    val extra = writer.toString()

    val xExtra = Base64.getEncoder.encodeToString(extra.getBytes(StandardCharsets.UTF_8))

    return Map("Charsert" -> "UTF-8", "X-EXTRA" -> xExtra)
  }

  val headerFeeder = new Array[Map[String, String]](users)
  for (i <- 0 to (headerFeeder.length - 1)) {
    headerFeeder(i) = genHeader
  }

  val scn = scenario("DebugSmallLogSimulation")
    .feed(headerFeeder)
    .exec(http("request_0")
      .post("/v1/log/file/upload")
      .headers(Map("Charsert" -> "${Charsert}", "X-EXTRA" -> "${X-EXTRA}"))
      .body(RawFileBody("RecordedSimulation_d_request.txt"))
      .check(status.is(202))
    )
} 
开发者ID:foxundermoon,项目名称:gatling-test,代码行数:52,代码来源:DebugLogFileReqConfig.scala


示例19: genHeader

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

import java.io.StringWriter
import java.nio.charset.StandardCharsets
import java.util.{Base64, UUID}

import com.fasterxml.jackson.databind.ObjectMapper
import io.gatling.core.Predef._
import io.gatling.http.Predef._

*")
    .authorizationHeader("bearer 4accb24d-729c-47a2-8a28-49d507da3771")
    .contentTypeHeader("multipart/form-data; boundary=------------------------b83ee7b4869ff609")

  val mapper = new ObjectMapper()

  def genHeader: Map[String, String] = {
    val fid = UUID.randomUUID.toString.replace("-", "").toLowerCase

    val map = new java.util.HashMap[String, Object]()
    map.put("uid", "9941dda1623c4170b8fab36e0c447596")
    map.put("bid", "com.getui.logful.sample")
    map.put("sum", "bc84c286c4d53b6a4d843ca288292329")
    map.put("aid", "57b56c5045ce1a6089f81d84")
    map.put("ver", "0.4.2")
    map.put("plt", new Integer(1))
    map.put("fid", fid)

    val writer = new StringWriter
    mapper.writeValue(writer, map)
    val extra = writer.toString()

    val xExtra = Base64.getEncoder.encodeToString(extra.getBytes(StandardCharsets.UTF_8))

    return Map("Charsert" -> "UTF-8", "X-EXTRA" -> xExtra)
  }

  val headerFeeder = new Array[Map[String, String]](users)
  for (i <- 0 to (headerFeeder.length - 1)) {
    headerFeeder(i) = genHeader
  }

  val scn = scenario("SmallLogSimulation")
    .feed(headerFeeder)
    .exec(http("request_0")
      .post("/v1/log/file/upload")
      .headers(Map("Charsert" -> "${Charsert}", "X-EXTRA" -> "${X-EXTRA}"))
      .body(RawFileBody("RecordedSimulation_0000_request.txt"))
      .check(status.is(202))
    )
} 
开发者ID:foxundermoon,项目名称:gatling-test,代码行数:52,代码来源:LogFileReqConfig.scala


示例20: genHeader

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

import java.io.StringWriter
import java.nio.charset.StandardCharsets
import java.util.{Base64, UUID}

import com.fasterxml.jackson.databind.ObjectMapper
import io.gatling.core.Predef._
import io.gatling.http.Predef._

*")
    .authorizationHeader("bearer 4accb24d-729c-47a2-8a28-49d507da3771")
    .contentTypeHeader("multipart/form-data; boundary=------------------------1bb290f73703a153")

  val mapper = new ObjectMapper()

  def genHeader: Map[String, String] = {
    val fid = UUID.randomUUID.toString.replace("-", "").toLowerCase

    val map = new java.util.HashMap[String, Object]()
    map.put("uid", "9941dda1623c4170b8fab36e0c447596")
    map.put("bid", "com.getui.logful.sample")
    map.put("sum", "8a511dd405209a10210cb4e1579a892c")
    map.put("aid", "57b56c5045ce1a6089f81d84")
    map.put("ver", "0.4.2")
    map.put("plt", new Integer(1))
    map.put("fid", fid)

    val writer = new StringWriter
    mapper.writeValue(writer, map)
    val extra = writer.toString()

    val xExtra = Base64.getEncoder.encodeToString(extra.getBytes(StandardCharsets.UTF_8))

    return Map("Charsert" -> "UTF-8", "X-EXTRA" -> xExtra)
  }

  val headerFeeder = new Array[Map[String, String]](users)
  for (i <- 0 to (headerFeeder.length - 1)) {
    headerFeeder(i) = genHeader
  }

  val scn = scenario("VerboseSmallLogSimulation")
    .feed(headerFeeder)
    .exec(http("request_0")
      .post("/v1/log/file/upload")
      .headers(Map("Charsert" -> "${Charsert}", "X-EXTRA" -> "${X-EXTRA}"))
      .body(RawFileBody("RecordedSimulation_v_request.txt"))
      .check(status.is(202))
    )
} 
开发者ID:foxundermoon,项目名称:gatling-test,代码行数:52,代码来源:VerboseLogFileReqConfig.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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