本文整理汇总了Scala中java.io.StringWriter类的典型用法代码示例。如果您正苦于以下问题:Scala StringWriter类的具体用法?Scala StringWriter怎么用?Scala StringWriter使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了StringWriter类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
}
示例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()
}
}
}
示例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()
}
}
}
示例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)
}
示例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.")
}
}
}
示例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))
}
)
}
示例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
}
}
示例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)
}
}
示例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)
}
}
}
}
示例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)
}
示例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
}
}
}
示例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
}
}
}
示例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()
}
示例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
}
}
示例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())
}
}