本文整理汇总了Scala中com.trueaccord.scalapb.GeneratedMessageCompanion类的典型用法代码示例。如果您正苦于以下问题:Scala GeneratedMessageCompanion类的具体用法?Scala GeneratedMessageCompanion怎么用?Scala GeneratedMessageCompanion使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了GeneratedMessageCompanion类的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: set
//设置package包名称以及导入依赖的类
package walfie.gbf.raidfinder.server.persistence
import com.trueaccord.scalapb.{GeneratedMessage, GeneratedMessageCompanion, Message}
import java.net.URI
import redis.clients.jedis.{BinaryJedis, Jedis}
trait ProtobufStorage {
type CacheItem[T] = GeneratedMessage with Message[T]
def set[T <: CacheItem[T]](key: String, value: T): Unit
def get[T <: CacheItem[T]](
key: String
)(implicit companion: GeneratedMessageCompanion[T]): Option[T]
def close(): Unit
}
object ProtobufStorage {
def redis(uri: URI): RedisProtobufStorage = {
new RedisProtobufStorage(new BinaryJedis(uri))
}
}
// TODO: Write integration test
class RedisProtobufStorage(redis: BinaryJedis) extends ProtobufStorage {
def set[T <: CacheItem[T]](key: String, value: T): Unit = {
redis.set(key.getBytes, value.toByteArray)
}
def get[T <: CacheItem[T]](
key: String
)(implicit companion: GeneratedMessageCompanion[T]): Option[T] = {
Option(redis.get(key.getBytes)).flatMap { bytes =>
companion.validate(bytes).toOption
}
}
def close(): Unit = redis.close()
}
object NoOpProtobufStorage extends ProtobufStorage {
def set[T <: CacheItem[T]](key: String, value: T): Unit = ()
def get[T <: CacheItem[T]](
key: String
)(implicit companion: GeneratedMessageCompanion[T]): Option[T] = None
def close(): Unit = ()
}
示例2: parseFrom
//设置package包名称以及导入依赖的类
package net.cakesolutions.strictify.scalapb.ops
import scala.util.Try
import com.trueaccord.scalapb.{GeneratedMessage, GeneratedMessageCompanion, Message}
import net.cakesolutions.strictify.core.{Binding, StrictifyError}
trait StrictTypeDeserializer[S] {
def parseFrom(s: Array[Byte]): Either[StrictifyError, S]
}
object StrictTypeDeserializer {
implicit def instance[S, L <: GeneratedMessage with Message[L]](
implicit
binding: Binding.Aux[S, L],
companion: GeneratedMessageCompanion[L]
) = new StrictTypeDeserializer[S] {
override def parseFrom(s: Array[Byte]): Either[StrictifyError, S] =
Try(companion.parseFrom(s)).fold(e => Left(StrictifyError(e)), binding.strictify.apply)
}
}
trait StrictTypeSerializer[S] {
def toByteArray(value: S): Array[Byte]
}
object StrictTypeSerializer {
implicit def instance[S, L <: GeneratedMessage with Message[L]](
implicit
binding: Binding.Aux[S, L]
) = new StrictTypeSerializer[S] {
override def toByteArray(value: S): Array[Byte] =
binding.loosen(value).toByteArray
}
}
object SerializationOps {
def parseFrom[S: StrictTypeDeserializer](s: Array[Byte]): Either[StrictifyError, S] =
implicitly[StrictTypeDeserializer[S]].parseFrom(s)
def toByteArray[S: StrictTypeSerializer](value: S): Array[Byte] =
implicitly[StrictTypeSerializer[S]].toByteArray(value)
}
示例3: ZmqToAkkaFlow
//设置package包名称以及导入依赖的类
package tmt.demo.connectors
import akka.cluster.pubsub.DistributedPubSub
import akka.cluster.pubsub.DistributedPubSubMediator.Publish
import com.trueaccord.scalapb.GeneratedMessageCompanion
import tmt.app.utils.{ActorRuntime, PbMessage}
import tmt.demo.zeromq_drivers.ZmqSubscriberFactory
class ZmqToAkkaFlow(actorRuntime: ActorRuntime, zmqSubscriberFactory: ZmqSubscriberFactory) {
import actorRuntime._
def connect[Msg <: PbMessage.Of[Msg]](
publishingTopic: String,
subscriberPort: Int,
responseParser: GeneratedMessageCompanion[Msg]
) = {
val zmqSubscriber = zmqSubscriberFactory.make(subscriberPort, responseParser)
zmqSubscriber.stream
.runForeach { message =>
DistributedPubSub(system).mediator ! Publish(publishingTopic, message)
}.onComplete { x =>
zmqSubscriber.shutdown()
}
}
}
示例4: ZmqServer
//设置package包名称以及导入依赖的类
package tmt.demo.zeromq_drivers
import com.trueaccord.scalapb.{GeneratedMessage, GeneratedMessageCompanion}
import org.zeromq.ZMQ
import tmt.app.configs.AppSettings
import tmt.app.utils.{ActorRuntime, EC, PbMessage}
import scala.concurrent.ExecutionContext.global
import scala.concurrent.Future
import scala.util.control.NonFatal
class ZmqServer(settings: AppSettings, runtime: ActorRuntime) {
import runtime._
val address = s"tcp://*:${settings.mcsCommandsPort}"
private val socket = zmqContext.socket(ZMQ.REP)
socket.bind(address)
private val ec = EC.singleThreadedEc()
def start[Req <: PbMessage.Of[Req]](
reqParser: GeneratedMessageCompanion[Req]
)(f: Req => GeneratedMessage): Future[Unit] = Future {
while (true) {
try {
val message = socket.recv(0)
val request = reqParser.parseFrom(message)
println(s"***** ZmqSever received : [$request]")
Thread.sleep(100)
socket.send(f(request).toByteArray, 0)
} catch {
case NonFatal(ex) =>
ex.printStackTrace()
socket.send("error".getBytes, 0)
}
}
}(ec).map { x =>
println(s"ZmqServer completed with value: $x")
}(global)
def shutdown(): Unit = {
socket.close()
ec.shutdown()
}
}
示例5: ZmqSubscriber
//设置package包名称以及导入依赖的类
package tmt.demo.zeromq_drivers
import akka.stream.scaladsl.Source
import com.trueaccord.scalapb.GeneratedMessageCompanion
import org.zeromq.ZMQ
import tmt.app.configs.AppSettings
import tmt.app.utils.{PbMessage, EC, ActorRuntime}
import scala.concurrent.Future
class ZmqSubscriber[Msg <: PbMessage.Of[Msg]](
port: Int,
responseParser: GeneratedMessageCompanion[Msg],
settings: AppSettings,
runtime: ActorRuntime
) {
import runtime._
val address = s"tcp://${settings.mcsHostname}:$port"
private val socket = zmqContext.socket(ZMQ.SUB)
println(s"ZmqSubscriber connecting to $address")
socket.connect(address)
socket.subscribe(Array.empty)
private val ec = EC.singleThreadedEc()
val stream = {
Source
.repeat(())
.mapAsync(1)(_ => receive())
.map(bytes => responseParser.parseFrom(bytes))
.map(x => {println(s"********* ZmqSubscriber received $x"); x})
}
private def receive() = Future {
socket.recv(0)
}(ec)
def shutdown(): Unit = {
socket.close()
ec.shutdown()
}
}
class ZmqSubscriberFactory(settings: AppSettings, runtime: ActorRuntime) {
def make[Msg <: PbMessage.Of[Msg]](port: Int, responseParser: GeneratedMessageCompanion[Msg]) =
new ZmqSubscriber[Msg](port, responseParser, settings, runtime)
}
示例6: ZmqClient
//设置package包名称以及导入依赖的类
package tmt.demo.zeromq_drivers
import com.trueaccord.scalapb.{GeneratedMessage, GeneratedMessageCompanion}
import org.zeromq.ZMQ
import tmt.app.configs.AppSettings
import tmt.app.utils.{PbMessage, EC, ActorRuntime}
import scala.concurrent.Future
class ZmqClient(settings: AppSettings, runtime: ActorRuntime) {
import runtime._
val address = s"tcp://${settings.mcsHostname}:${settings.mcsCommandsPort}"
private val socket = zmqContext.socket(ZMQ.REQ)
println(s"ZmqClient is connecting to server $address")
socket.connect(address)
private val ec = EC.singleThreadedEc()
def query[Req <: GeneratedMessage, Res <: PbMessage.Of[Res]](
request: Req,
responseParser: GeneratedMessageCompanion[Res]
): Future[Res] = Future {
println(s"***** ZmqClient sending $request to $address at ${System.currentTimeMillis()}")
socket.send(request.toByteArray, 0)
responseParser.parseFrom(socket.recv(0))
}(ec)
def shutdown(): Unit = {
socket.close()
ec.shutdown()
}
}
示例7: ProtoUtils
//设置package包名称以及导入依赖的类
package org.karps.structures
import scala.util.{Failure, Success, Try}
import com.trueaccord.scalapb.{GeneratedMessage, Message, GeneratedMessageCompanion}
import com.trueaccord.scalapb.json._
object ProtoUtils {
def checkField[X](x: X, fieldName: String): Try[X] = {
if (x == null) {
missingField(fieldName)
} else {
Success(x)
}
}
def checkField[X](x: Option[X], fieldName: String): Try[X] = {
if (x == None) {
missingField(fieldName)
} else {
Success(x.get)
}
}
def missingField[X](fieldName: String): Try[X] = {
Failure(new Exception(s"Missing field $fieldName"))
}
def unrecognized[X](fieldName: String, x: Int): Try[X] = {
Failure(new Exception(s"unrecognized value for $fieldName: $x"))
}
def sequence[T](xs : Seq[Try[T]]) : Try[Seq[T]] = (Try(Seq[T]()) /: xs) {
(a, b) => a flatMap (c => b map (d => c :+ d))
}
def fromExtra[A <: GeneratedMessage with Message[A]](extra: OpExtra)(
implicit cmp: GeneratedMessageCompanion[A]): Try[A] = {
Try(JsonFormat.fromJsonString[A](extra.content))
}
def fromString[A <: GeneratedMessage with Message[A]](extra: String)(
implicit cmp: GeneratedMessageCompanion[A]): Try[A] = {
Try(JsonFormat.fromJsonString[A](extra))
}
def toJsonString[A <: GeneratedMessage](m: A): String = printer.print(m)
private val printer = new Printer(includingDefaultValueFields = false)
}
示例8: scalaPBFromRequestUnmarshaller
//设置package包名称以及导入依赖的类
package com.example.utilities.serialization
import akka.http.scaladsl.marshalling.{Marshaller, ToEntityMarshaller}
import akka.http.scaladsl.model.MediaType.Compressible
import akka.http.scaladsl.model.{ContentType, ContentTypes, HttpEntity, MediaType}
import akka.http.scaladsl.unmarshalling.Unmarshaller.UnsupportedContentTypeException
import akka.http.scaladsl.unmarshalling.{FromEntityUnmarshaller, Unmarshaller}
import akka.http.scaladsl.util.FastFuture
import com.google.protobuf.CodedInputStream
import com.trueaccord.scalapb.json.JsonFormat
import com.trueaccord.scalapb.{GeneratedMessage, GeneratedMessageCompanion, Message}
import scala.concurrent.Future
trait ScalaPBMarshalling {
private val protobufContentType = ContentType(MediaType.applicationBinary("octet-stream", Compressible, "proto"))
private val applicationJsonContentType = ContentTypes.`application/json`
def scalaPBFromRequestUnmarshaller[O <: GeneratedMessage with Message[O]](companion: GeneratedMessageCompanion[O]): FromEntityUnmarshaller[O] = {
Unmarshaller.withMaterializer[HttpEntity, O](_ => implicit mat => {
case [email protected](`applicationJsonContentType`, data) =>
val charBuffer = Unmarshaller.bestUnmarshallingCharsetFor(entity)
FastFuture.successful(JsonFormat.fromJsonString(data.decodeString(charBuffer.nioCharset().name()))(companion))
case [email protected](`protobufContentType`, data) =>
FastFuture.successful(companion.parseFrom(CodedInputStream.newInstance(data.asByteBuffer)))
case entity =>
Future.failed(UnsupportedContentTypeException(applicationJsonContentType, protobufContentType))
})
}
implicit def scalaPBToEntityMarshaller[U <: GeneratedMessage]: ToEntityMarshaller[U] = {
def jsonMarshaller(): ToEntityMarshaller[U] = {
val contentType = applicationJsonContentType
Marshaller.withFixedContentType(contentType) { value =>
HttpEntity(contentType, JsonFormat.toJsonString(value))
}
}
def protobufMarshaller(): ToEntityMarshaller[U] = {
Marshaller.withFixedContentType(protobufContentType) { value =>
HttpEntity(protobufContentType, value.toByteArray)
}
}
Marshaller.oneOf(jsonMarshaller(), protobufMarshaller())
}
}
示例9: ScalaPBReadSupport
//设置package包名称以及导入依赖的类
package com.trueaccord.scalapb.parquet
import java.util
import com.trueaccord.scalapb.{GeneratedMessage, GeneratedMessageCompanion, Message}
import org.apache.hadoop.conf.Configuration
import org.apache.parquet.hadoop.api.{InitContext, ReadSupport}
import org.apache.parquet.hadoop.api.ReadSupport.ReadContext
import org.apache.parquet.io.api.{GroupConverter, RecordMaterializer}
import org.apache.parquet.schema.MessageType
class ScalaPBReadSupport[T <: GeneratedMessage with Message[T]] extends ReadSupport[T] {
override def prepareForRead(
configuration: Configuration,
keyValueMetaData: util.Map[String, String],
fileSchema: MessageType,
readContext: ReadContext): RecordMaterializer[T] = {
val protoClass = Option(keyValueMetaData.get(ScalaPBReadSupport.PB_CLASS)).getOrElse(throw new RuntimeException(s"Value for ${ScalaPBReadSupport.PB_CLASS} not found."))
val cmp = {
import scala.reflect.runtime.universe
val runtimeMirror = universe.runtimeMirror(getClass.getClassLoader)
val module = runtimeMirror.staticModule(protoClass)
val obj = runtimeMirror.reflectModule(module)
obj.instance.asInstanceOf[GeneratedMessageCompanion[T]]
}
new RecordMaterializer[T] {
val root = new ProtoMessageConverter[T](cmp, fileSchema, onEnd = _ => ())
override def getRootConverter: GroupConverter = root
override def getCurrentRecord: T = root.getCurrentRecord
}
}
override def init(context: InitContext): ReadContext = {
new ReadContext(context.getFileSchema)
}
}
object ScalaPBReadSupport {
val PB_CLASS = "parquet.scalapb.class"
}