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

Scala StringWriter类代码示例

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

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



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

示例1: exportReply

//设置package包名称以及导入依赖的类
package com.github.norwae.ignifera

import java.io.StringWriter

import akka.http.scaladsl.model.{ContentType, HttpEntity, HttpResponse}
import akka.util.ByteString
import io.prometheus.client.CollectorRegistry
import io.prometheus.client.exporter.common.TextFormat
import io.prometheus.client.hotspot.DefaultExports


  def exportReply: HttpResponse = {
    val writer = new StringWriter
    TextFormat.write004(writer, registry.metricFamilySamples())
    val string = writer.toString

    HttpResponse(entity = HttpEntity.Strict(HttpExport.contentType, ByteString(string)))
  }
}

object HttpExport {
  val contentType: ContentType = ContentType.parse(TextFormat.CONTENT_TYPE_004).right.get
} 
开发者ID:Norwae,项目名称:ignifera,代码行数:24,代码来源:HttpExport.scala


示例2: PaloParser

//设置package包名称以及导入依赖的类
package com.wix.sms.cellact.model

import java.io.{StringReader, StringWriter}
import javax.xml.bind.{JAXBContext, Marshaller}

class PaloParser {
  val context = JAXBContext.newInstance(classOf[Palo])
  val marshaller = context.createMarshaller()
  marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true)

  val unmarshaller = context.createUnmarshaller()

  def stringify(obj: Palo): String = {
    val writer = new StringWriter()
    try {
      marshaller.marshal(obj, writer)
    } finally {
      writer.close()
    }
    writer.toString
  }

  def parse(xml: String): Palo = {
    val reader = new StringReader(xml)
    try {
      unmarshaller.unmarshal(reader).asInstanceOf[Palo]
    } finally {
      reader.close()
    }
  }
} 
开发者ID:wix,项目名称:libsms-cellact,代码行数:32,代码来源:PaloParser.scala


示例3: ResponseParser

//设置package包名称以及导入依赖的类
package com.wix.sms.cellact.model

import java.io.{StringReader, StringWriter}
import javax.xml.bind.{JAXBContext, Marshaller}

class ResponseParser {
  val context = JAXBContext.newInstance(classOf[Response])
  val marshaller = context.createMarshaller()
  marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);

  val unmarshaller = context.createUnmarshaller()

  def stringify(obj: Response): String = {
    val writer = new StringWriter()
    try {
      marshaller.marshal(obj, writer)
    } finally {
      writer.close()
    }
    writer.toString
  }

  def parse(xml: String): Response = {
    val reader = new StringReader(xml)
    try {
      unmarshaller.unmarshal(reader).asInstanceOf[Response]
    } finally {
      reader.close()
    }
  }
} 
开发者ID:wix,项目名称:libsms-cellact,代码行数:32,代码来源:ResponseParser.scala


示例4: JsonUtil

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

import java.io.StringWriter

import com.fasterxml.jackson.databind.{DeserializationFeature, ObjectMapper}
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper

import scala.reflect.{ClassTag, Manifest}

object JsonUtil {

  val mapper = new ObjectMapper() with ScalaObjectMapper
  mapper.registerModule(DefaultScalaModule)
  mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)

  def toJson[T](data: T): String = {
    val out = new StringWriter()
    mapper.writeValue(out, data)
    out.toString
  }

  def fromJson[T: ClassTag](json: String)(implicit m: Manifest[T]): T =
    mapper.readValue[T](json)
} 
开发者ID:SarathChandran,项目名称:InventoryTracker,代码行数:26,代码来源:JsonUtil.scala


示例5: getStackTrace

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

import java.io.{PrintWriter, StringWriter}
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.util.UUID

import spray.json.{JsValue, JsonFormat, _}

trait UsersProtocol {
  private def getStackTrace(t: Throwable) = {
    val sw: StringWriter = new StringWriter()
    val pw: PrintWriter = new PrintWriter(sw)
    t.printStackTrace(pw)
    sw.toString
  }

  implicit object ThrowableWriter extends RootJsonWriter[Throwable] {
    def write(t: Throwable) = JsObject(
      "message" -> JsString(t.getMessage),
      "cause" -> t.getCause.toJson,
      "stackTrace" -> JsString(getStackTrace(t))
    )
  }

  implicit object MessageFormat extends RootJsonWriter[Message] {
    def write(m: Message) = JsObject(
      "summary" -> JsString(m.summary),
      "errorCode" -> JsNumber(m.errorCode)
    )
  }

  implicit object ValidationFormat extends RootJsonWriter[Validation] {
    def write(v: Validation) = {
      val fields = Seq[Option[JsField]](
        Some("message"   -> JsString(v.message)),
        Some("errorCode" -> JsNumber(v.errorCode)),
        v.exception.map(exception => "exception" -> exception.toJson)
      )
      JsObject(fields.flatten: _*)
    }
  }

  implicit object UUIDFormat extends JsonFormat[UUID] {
    def write(uuid: UUID) = JsString(uuid.toString)
    def read(value: JsValue) = value match {
      case JsString(uuid) => UUID.fromString(uuid)
      case _ => deserializationError("UUID expected.")
    }
  }

  implicit object LocalDateTimeFormat extends JsonFormat[LocalDateTime] {
    def write(dateTime: LocalDateTime) = JsString(dateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME))
    def read(value: JsValue) = value match {
      case JsString(dateTime) => LocalDateTime.parse(dateTime, DateTimeFormatter.ISO_LOCAL_DATE_TIME)
      case _ => deserializationError("LocalDateTime expected.")
    }
  }
} 
开发者ID:Morgan-Stanley,项目名称:proton,代码行数:60,代码来源:UsersProtocol.scala


示例6:

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

import com.vividsolutions.jts.geom.{ Coordinate, Geometry }
import java.io.StringWriter
import org.geotools.geojson.geom.GeometryJSON
import play.api.libs.json._

trait HasGeometry {

  private val DECIMAL_PRECISION = 12
  
  implicit val geometryFormat: Format[Geometry] =
    Format(
      JsPath.read[JsValue].map { json =>
        new GeometryJSON(DECIMAL_PRECISION).read(Json.stringify(json))
      },
      
      Writes[Geometry] { geom =>
        val writer = new StringWriter()
        new GeometryJSON(DECIMAL_PRECISION).write(geom, writer)
        Json.parse(writer.toString)
      }
    )
  
  implicit val coordinateFormat: Format[Coordinate] =
    Format(
      JsPath.read[JsArray].map { json =>
        val lon = json.value(0).as[Double]
        val lat = json.value(1).as[Double]
        new Coordinate(lon, lat)
      },
      
      Writes[Coordinate] { c =>
        Json.toJson(Seq(c.x, c.y))
      }
    )

} 
开发者ID:pelagios,项目名称:recogito2,代码行数:39,代码来源:HasGeometry.scala


示例7: Csv

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

  import java.io.{StringWriter, Writer}

  import com.github.tototoshi.csv.CSVWriter
  import org.intracer.wmua.{ImageWithRating, Round, User}

  object Csv {

    def writeStringBuffer(data: Seq[Seq[Any]]): StringBuffer = {
      val writer = new StringWriter()
      write(data, writer)
      writer.getBuffer
    }

    def writeRow(data: Seq[Any]): String = {
      val writer = new StringWriter()
      val csv = CSVWriter.open(writer)
      csv.writeRow(data)
      csv.close()
      writer.getBuffer.toString
    }

    def write(data: Seq[Seq[Any]], writer: Writer): Unit = {
      val csv = CSVWriter.open(writer)
      csv.writeAll(data)
      csv.close()
    }

    def exportRates(files: Seq[ImageWithRating], jurors: Seq[User], round: Round): Seq[Seq[String]] = {
      val header = Seq("Rank", "File", "Overall") ++ jurors.map(_.fullname)

      val ranks = ImageWithRating.rankImages(files, round)
      val rows = for ((file, rank) <- files.zip(ranks))
        yield Seq(rank, file.image.title, file.rateString(round)) ++ jurors.map(file.jurorRateStr)

      header +: rows
    }

    def addBom(data: Seq[Seq[String]]): Seq[Seq[String]] = {
      val BOM = "\ufeff"
      val header = data.head
      val headerWithBom = (BOM + header.head) +: header.tail
      headerWithBom +: data.tail
    }
  } 
开发者ID:intracer,项目名称:wlxjury,代码行数:47,代码来源:Csv.scala


示例8: DirectoryViewer

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

import com.github.mustachejava.DefaultMustacheFactory
import java.io.{StringWriter, File}
import com.twitter.util.Try

object DirectoryViewer {

  // these are passed to the mustache view
  case class ListingView(root: FileView, files: Array[FileView], directories: Array[FileView])

  case class FileView(relativeName: String, shortName: String)

  def getListing(directory: File): Try[String] = {
    // there's a lot of io and untyped computation in this function. It's best to
    // err on the side of safety and wrap everything in a Try comprehension
    val mustacheFactory = new DefaultMustacheFactory
    val output = new StringWriter
    for {
      reader <- Try(mustacheFactory.getReader("directory_browser.mustache"))
      mustache <- Try(mustacheFactory.compile(reader, "directory_browser"))
      scope <- Try(renderView(directory))
      () <- Try(mustache.execute(output, scope).flush())
    } yield output.toString
  }

  val absoluteAssetPath = new File(config.docRoot() + config.assetPath()).getAbsolutePath

  private def fileToView(f: File): FileView = {
    val relativeName = f.getAbsolutePath.replace(absoluteAssetPath, "")
    val name = f.getName
    FileView(relativeName, name)
  }

  def renderView(directory: File): ListingView = {
    val directories = directory.listFiles.filter(x => x != null && x.isDirectory).map(fileToView)
    val files = directory.listFiles.filter(x => x != null && x.isFile).map(fileToView)
    ListingView(fileToView(directory), files, directories)
  }
} 
开发者ID:pairi,项目名称:pairi,代码行数:41,代码来源:DirectoryViewer.scala


示例9: SystemResource

//设置package包名称以及导入依赖的类
package mesosphere.marathon.api

import java.io.StringWriter
import java.util.concurrent.TimeUnit
import javax.servlet.http.HttpServletRequest
import javax.ws.rs._
import javax.ws.rs.core.{ Context, MediaType, Response }

import com.codahale.metrics.{ MetricFilter, MetricRegistry }
import com.codahale.metrics.annotation.Timed
import com.codahale.metrics.json.MetricsModule
import com.fasterxml.jackson.databind.ObjectMapper
import com.google.inject.Inject
import mesosphere.marathon.MarathonConf
import mesosphere.marathon.io.IO
import mesosphere.marathon.plugin.auth.AuthorizedResource.SystemConfig
import mesosphere.marathon.plugin.auth.{ Authenticator, Authorizer, ViewResource }


@Path("")
@Consumes(Array(MediaType.APPLICATION_JSON))
@Produces(Array(MarathonMediaType.PREFERRED_APPLICATION_JSON))
class SystemResource @Inject() (metrics: MetricRegistry, val config: MarathonConf)(implicit
  val authenticator: Authenticator,
    val authorizer: Authorizer) extends RestResource with AuthResource {

  private[this] lazy val mapper = new ObjectMapper().registerModule(
    new MetricsModule(TimeUnit.SECONDS, TimeUnit.SECONDS, false, MetricFilter.ALL)
  )

  @GET
  @Path("ping")
  @Timed
  def ping(@Context req: HttpServletRequest): Response = authenticated(req) { implicit identity =>
    withAuthorization(ViewResource, SystemConfig){
      ok("pong")
    }
  }

  @GET
  @Path("metrics")
  @Timed
  def metrics(@Context req: HttpServletRequest): Response = authenticated(req) { implicit identity =>
    withAuthorization(ViewResource, SystemConfig){
      IO.using(new StringWriter()) { writer =>
        mapper.writer().writeValue(writer, metrics)
        ok(writer.toString)
      }
    }
  }
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:52,代码来源:SystemResource.scala


示例10: ThrowableOps

//设置package包名称以及导入依赖的类
package com.github.stonexx.scala.util

import java.io.{PrintWriter, StringWriter}

final class ThrowableOps(val self: Throwable) extends AnyVal {

  def stackTraceString: String = {
    val stackTrace = new StringWriter
    self.printStackTrace(new PrintWriter(stackTrace))
    stackTrace.toString
  }
}

trait ToThrowableOps {
  implicit def toThrowableOps(x: Throwable): ThrowableOps = new ThrowableOps(x)
} 
开发者ID:stonexx,项目名称:utils,代码行数:17,代码来源:ThrowableOps.scala


示例11: RSAKeyPairFactory

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

import java.io.StringWriter
import java.security.{KeyPair, KeyPairGenerator}

import org.bouncycastle.openssl.jcajce.JcaMiscPEMGenerator
import org.bouncycastle.util.io.pem.PemWriter


object RSAKeyPairFactory {

  def generate: KeyPair = {
    val generator = KeyPairGenerator.getInstance("RSA")
    generator.initialize(2048)
    generator.genKeyPair()
  }

  def privateKeyToString(keyPair: KeyPair) = {
    val writer = new StringWriter
    try {
      val pemWriter = new PemWriter(writer)
      try {
        val pemObject = new JcaMiscPEMGenerator(keyPair.getPrivate)
        pemWriter.writeObject(pemObject)
      }
      finally {
        pemWriter.close
      }
      writer.toString
    }
    finally {
      writer.close
    }
  }

  def publicKeyToString(keyPair: KeyPair) = {
    val writer = new StringWriter
    try {
      val pemWriter = new PemWriter(writer)
      try {
        val pemObject = new JcaMiscPEMGenerator(keyPair.getPublic)
        pemWriter.writeObject(pemObject)
      }
      finally {
        pemWriter.close
      }
      writer.toString
    }
    finally {
      writer.close
    }
  }
} 
开发者ID:takesection,项目名称:apple-mdm-certificate,代码行数:54,代码来源:RSAKeyPairFactory.scala


示例12: CertificationSigningRequestFactory

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

import java.io.StringWriter
import java.security.KeyPair

import org.bouncycastle.asn1.oiw.OIWObjectIdentifiers
import org.bouncycastle.asn1.x500.X500Name
import org.bouncycastle.asn1.x509.AlgorithmIdentifier
import org.bouncycastle.crypto.util.{PrivateKeyFactory, PublicKeyFactory, SubjectPublicKeyInfoFactory}
import org.bouncycastle.openssl.jcajce.JcaMiscPEMGenerator
import org.bouncycastle.operator.bc.BcRSAContentSignerBuilder
import org.bouncycastle.pkcs.{PKCS10CertificationRequest, PKCS10CertificationRequestBuilder}
import org.bouncycastle.util.io.pem.PemWriter

object CertificationSigningRequestFactory {

  def generate(subject: X500Name, keyPair: KeyPair): PKCS10CertificationRequest = {
    val publicKeyParam = PublicKeyFactory.createKey(keyPair.getPublic.getEncoded)
    val subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(publicKeyParam)

    val builder = new PKCS10CertificationRequestBuilder(subject, subjectPublicKeyInfo)

    val sigAlgId = new AlgorithmIdentifier(OIWObjectIdentifiers.sha1WithRSA)
    val digAlgId = new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1)

    val privateKeyParam = PrivateKeyFactory.createKey(keyPair.getPrivate.getEncoded)

    val contentSigner = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyParam)
    builder.build(contentSigner)
  }

  def csrToString(csr: PKCS10CertificationRequest) = {
    val writer = new StringWriter
    try {
      val pemWriter = new PemWriter(writer)
      try {
        val pemObject = new JcaMiscPEMGenerator(csr)
        pemWriter.writeObject(pemObject)
      }
      finally {
        pemWriter.close
      }
      writer.toString
    }
    finally {
      writer.close
    }
  }

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


示例13: SparkLogger

//设置package包名称以及导入依赖的类
package comp.bio.aging.playground

import org.apache.spark.SparkContext
import org.apache.spark.rdd.RDD
import org.bdgenomics.formats.avro.Feature
import org.bdgenomics.utils.instrumentation.{Metrics, MetricsListener, RecordedMetrics}

class SparkLogger(sparkContext: SparkContext) {

  import scala.reflect.ClassTag

  def log[T: ClassTag](rdd: RDD[T]): RDD[T] = {
    org.apache.spark.rdd.MetricsContext.rddToInstrumentedRDD[T](rdd).instrument
  }

  lazy val metricsListener = new MetricsListener(new RecordedMetrics())

  def init(): SparkLogger = {
    //note is called by default
    Metrics.initialize(sparkContext)
    sparkContext.addSparkListener(metricsListener)
    this
  }

  def lines: List[String] = {
    val stages = metricsListener.metrics.sparkMetrics.stageTimes.toList
    for (stage <- stages)
      yield s"${stage.stageName.getOrElse("")} ${stage.duration} id = ${stage.stageId}"
  }

  def stop = {
    Metrics.stopRecording()
    this
  }

  def prettyPrint() = {
    import java.io.{PrintWriter, StringWriter}
    val stringWriter = new StringWriter()
    val writer = new PrintWriter(stringWriter)
    val result = stringWriter.toString
    writer.close()
    result
  }

  init()
} 
开发者ID:antonkulaga,项目名称:adam-playground,代码行数:47,代码来源:SparkLogger.scala


示例14: FindingTest

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

import java.io.StringWriter

import org.scalatest._

class FindingTest extends FlatSpec with Matchers {

  "Finding" should "output the correct finding position" in {
    val out = new StringWriter()
    Finding.printAll(List(
      new Finding { val pos = Position(3, 3); val severity = Severity.WARNING; val msg = "A" },
      new Finding { val pos = Position(1, 2); val severity = Severity.ERROR; val msg = "B" }
    ), List("line1\n", "line2\r", "line3\r\n"), out)

    out.toString shouldBe
      """1:2 ERROR: B
        |line1
        | ^
        |3:3 WARNING: A
        |line3
        |  ^
        |""".stripMargin
  }

  it should "output findings without input source" in {
    val out = new StringWriter()
    Finding.printAll(List(
      new Finding { val pos = Position(3, 3); val severity = Severity.WARNING; val msg = "A" },
      new Finding { val pos = Position(1, 2); val severity = Severity.ERROR; val msg = "B" }
    ), Iterable.empty, out)

    out.toString shouldBe
      """1:2 ERROR: B
        |3:3 WARNING: A
        |""".stripMargin
  }
} 
开发者ID:jspam,项目名称:mjis,代码行数:39,代码来源:FindingTest.scala


示例15: EventGeneratingClient

//设置package包名称以及导入依赖的类
package org.argus.jc.incremental.jawa
package remote

import java.io.{File, PrintWriter, StringWriter}

import org.argus.jawa.core.io.SourceFile
import org.jetbrains.jps.incremental.messages.BuildMessage.Kind


class EventGeneratingClient(listener: Event => Unit, canceled: => Boolean) extends Client {
  def message(kind: Kind, text: String, source: SourceFile, line: Option[Long], column: Option[Long]) {
    listener(MessageEvent(kind, text, source, line, column))
  }

  def trace(exception: Throwable) {
    val lines = {
      val writer = new StringWriter()
      exception.printStackTrace(new PrintWriter(writer))
      writer.toString.split("\\n")
    }
    listener(TraceEvent(exception.getMessage, lines))
  }

  def progress(text: String, done: Option[Float]) {
    listener(ProgressEvent(text, done))
  }

  def debug(text: String) {
    listener(DebugEvent(text))
  }

  def generated(source: SourceFile, module: File, name: String) {
    listener(GeneratedEvent(source, module, name))
  }

  def deleted(module: File) {
    listener(DeletedEvent(module))
  }

  def isCanceled = canceled

  def processed(source: SourceFile) {
    listener(SourceProcessedEvent(source))
  }

  override def compilationEnd() {
    listener(CompilationEndEvent())
  }
} 
开发者ID:arguslab,项目名称:argus-cit-intellij,代码行数:50,代码来源:EventGeneratingClient.scala


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


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


示例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=------------------------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


示例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=------------------------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


示例20: VelocityFabric

//设置package包名称以及导入依赖的类
package com.flipkart.connekt.commons.entities.fabric

import java.io.StringWriter

import com.fasterxml.jackson.databind.node.ObjectNode
import com.flipkart.connekt.commons.factories.{ConnektLogger, LogFile}
import com.flipkart.connekt.commons.utils.VelocityUtils
import org.apache.velocity.app.Velocity
import org.apache.velocity.context.Context

import scala.util.{Failure, Success, Try}

class VelocityFabric(dataVtl: String) extends EngineFabric {
  
  def fabricate(id: String, context: Context, vtlFabric: String, errorTag: String): Try[String] = {
    try {
      val w = new StringWriter()
      Velocity.evaluate(context, w, errorTag, vtlFabric)
      Success(w.toString)
    } catch {
      case e: Exception =>
        ConnektLogger(LogFile.PROCESSORS).error(s"Velocity fabricate failed for [$id}], ${e.getMessage}", e)
        Failure(new Throwable(s"Velocity fabricate failed for [$id}] error: ${e.getMessage}"))
    }
  }

  def fabricate(id: String, context: ObjectNode, vtlFabric: String, errorTag: String): Try[String] = {
    fabricate(id, VelocityUtils.convertToVelocityContext(context), vtlFabric, errorTag)
  }

  def validateVtl(): Try[Boolean] = Try.apply(true)

  def compute(id: String, context: ObjectNode): AnyRef = {
    fabricate(id, context, dataVtl, s"_$id _").get
  }
} 
开发者ID:ayush03agarwal,项目名称:connekt,代码行数:37,代码来源:VelocityFabric.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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