本文整理汇总了Scala中java.io.StringReader类的典型用法代码示例。如果您正苦于以下问题:Scala StringReader类的具体用法?Scala StringReader怎么用?Scala StringReader使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了StringReader类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。
示例1: 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
示例2: 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
示例3: SummaryParser
//设置package包名称以及导入依赖的类
package org.argus.jawa.summary.parser
import java.io.StringReader
import org.antlr.v4.runtime.misc.ParseCancellationException
import org.antlr.v4.runtime.{BailErrorStrategy, CharStreams, CommonTokenStream, NoViableAltException}
import org.argus.jawa.summary.rule.SummaryFile
import org.argus.jawa.summary.grammar.{SafsuLexer, SafsuParser}
object SummaryParser {
def apply(source: String): SummaryFile =
parse(source)
@throws[SummaryParserException]
def parse(source: String): SummaryFile = {
val reader = new StringReader(source)
val input = CharStreams.fromReader(reader)
val lexer = new SafsuLexer(input)
val cts = new CommonTokenStream(lexer)
val parser = new SafsuParser(cts)
parser.setErrorHandler(new BailErrorStrategy)
try {
SummaryParserVisitor(parser.summaryFile())
} catch {
case oie: IndexOutOfBoundsException =>
throw SummaryParserException(oie)
case nvae: NoViableAltException =>
throw SummaryParserException(nvae)
case pce: ParseCancellationException =>
throw SummaryParserException(pce.getCause)
}
}
}
case class SummaryParserException(cause: Throwable) extends Exception(cause.getMessage)
开发者ID:arguslab,项目名称:Argus-SAF,代码行数:37,代码来源:SummaryParser.scala
示例4: BackupMetadataTest
//设置package包名称以及导入依赖的类
package com.unity.analytics.spark.utils.parquet
import java.io.{File, StringReader}
import java.sql.DriverManager
import org.apache.commons.io.FileUtils
import org.h2.tools.{RunScript, Server}
class BackupMetadataTest extends BaseTest {
val dbDriver = "org.h2.Driver"
val server = Server.createTcpServer("-tcpPort", "9999")
val jdbcDB = "dummydb"
val jdbcUrl = s"jdbc:h2:mem:$jdbcDB;DATABASE_TO_UPPER=FALSE;MODE=MYSQL"
val jdbcConfig = Map(
"url" -> jdbcUrl
)
val backendConnection = DriverManager.getConnection(jdbcUrl)
val backupId = "dummyBackupId"
override def beforeAll(): Unit = {
super.beforeAll()
println("INITIALIZE H2")
// Initialize H2
val reader = new StringReader(FileUtils.readFileToString(new File("src/test/scala/resources/backup_metadata.sql")).replace('`', '"'))
RunScript.execute(backendConnection, reader)
}
test("Test reading and writing backup metadata") {
val entries = Array(
BackupEntry("hdfs://hello", "s3a://hello", 100, 10),
BackupEntry("/source", "/destination", 200, 2)
).sortBy(_.destDir)
BackupMetadata.write(backupId, entries, jdbcConfig)
val metadata = BackupMetadata.read(backupId, jdbcConfig).get
assert(metadata.backupId === backupId)
assert(metadata.backupEntries.length === entries.length)
val output = metadata.backupEntries.sortBy(_.destDir)
entries.zip(output).foreach(e => {
assert(e._1 === e._2)
})
}
}
开发者ID:UnityTech,项目名称:parquet-s3-backup,代码行数:45,代码来源:BackupMetadataTest.scala
示例5: Pkcs12ConvertorSpec
//设置package包名称以及导入依赖的类
package jp.pigumer
import java.io.{FileOutputStream, StringReader}
import java.math.BigInteger
import java.time.{Duration, Instant}
import java.util.Date
import org.bouncycastle.asn1.oiw.OIWObjectIdentifiers
import org.bouncycastle.asn1.x500.X500NameBuilder
import org.bouncycastle.asn1.x500.style.BCStyle
import org.bouncycastle.asn1.x509.AlgorithmIdentifier
import org.bouncycastle.cert.X509v3CertificateBuilder
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter
import org.bouncycastle.crypto.util.PrivateKeyFactory
import org.bouncycastle.operator.bc.BcRSAContentSignerBuilder
import org.specs2.mutable.Specification
class Pkcs12ConvertorSpec extends Specification {
"Pkcs12Convertor" should {
"parsePrivateKey" in {
val keyPair = RSAKeyPairFactory.generate
val pem = RSAKeyPairFactory.privateKeyToString(keyPair)
val reader = new StringReader(pem)
val pk = Pkcs12Convertor.parsePrivateKey(reader)
keyPair.getPrivate.getEncoded must_== pk.getEncoded
}
"parseCertificate" in {
val keyPair = RSAKeyPairFactory.generate
val builder = new X500NameBuilder()
builder.addRDN(BCStyle.C, "JP")
builder.addRDN(BCStyle.CN, "Pigumer Group")
val csr = CertificationSigningRequestFactory.generate(builder.build(), keyPair)
val now = Instant.now()
val notBefore = new Date(now.toEpochMilli)
val notAfter = new Date(now.plus(Duration.ofDays(365)).toEpochMilli)
val b = new X509v3CertificateBuilder(csr.getSubject, BigInteger.valueOf(1L), notBefore, notAfter, csr.getSubject, csr.getSubjectPublicKeyInfo)
val sigAlgId = new AlgorithmIdentifier(OIWObjectIdentifiers.sha1WithRSA)
val digAlgId = new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1)
val privateKeyInfo = PrivateKeyFactory.createKey(keyPair.getPrivate.getEncoded)
val contentSigner = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyInfo)
val certificate = new JcaX509CertificateConverter().getCertificate(b.build(contentSigner))
val os = new FileOutputStream("test.p12")
try {
Pkcs12Convertor.write(os, keyPair.getPrivate, "test".toCharArray, certificate)
} finally {
os.close
}
success
}
}
}
开发者ID:takesection,项目名称:apple-mdm-certificate,代码行数:62,代码来源:Pkcs12ConvertorSpec.scala
示例6: CompilerTestHelper
//设置package包名称以及导入依赖的类
package mjis
import java.io.StringReader
import System.{ lineSeparator => n }
import mjis.ast._
import org.scalatest._
import scala.reflect._
import scala.collection.JavaConversions._
object CompilerTestHelper {
def fromMembers(member: String, mainMethod: Boolean = true): String = s"class Test {$n$member$n" +
(if (mainMethod) s"public static void main(String[] args){}}" else "}")
def fromStatements(statements: String, mainMethod: Boolean = true): String =
fromMembers(s"public void test() {$n$statements$n}", mainMethod)
def assertExec[P <: Phase[_]: ClassTag](input: String): P = Compiler.exec(new StringReader(input)) match {
case Left(phase) => phase
case Right(findings) => Assertions.fail(s"Compilation up to ${classTag[P].runtimeClass.getName} failed. Findings:$n${findings.mkString(n)}")
}
def assertExecClass[P <: Phase[Program]: ClassTag](cls: String): ClassDecl = assertExec[P](cls).result.classes(0)
def assertExecMethod[P <: Phase[Program]: ClassTag](method: String): MethodDecl = assertExecClass[P](fromMembers(method)).methods(0)
def assertExecStatements[P <: Phase[Program]: ClassTag](statements: String): List[Statement] = assertExecClass[P](fromStatements(statements)).methods(0).body.statements
def assertExecFailure[P <: Phase[_]: ClassTag](input: String): List[Finding] = Compiler.exec(new StringReader(input)) match {
case Left(phase) => Assertions.fail(s"Compilation up to ${classTag[P].runtimeClass.getName} succeeded, expected it to fail.")
case Right(findings) => findings
}
def getGraph(method: String, methodName: String = "test"): firm.Graph = {
assertExec[FirmConstructor](fromMembers(method))
val g = firm.Program.getGraphs.find(_.getEntity.getName == "_4Test_" + methodName)
assert(g.isDefined)
g.get
}
}
开发者ID:jspam,项目名称:mjis,代码行数:37,代码来源:CompilerTestHelper.scala
示例7: PageDownloader
//设置package包名称以及导入依赖的类
package com.nekopiano.scala.rest.client
import dispatch.classic.url
import dispatch.classic.Http
import java.io.StringReader
import nu.validator.htmlparser.common.XmlViolationPolicy
import nu.validator.htmlparser.sax.HtmlParser
import org.xml.sax.InputSource
import scalax.io.JavaConverters._
import scalax.io.Resource
import scala.xml.Node
import scala.xml.parsing.NoBindingFactoryAdapter
object PageDownloader {
def main(args: Array[String]): Unit = {
val h = new Http
val req = url("http://www.sample.jp/products/") >\ "UTF-8"
val html = h(req as_str)
val rootNode = toNode(html)
val links = rootNode \\ "@href" filter (_.text matches "/products/[a-z]+/[a-z0-9]+/")
val pages = links.map(a => {
"http://www.sample.jp" + a.text + "shiyo.htm"
}).sorted.distinct
println("pages.size=" + pages.size)
pages.foreach(url => {
println(url)
val data = Resource.fromURL(url).byteArray
println("downloading: %s ..." format url)
val r = "[a-z]+/[a-z0-9]+/shiyo.htm".r
val productName = r.findAllIn(url).matchData.mkString.dropRight(10).replace("/", "-")
Resource.fromFile(new java.io.File("samplepages\\" + productName + ".html")).write(data)
})
}
def toNode(str: String): Node = {
val hp = new HtmlParser
hp.setNamePolicy(XmlViolationPolicy.ALLOW)
val saxer = new NoBindingFactoryAdapter
hp.setContentHandler(saxer)
hp.parse(new InputSource(new StringReader(str)))
saxer.rootElem
}
}
开发者ID:lamusique,项目名称:ScalaSandbox,代码行数:54,代码来源:PageDownloader.scala
示例8: PageDownloader
//设置package包名称以及导入依赖的类
package com.nekopiano.scala.scalasandbox.download
import dispatch.classic.url
import dispatch.classic.Http
import java.io.StringReader
import nu.validator.htmlparser.common.XmlViolationPolicy
import nu.validator.htmlparser.sax.HtmlParser
import org.xml.sax.InputSource
import scalax.io.JavaConverters._
import scalax.io.Resource
import scala.xml.Node
import scala.xml.parsing.NoBindingFactoryAdapter
object PageDownloader {
def main(args: Array[String]): Unit = {
val h = new Http
val req = url("http://www.sample.jp/products/") >\ "UTF-8"
val html = h(req as_str)
val rootNode = toNode(html)
val links = rootNode \\ "@href" filter (_.text matches "/products/[a-z]+/[a-z0-9]+/")
val pages = links.map(a => {
"http://www.sample.jp" + a.text + "shiyo.htm"
}).sorted.distinct
println("pages.size=" + pages.size)
pages.foreach(url => {
println(url)
val data = Resource.fromURL(url).byteArray
println("downloading: %s ..." format url)
val r = "[a-z]+/[a-z0-9]+/shiyo.htm".r
val productName = r.findAllIn(url).matchData.mkString.dropRight(10).replace("/", "-")
Resource.fromFile(new java.io.File("samplepages\\" + productName + ".html")).write(data)
})
}
def toNode(str: String): Node = {
val hp = new HtmlParser
hp.setNamePolicy(XmlViolationPolicy.ALLOW)
val saxer = new NoBindingFactoryAdapter
hp.setContentHandler(saxer)
hp.parse(new InputSource(new StringReader(str)))
saxer.rootElem
}
}
开发者ID:lamusique,项目名称:ScalaSandbox,代码行数:54,代码来源:PageDownloader.scala
示例9: Neologd
//设置package包名称以及导入依赖的类
package com.kenjih
import java.io.StringReader
import org.codelibs.neologd.ipadic.lucene.analysis.ja.JapaneseTokenizer
import org.codelibs.neologd.ipadic.lucene.analysis.ja.tokenattributes.BaseFormAttribute
import org.codelibs.neologd.ipadic.lucene.analysis.ja.tokenattributes.PartOfSpeechAttribute
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute
object Neologd {
def main(args: Array[String]): Unit = {
val tokenizer = new JapaneseTokenizer(null, true, JapaneseTokenizer.DEFAULT_MODE)
val text = "?????????????????"
tokenizer.setReader(new StringReader(text))
val baseForm = tokenizer.addAttribute(classOf[BaseFormAttribute])
val partOfSpeech = tokenizer.addAttribute(classOf[PartOfSpeechAttribute])
val charTerm = tokenizer.addAttribute(classOf[CharTermAttribute])
tokenizer.reset()
while (tokenizer.incrementToken()) {
println(charTerm.toString + '\t' + baseForm.getBaseForm() + '\t' + partOfSpeech.getPartOfSpeech())
}
tokenizer.close()
}
}
开发者ID:Kenji-H,项目名称:scala-sample,代码行数:26,代码来源:Neologd.scala
示例10: CsvValidatorSpec
//设置package包名称以及导入依赖的类
package uk.gov.nationalarchives.csv.validator.api
import java.io.StringReader
import org.junit.runner.RunWith
import org.specs2.mutable.Specification
import org.specs2.runner.JUnitRunner
import scalaz._
import uk.gov.nationalarchives.csv.validator._
import uk.gov.nationalarchives.csv.validator.schema.Schema
import scalax.file.Path
import uk.gov.nationalarchives.csv.validator.api.CsvValidator.SubstitutePath
@RunWith(classOf[JUnitRunner])
class CsvValidatorSpec extends Specification with TestResources {
"Parsing schema" should {
val app = new CsvValidator with AllErrorsMetaDataValidator { val pathSubstitutions = List[SubstitutePath](); val enforceCaseSensitivePathChecks = false; val trace = false }
"report position on parse fail" in {
val schema =
"""version 1.0
|@totalColumns 1
|Name: regox("A")
""".stripMargin
app.parseAndValidate(new StringReader(schema)) must beLike {
case Failure(msgs) =>
msgs.list mustEqual IList(FailMessage(SchemaDefinitionError,
"[3.7] failure: Invalid column definition" + EOL
+ EOL
+ """Name: regox("A")""" + EOL
+ EOL
+ " ^"))
}
}
}
"Validation" should {
val app = new CsvValidator with AllErrorsMetaDataValidator { val pathSubstitutions = List[(String,String)](); val enforceCaseSensitivePathChecks = false; val trace = false }
def parse(filePath: String): Schema = app.parseSchema(TextFile(Path.fromString(filePath))) fold (f => throw new IllegalArgumentException(f.toString()), s => s)
"succeed for valid schema and metadata file" in {
app.validate(TextFile(Path.fromString(baseResourcePkgPath) / "metaData.csv"), parse(baseResourcePkgPath + "/schema.csvs"), None) must beLike {
case Success(_) => ok
}
}
"succeed for valid @totalColumns in schema and metadata file" in {
app.validate(TextFile(Path.fromString(baseResourcePkgPath) / "metaData.csv"), parse(baseResourcePkgPath + "/schema.csvs"), None) must beLike {
case Success(_) => ok
}
}
}
}
开发者ID:er-pritpal-singh,项目名称:CSV-Validator-Java,代码行数:57,代码来源:CsvValidatorSpec.scala
示例11: SchemaParserTotalColumnsSpec
//设置package包名称以及导入依赖的类
package uk.gov.nationalarchives.csv.validator.schema.v1_0
import java.io.StringReader
import org.junit.runner.RunWith
import org.specs2.runner.JUnitRunner
import uk.gov.nationalarchives.csv.validator.schema._
@RunWith(classOf[JUnitRunner])
class SchemaParserTotalColumnsSpec extends SchemaSpecBase {
import TestSchemaParser._
"Schema" should {
"fail for TotalColumns with missing value" in {
parse(new StringReader("version 1.0\[email protected]")) must beLike { case Failure(message, _) => message mustEqual "Invalid global directive" }
}
"fail for incorrect TotalColumns field name" in {
parse(new StringReader("version 1.0\[email protected] 23")) must beLike { case Failure(message, _) => message mustEqual "Invalid global directive" }
}
"fail for incorrect TotalColumns field name with no value" in {
parse(new StringReader("version 1.0\[email protected]")) must beLike { case Failure(message, _) => message mustEqual "Invalid global directive" }
}
"fail for TotalColumns field name incorrect case" in {
parse(new StringReader("version 1.0\[email protected] 65")) must beLike { case Failure(message, _) => message mustEqual "Invalid global directive" }
}
"fail for TotalColumns of zero" in {
parse(new StringReader("version 1.0\[email protected] 0")) must beLike { case Failure(message, _) => message mustEqual "Invalid global directive" }
}
"fail for TotalColumns with negative integer" in {
parse(new StringReader("version 1.0\[email protected] -23")) must beLike { case Failure(message, _) => message mustEqual "Invalid global directive" }
}
"fail for TotalColumns with non integer" in {
parse(new StringReader("version 1.0\[email protected] 132.45")) must beLike { case Failure(message, _) => message mustEqual "Invalid column definition" }
}
"fail for TotalColumns with non numeric" in {
parse(new StringReader("version 1.0\[email protected] blah")) must beLike { case Failure(message, _) => message mustEqual "Invalid global directive" }
}
}
}
开发者ID:er-pritpal-singh,项目名称:CSV-Validator-Java,代码行数:49,代码来源:SchemaParserTotalColumnsSpec.scala
示例12: SchemaParserSpec
//设置package包名称以及导入依赖的类
package uk.gov.nationalarchives.csv.validator.schema.v1_1
import java.io.StringReader
import org.junit.runner.RunWith
import org.specs2.runner.JUnitRunner
import uk.gov.nationalarchives.csv.validator.schema._
import uk.gov.nationalarchives.csv.validator.schema.v1_0.IsRule
@RunWith(classOf[JUnitRunner])
class SchemaParserSpec extends SchemaSpecBase {
import TestSchemaParser._
"Schema" should {
"succeed for valid minimal schema" in {
val columnDefinitions = List(new ColumnDefinition(NamedColumnIdentifier("column1")), new ColumnDefinition(NamedColumnIdentifier("column2"),List(IsRule(NoExt(ColumnReference(NamedColumnIdentifier("column1"))))),List()), new ColumnDefinition(NamedColumnIdentifier("column3")))
val schema =
"""version 1.1
|@totalColumns 3
|@noHeader
|column1:
|column2: is(noext($column1))
|column3:""".stripMargin
parse(new StringReader(schema)) must beLike { case Success(parsedSchema, _) => parsedSchema mustEqual buildSchema1_1(TotalColumns(3), NoHeader())(columnDefinitions:_*) }
}
"succeed for valid minimal schema" in {
val columnDefinitions = List(new ColumnDefinition(NamedColumnIdentifier("c1")), new ColumnDefinition(NamedColumnIdentifier("c2")),new ColumnDefinition(NamedColumnIdentifier("c3"),List(IsRule(Concat(ColumnReference(NamedColumnIdentifier("c1")), ColumnReference(NamedColumnIdentifier("c2"))))),List()))
val schema =
"""version 1.1
|@totalColumns 3
|c1:
|c2:
|c3: is(concat($c1,$c2))""".stripMargin
parse(new StringReader(schema)) must beLike { case Success(parsedSchema, _) => parsedSchema mustEqual buildSchema1_1(TotalColumns(3))(columnDefinitions:_*) }
}
}
}
开发者ID:er-pritpal-singh,项目名称:CSV-Validator-Java,代码行数:45,代码来源:SchemaParserSpec.scala
示例13: Tokenizer
//设置package包名称以及导入依赖的类
package io.gzet.story.util
import java.io.StringReader
import org.apache.lucene.analysis.en.EnglishAnalyzer
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute
object Tokenizer {
lazy private val replacePunc = """\\W""".r
lazy private val replaceDigitOnly = """\\s\\d+\\s""".r
def lucene(url: Traversable[String]): Traversable[Seq[String]] = {
val analyzer = new EnglishAnalyzer
url.map({ text =>
lucene(text, analyzer)
})
}
def lucene(line: String, analyzer: EnglishAnalyzer = new EnglishAnalyzer()): Seq[String] = {
val content1 = replacePunc.replaceAllIn(line, " ")
val content = replaceDigitOnly.replaceAllIn(content1, " ")
val tReader = new StringReader(content)
val tStream = analyzer.tokenStream("contents", tReader)
val term = tStream.addAttribute(classOf[CharTermAttribute])
tStream.reset()
val terms = collection.mutable.MutableList[String]()
while (tStream.incrementToken) {
if (!term.toString.matches(".*\\d.*") && term.toString.length > 3) {
terms += term.toString
}
}
tStream.close()
terms.toSeq
}
}
开发者ID:PacktPublishing,项目名称:Mastering-Spark-for-Data-Science,代码行数:37,代码来源:Tokenizer.scala
示例14: MessageReader
//设置package包名称以及导入依赖的类
package com.hypertino.hyperbus.serialization
import java.io.{Reader, StringReader}
import com.fasterxml.jackson.core.{JsonFactory, JsonParser}
import com.hypertino.binders.json.{JacksonParserAdapter, JsonBindersFactory}
import com.hypertino.binders.value.{Obj, Text, Value}
import com.hypertino.hyperbus.model.{Body, Header, Headers, HeadersMap, Message}
object MessageReader {
def read[M <: Message[_ <: Body,_ <: Headers]](reader: Reader, concreteDeserializer: MessageDeserializer[M]): M = {
val jacksonFactory = new JsonFactory()
jacksonFactory.disable(JsonParser.Feature.AUTO_CLOSE_SOURCE)
val jp = jacksonFactory.createParser(reader)
val headers = try {
val adapter = new JacksonParserAdapter(jp)
val headers = JsonBindersFactory.findFactory().withJsonParserApi(adapter) { jpa ?
val headersSeq = jpa.unbind[Value].asInstanceOf[Obj].v.toSeq // todo: this isn't great, also see https://github.com/hypertino/binders/issues/2
val transformedSeq = headersSeq.map {
case (Header.CONTENT_TYPE, value) ? Header.CONTENT_TYPE ? JsonContentTypeConverter.universalJsonContentTypeToSimple(value)
case other ? other
}
HeadersMap(transformedSeq: _*)
}
jp.nextToken()
val offset = jp.getTokenLocation.getCharOffset
reader.reset()
reader.skip(offset)
headers
}
finally {
jp.close()
}
concreteDeserializer(reader, headers)
}
def fromString[M <: Message[_ <: Body,_ <: Headers]](message: String, concreteDeserializer: MessageDeserializer[M]): M = {
val stringReader = new StringReader(message)
try {
read(stringReader, concreteDeserializer)
}
finally {
stringReader.close()
}
}
}
开发者ID:hypertino,项目名称:hyperbus,代码行数:52,代码来源:MessageReader.scala
示例15: DoiMetaSerializerTest
//设置package包名称以及导入依赖的类
package se.lu.nateko.cp.doi.core.test
import org.scalatest.FunSuite
import views.xml.doi.DoiMeta
import scala.xml.XML
import se.lu.nateko.cp.doi.core.DoiMetaParser
import javax.xml.validation.SchemaFactory
import javax.xml.XMLConstants
import java.net.URL
import javax.xml.transform.stream.StreamSource
import java.io.StringReader
class DoiMetaSerializerTest extends FunSuite{
test("Serializing/parsing round trip"){
val meta = DoiMetaExamples.full
assertResult(meta){
val serialized = views.xml.doi.DoiMeta(meta).body
val xml = XML.loadString(serialized)
DoiMetaParser.parse(xml).get
}
}
ignore("For manual run: validating the XML-serialized metadata against DataCite's XSD Schema"){
val sfactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
val schema = sfactory.newSchema(new URL("http://schema.datacite.org/meta/kernel-4.0/metadata.xsd"))
val validator = schema.newValidator()
val serialized = views.xml.doi.DoiMeta(DoiMetaExamples.full).body
val source = new StreamSource(new StringReader(serialized))
validator.validate(source)
}
}
开发者ID:ICOS-Carbon-Portal,项目名称:doi,代码行数:34,代码来源:DoiMetaSerializerTest.scala
示例16: Mustache
//设置package包名称以及导入依赖的类
package org.cddcore.rendering
import java.io.{StringReader, StringWriter}
import java.util
import com.github.mustachejava.{DefaultMustacheFactory, Mustache => JMustache}
object Mustache {
val mf = new DefaultMustacheFactory();
def apply(name: String, template: String) = new Mustache(mf.compile(new StringReader(template), name))
def apply(name: String) = new Mustache(mf.compile(name))
def forMustache(s: Any): Any = s match {
case m: Map[_, _] => m.foldLeft(new util.HashMap[String, Any]) {
case (acc, (k: String, v)) => acc.put(k, forMustache(v))
acc
}
case l: List[_] => l.foldLeft(new util.ArrayList[Any]) {
(acc, v) => acc.add(forMustache(v))
acc
}
case _ => s
}
}
class Mustache(mustache: JMustache) {
def apply(item: Any) = {
val writer = new StringWriter()
mustache.execute(writer, Mustache.forMustache(item))
writer.flush()
writer.toString
}
}
开发者ID:phil-rice,项目名称:CddCore2,代码行数:38,代码来源:Mustache.scala
示例17: MessagesParser
//设置package包名称以及导入依赖的类
package com.wix.sms.cm.model
import java.io.{StringReader, StringWriter}
import javax.xml.bind.{JAXBContext, Marshaller}
class MessagesParser {
val context = JAXBContext.newInstance(classOf[Messages])
val marshaller = context.createMarshaller()
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true)
val unmarshaller = context.createUnmarshaller()
def stringify(obj: Messages): String = {
val writer = new StringWriter()
try {
marshaller.marshal(obj, writer)
} finally {
writer.close()
}
writer.toString
}
def parse(xml: String): Messages = {
val reader = new StringReader(xml)
try {
unmarshaller.unmarshal(reader).asInstanceOf[Messages]
} finally {
reader.close()
}
}
}
开发者ID:wix,项目名称:libsms-cm,代码行数:32,代码来源:MessagesParser.scala
示例18: ArtifactSourceBackedMustacheResolver
//设置package包名称以及导入依赖的类
package com.atomist.project.common.template
import java.io.{Reader, StringReader}
import com.atomist.source.ArtifactSource
import com.github.mustachejava.resolver.DefaultResolver
import com.typesafe.scalalogging.LazyLogging
class ArtifactSourceBackedMustacheResolver(artifactSource: ArtifactSource)
extends DefaultResolver
with LazyLogging{
override def getReader(resourceName: String): Reader = {
logger.debug(s"Need to return Reader for $resourceName")
artifactSource.findFile(resourceName) match {
case Some(f) => new StringReader(f.content)
case _ => new StringReader(resourceName)
}
}
}
开发者ID:atomist,项目名称:rug,代码行数:21,代码来源:ArtifactSourceBackedMustacheResolver.scala
示例19: CuffDiff
//设置package包名称以及导入依赖的类
package org.denigma.genetics.expressions
import java.io.StringReader
import java.io.{File, StringReader}
import java.nio.file._
import scala.collection.JavaConverters._
import com.github.marklister.collections.immutable.CollSeq
import com.github.marklister.collections.io.{CSVReader, CsvParser}
import scala.io.Source
import com.github.marklister.collections.io.CsvParser
object CuffDiff {
case class DiffExpress(test_id: String,
gene_id: String,
gene: String,
locus: String,
sample_1: String,
sample_2: String,
status: String,
value_1: Double,
value_2: Double,
log2FoldChange: String,
test_stat: String,
p_value: Double,
q_value: Double,
significant: String
)
val parser = CsvParser(DiffExpress)
//protected def read(list: List[String]): StringReader = readStr( list.tail.reduce(_+_) )
protected def readStr(str: String): StringReader = new java.io.StringReader(str)
//def load(path: String, withHeaders: Boolean = true) = parser.parse(read(Source.fromFile(new File(path)).getLines().toList), "\t")
//def readLines(path: String) = Source.fromFile(new File(path)).getLines().toList.tail.reduce(_ + _)
def readFile(path: String) = parser.parse(readStr(Source.fromFile(path).getLines().toList.tail.mkString("\n")), "\t")
}
开发者ID:antonkulaga,项目名称:genetics,代码行数:42,代码来源:CuffDiff.scala
示例20: SequenceSupport
//设置package包名称以及导入依赖的类
package io.eels.component.sequence
import java.io.StringReader
import java.nio.charset.Charset
import com.sksamuel.exts.Logging
import com.sksamuel.exts.io.Using
import io.eels.component.csv.{CsvFormat, CsvSupport}
import io.eels.schema.{Field, StructType}
import org.apache.hadoop.conf.Configuration
import org.apache.hadoop.fs.Path
import org.apache.hadoop.io.{BytesWritable, IntWritable, SequenceFile}
object SequenceSupport extends Logging with Using {
def createReader(path: Path)(implicit conf: Configuration): SequenceFile.Reader =
new SequenceFile.Reader(conf, SequenceFile.Reader.file(path))
def toValues(v: BytesWritable): Array[String] = toValues(new String(v.copyBytes(), Charset.forName("UTF8")))
def toValues(str: String): Array[String] = {
val parser = CsvSupport.createParser(CsvFormat(), false, false, false, null, null)
parser.beginParsing(new StringReader(str))
val record = parser.parseNext()
parser.stopParsing()
record
}
def schema(path: Path)(implicit conf: Configuration): StructType = {
logger.debug(s"Fetching sequence schema for $path")
using(createReader(path)) { it =>
val k = new IntWritable()
val v = new BytesWritable()
val fields: Array[Field] = {
it.next(k, v)
toValues(v).map { it => new Field(it) }
}
StructType(fields.toList)
}
}
}
开发者ID:51zero,项目名称:eel-sdk,代码行数:42,代码来源:SequenceSupport.scala
注:本文中的java.io.StringReader类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论