akka.serialization.SerializerWithStringManifest Scala Examples

The following examples show how to use akka.serialization.SerializerWithStringManifest. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: CrdtSerializers.scala    From cloudstate   with Apache License 2.0 5 votes vote down vote up
package io.cloudstate.proxy.crdt

import akka.actor.{AddressFromURIString, ExtendedActorSystem}
import akka.cluster.UniqueAddress
import akka.serialization.{BaseSerializer, SerializerWithStringManifest}
import com.google.protobuf.UnsafeByteOperations
import io.cloudstate.proxy.crdt.protobufs.{CrdtVote, CrdtVoteEntry}

class CrdtSerializers(override val system: ExtendedActorSystem)
    extends SerializerWithStringManifest
    with BaseSerializer {
  override def manifest(o: AnyRef): String = o match {
    case v: Vote => "V"
  }

  override def toBinary(o: AnyRef): Array[Byte] = o match {
    case v: Vote =>
      CrdtVote(v.state.toSeq.sortBy(_._1).map {
        case (address, value) =>
          CrdtVoteEntry(address.address.toString, address.longUid, UnsafeByteOperations.unsafeWrap(value.toByteArray))
      }).toByteArray
    case _ => throw new RuntimeException(s"Don't know how to serialize message of type [${o.getClass}]")
  }

  override def fromBinary(bytes: Array[Byte], manifest: String): AnyRef = manifest match {
    case "V" =>
      Vote(
        CrdtVote
          .parseFrom(bytes)
          .entries
          .map { entry =>
            (UniqueAddress(AddressFromURIString(entry.address), entry.uid), BigInt(entry.value.toByteArray))
          }
          .toMap,
        None
      )
    case _ => throw new RuntimeException(s"Don't know how to deserialize manifest [$manifest]")
  }
} 
Example 2
Source File: UserSerializer.scala    From whirlwind-tour-akka-typed   with Apache License 2.0 5 votes vote down vote up
package de.heikoseeberger.wtat

import akka.actor.ExtendedActorSystem
import akka.serialization.SerializerWithStringManifest
import de.heikoseeberger.wtat.proto.{ User => UserProto }
import java.io.NotSerializableException

final class UserSerializer(system: ExtendedActorSystem) extends SerializerWithStringManifest {

  override val identifier = 4242

  private final val UserManifest = "User"

  override def manifest(o: AnyRef) =
    o match {
      case _: User => UserManifest
      case _       => throw new IllegalArgumentException(s"Unknown class: ${o.getClass}!")
    }

  override def toBinary(o: AnyRef) =
    o match {
      case User(username, nickname) => UserProto(username.value, nickname.value).toByteArray
      case _                        => throw new IllegalArgumentException(s"Unknown class: ${o.getClass}!")
    }

  override def fromBinary(bytes: Array[Byte], manifest: String) = {
    def user(pb: UserProto) = User(pb.username, pb.nickname)
    manifest match {
      case UserManifest => user(UserProto.parseFrom(bytes))
      case _            => throw new NotSerializableException(s"Unknown manifest: $manifest!")
    }
  }
} 
Example 3
Source File: UserRepositorySerializer.scala    From whirlwind-tour-akka-typed   with Apache License 2.0 5 votes vote down vote up
package de.heikoseeberger.wtat

import akka.actor.ExtendedActorSystem
import akka.actor.typed.{ ActorRef, ActorRefResolver }
import akka.serialization.SerializerWithStringManifest
import de.heikoseeberger.wtat.proto.userrepository.{
  AddUser => AddUserProto,
  RemoveUser => RemoveUserProto,
  UserAdded => UserAddedProto,
  UserRemoved => UserRemovedProto,
  UsernameTaken => UsernameTakenProto,
  UsernameUnknown => UsernameUnknownProto
}
import de.heikoseeberger.wtat.proto.{ User => UserProto }
import java.io.NotSerializableException

final class UserRepositorySerializer(system: ExtendedActorSystem)
    extends SerializerWithStringManifest {
  import UserRepository._
  import akka.actor.typed.scaladsl.adapter._

  override val identifier = 4243

  private final val AddUserManifest         = "AddUser"
  private final val UsernameTakenManifest   = "UsernameTaken"
  private final val UserAddedManifest       = "UserAdded"
  private final val RemoveUserManifest      = "RemoveUser"
  private final val UsernameUnknownManifest = "UsernameUnknown"
  private final val UserRemovedManifest     = "UserRemoved"

  private val resolver = ActorRefResolver(system.toTyped)

  override def manifest(o: AnyRef) =
    o match {
      case serializable: Serializable =>
        serializable match {
          case _: AddUser         => AddUserManifest
          case _: UsernameTaken   => UsernameTakenManifest
          case _: UserAdded       => UserAddedManifest
          case _: RemoveUser      => RemoveUserManifest
          case _: UsernameUnknown => UsernameUnknownManifest
          case _: UserRemoved     => UserRemovedManifest
        }
      case _ => throw new IllegalArgumentException(s"Unknown class: ${o.getClass}!")
    }

  override def toBinary(o: AnyRef) = {
    def userProto(user: User)      = UserProto(user.username.value, user.nickname.value)
    def toBinary(ref: ActorRef[_]) = resolver.toSerializationFormat(ref)
    val proto =
      o match {
        case serializable: Serializable =>
          serializable match {
            case AddUser(user, replyTo)        => AddUserProto(Some(userProto(user)), toBinary(replyTo))
            case UsernameTaken(username)       => UsernameTakenProto(username)
            case UserAdded(user)               => UserAddedProto(Some(userProto(user)))
            case RemoveUser(username, replyTo) => RemoveUserProto(username, toBinary(replyTo))
            case UsernameUnknown(username)     => UsernameUnknownProto(username)
            case UserRemoved(username)         => UserRemovedProto(username)
          }
        case _ => throw new IllegalArgumentException(s"Unknown class: ${o.getClass}!")
      }
    proto.toByteArray
  }

  override def fromBinary(bytes: Array[Byte], manifest: String) = {
    def addUser(proto: AddUserProto)                 = AddUser(user(proto.user.get), fromBinary(proto.replyTo))
    def usernameTaken(proto: UsernameTakenProto)     = UsernameTaken(proto.username)
    def userAdded(proto: UserAddedProto)             = UserAdded(user(proto.user.get))
    def user(proto: UserProto)                       = User(proto.username, proto.nickname).valueOr(_.fail)
    def removeUser(proto: RemoveUserProto)           = RemoveUser(proto.username, fromBinary(proto.replyTo))
    def usernameUnknown(proto: UsernameUnknownProto) = UsernameUnknown(proto.username)
    def userRemoved(proto: UserRemovedProto)         = UserRemoved(proto.username)
    def fromBinary(ref: String)                      = resolver.resolveActorRef(ref)
    manifest match {
      case AddUserManifest         => addUser(AddUserProto.parseFrom(bytes))
      case UsernameTakenManifest   => usernameTaken(UsernameTakenProto.parseFrom(bytes))
      case UserAddedManifest       => userAdded(UserAddedProto.parseFrom(bytes))
      case RemoveUserManifest      => removeUser(RemoveUserProto.parseFrom(bytes))
      case UsernameUnknownManifest => usernameUnknown(UsernameUnknownProto.parseFrom(bytes))
      case UserRemovedManifest     => userRemoved(UserRemovedProto.parseFrom(bytes))
      case _                       => throw new NotSerializableException(s"Unknown manifest: $manifest!")
    }
  }
} 
Example 4
Source File: BankAccountEventJSONSerializer.scala    From akka-ddd-cqrs-es-example   with MIT License 5 votes vote down vote up
package com.github.j5ik2o.bank.adaptor.serialization

import akka.actor.ExtendedActorSystem
import akka.event.{ Logging, LoggingAdapter }
import akka.serialization.SerializerWithStringManifest
import com.github.j5ik2o.bank.domain.model._
import org.slf4j.LoggerFactory
import pureconfig._

object BankAccountEventJSONManifest {
  final val CREATE   = BankAccountOpened.getClass.getName.stripSuffix("$")
  final val UPDATE   = BankAccountEventUpdated.getClass.getName.stripSuffix("$")
  final val DEPOSIT  = BankAccountDeposited.getClass.getName.stripSuffix("$")
  final val WITHDRAW = BankAccountWithdrawn.getClass.getName.stripSuffix("$")
  final val DESTROY  = BankAccountClosed.getClass.getName.stripSuffix("$")
}

class BankAccountEventJSONSerializer(system: ExtendedActorSystem) extends SerializerWithStringManifest {
  import BankAccountCreatedJson._
  import BankAccountEventJSONManifest._
  import io.circe.generic.auto._

  private val logger = LoggerFactory.getLogger(getClass)

  private val config = loadConfigOrThrow[BankAccountEventJSONSerializerConfig](
    system.settings.config.getConfig("bank.interface.bank-account-event-json-serializer")
  )

  private implicit val log: LoggingAdapter = Logging.getLogger(system, getClass)

  private val isDebugEnabled = config.isDebuged

  override def identifier: Int = 50

  override def manifest(o: AnyRef): String = {
    val result = o.getClass.getName
    logger.debug(s"manifest: $result")
    result
  }

  override def toBinary(o: AnyRef): Array[Byte] = o match {
    case orig: BankAccountOpened       => CirceJsonSerialization.toBinary(orig, isDebugEnabled)
    case orig: BankAccountEventUpdated => CirceJsonSerialization.toBinary(orig, isDebugEnabled)
    case orig: BankAccountDeposited    => CirceJsonSerialization.toBinary(orig, isDebugEnabled)
    case orig: BankAccountWithdrawn    => CirceJsonSerialization.toBinary(orig, isDebugEnabled)
    case orig: BankAccountClosed       => CirceJsonSerialization.toBinary(orig, isDebugEnabled)
  }

  override def fromBinary(bytes: Array[Byte], manifest: String): AnyRef = {
    logger.debug(s"fromBinary: $manifest")
    manifest match {
      case CREATE =>
        CirceJsonSerialization.fromBinary[BankAccountOpened, BankAccountCreatedJson](bytes, isDebugEnabled)
      case UPDATE =>
        CirceJsonSerialization.fromBinary[BankAccountEventUpdated, BankAccountUpdatedJson](bytes, isDebugEnabled)
      case DEPOSIT =>
        CirceJsonSerialization.fromBinary[BankAccountDeposited, BankAccountDepositedJson](bytes, isDebugEnabled)
      case WITHDRAW =>
        CirceJsonSerialization.fromBinary[BankAccountWithdrawn, BankAccountWithdrawedJson](bytes, isDebugEnabled)
      case DESTROY =>
        CirceJsonSerialization.fromBinary[BankAccountClosed, BankAccountDestroyedJson](bytes, isDebugEnabled)
    }
  }
} 
Example 5
Source File: PersistentRepr.scala    From aecor   with MIT License 5 votes vote down vote up
package aecor.runtime.akkapersistence.serialization

import akka.actor.ExtendedActorSystem
import akka.serialization.{ BaseSerializer, SerializerWithStringManifest }

final case class PersistentRepr(manifest: String, payload: Array[Byte])

class PersistentReprSerializer(val system: ExtendedActorSystem)
    extends SerializerWithStringManifest
    with BaseSerializer {

  override def toBinary(o: AnyRef): Array[Byte] = o match {
    case pr: PersistentRepr => pr.payload
    case x => throw new IllegalArgumentException(s"Serialization of [$x] is not supported")
  }

  override def manifest(o: AnyRef): String = o match {
    case pr: PersistentRepr => pr.manifest
    case x => throw new IllegalArgumentException(s"Serialization of [$x] is not supported")
  }

  override def fromBinary(bytes: Array[Byte], manifest: String): AnyRef =
    PersistentRepr(manifest, bytes)
} 
Example 6
Source File: MessageSerializer.scala    From aecor   with MIT License 5 votes vote down vote up
package aecor.runtime.akkapersistence.serialization

import aecor.runtime.akkapersistence.AkkaPersistenceRuntime.EntityCommand
import aecor.runtime.akkapersistence.AkkaPersistenceRuntimeActor.{ CommandResult, HandleCommand }
import akka.actor.ExtendedActorSystem
import akka.serialization.{ BaseSerializer, SerializerWithStringManifest }
import com.google.protobuf.ByteString
import scodec.bits.BitVector

import scala.collection.immutable._

class MessageSerializer(val system: ExtendedActorSystem)
    extends SerializerWithStringManifest
    with BaseSerializer {

  val HandleCommandManifest = "A"
  val EntityCommandManifest = "B"
  val CommandResultManifest = "C"

  private val fromBinaryMap =
    HashMap[String, Array[Byte] => AnyRef](
      HandleCommandManifest -> handleCommandFromBinary,
      EntityCommandManifest -> entityCommandFromBinary,
      CommandResultManifest -> commandResultFromBinary
    )

  override def manifest(o: AnyRef): String = o match {
    case HandleCommand(_)    => HandleCommandManifest
    case EntityCommand(_, _) => EntityCommandManifest
    case CommandResult(_)    => CommandResultManifest
    case x                   => throw new IllegalArgumentException(s"Serialization of [$x] is not supported")
  }

  override def toBinary(o: AnyRef): Array[Byte] = o match {
    case x @ HandleCommand(_) =>
      x.commandBytes.toByteArray
    case _ @CommandResult(resultBytes) =>
      resultBytes.toByteArray
    case x @ EntityCommand(_, _) =>
      entityCommandToBinary(x)
    case x => throw new IllegalArgumentException(s"Serialization of [$x] is not supported")
  }

  override def fromBinary(bytes: Array[Byte], manifest: String): AnyRef =
    fromBinaryMap.get(manifest) match {
      case Some(f) => f(bytes)
      case other   => throw new IllegalArgumentException(s"Unknown manifest [$other]")
    }

  private def entityCommandToBinary(a: EntityCommand): Array[Byte] =
    msg.EntityCommand(a.entityKey, ByteString.copyFrom(a.commandBytes.toByteBuffer)).toByteArray

  private def entityCommandFromBinary(bytes: Array[Byte]): EntityCommand =
    msg.EntityCommand.parseFrom(bytes) match {
      case msg.EntityCommand(entityId, commandBytes) =>
        EntityCommand(entityId, BitVector(commandBytes.asReadOnlyByteBuffer))
    }

  private def handleCommandFromBinary(bytes: Array[Byte]): HandleCommand =
    HandleCommand(BitVector(bytes))

  private def commandResultFromBinary(bytes: Array[Byte]): CommandResult =
    CommandResult(BitVector(bytes))

} 
Example 7
Source File: MessageSerializer.scala    From aecor   with MIT License 5 votes vote down vote up
package aecor.runtime.akkageneric.serialization

import aecor.runtime.akkageneric.GenericAkkaRuntime.KeyedCommand
import aecor.runtime.akkageneric.GenericAkkaRuntimeActor.{ Command, CommandResult }
import akka.actor.ExtendedActorSystem
import akka.serialization.{ BaseSerializer, SerializerWithStringManifest }
import com.google.protobuf.ByteString
import scodec.bits.BitVector

import scala.collection.immutable.HashMap

class MessageSerializer(val system: ExtendedActorSystem)
    extends SerializerWithStringManifest
    with BaseSerializer {

  val KeyedCommandManifest = "A"
  val CommandManifest = "B"
  val CommandResultManifest = "C"

  private val fromBinaryMap =
    HashMap[String, Array[Byte] => AnyRef](
      KeyedCommandManifest -> keyedCommandFromBinary,
      CommandManifest -> commandFromBinary,
      CommandResultManifest -> commandResultFromBinary
    )

  override def manifest(o: AnyRef): String = o match {
    case KeyedCommand(_, _) => KeyedCommandManifest
    case Command(_)         => CommandManifest
    case CommandResult(_)   => CommandResultManifest
    case x                  => throw new IllegalArgumentException(s"Serialization of [$x] is not supported")
  }

  override def toBinary(o: AnyRef): Array[Byte] = o match {
    case Command(bytes) =>
      bytes.toByteArray
    case CommandResult(bytes) =>
      bytes.toByteArray
    case x @ KeyedCommand(_, _) =>
      entityCommandToBinary(x)
    case x => throw new IllegalArgumentException(s"Serialization of [$x] is not supported")
  }

  override def fromBinary(bytes: Array[Byte], manifest: String): AnyRef =
    fromBinaryMap.get(manifest) match {
      case Some(f) => f(bytes)
      case other   => throw new IllegalArgumentException(s"Unknown manifest [$other]")
    }

  private def entityCommandToBinary(a: KeyedCommand): Array[Byte] =
    msg.KeyedCommand(a.key, ByteString.copyFrom(a.bytes.toByteBuffer)).toByteArray

  private def keyedCommandFromBinary(bytes: Array[Byte]): KeyedCommand =
    msg.KeyedCommand.parseFrom(bytes) match {
      case msg.KeyedCommand(key, commandBytes) =>
        KeyedCommand(key, BitVector(commandBytes.asReadOnlyByteBuffer()))
    }

  private def commandFromBinary(bytes: Array[Byte]): Command =
    Command(BitVector(bytes))

  private def commandResultFromBinary(bytes: Array[Byte]): CommandResult =
    CommandResult(BitVector(bytes))
} 
Example 8
Source File: MessageSerializer.scala    From aecor   with MIT License 5 votes vote down vote up
package aecor.distributedprocessing.serialization

import aecor.distributedprocessing.DistributedProcessingWorker.KeepRunning
import akka.actor.ExtendedActorSystem
import akka.serialization.{ BaseSerializer, SerializerWithStringManifest }

class MessageSerializer(val system: ExtendedActorSystem)
    extends SerializerWithStringManifest
    with BaseSerializer {
  val KeepRunningManifest = "A"
  override def manifest(o: AnyRef): String = o match {
    case KeepRunning(_) => KeepRunningManifest
    case x => throw new IllegalArgumentException(s"Serialization of [$x] is not supported")
  }

  override def toBinary(o: AnyRef): Array[Byte] = o match {
    case KeepRunning(workerId) => msg.KeepRunning(workerId).toByteArray
    case x => throw new IllegalArgumentException(s"Serialization of [$x] is not supported")
  }

  override def fromBinary(bytes: Array[Byte], manifest: String): AnyRef =
    manifest match {
      case KeepRunningManifest =>
        KeepRunning(msg.KeepRunning.parseFrom(bytes).workerId)
      case other => throw new IllegalArgumentException(s"Unknown manifest [$other]")
    }
} 
Example 9
Source File: EventSerializer.scala    From nexus-iam   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.iam.io

import java.nio.charset.Charset

import akka.actor.ExtendedActorSystem
import akka.serialization.SerializerWithStringManifest
import ch.epfl.bluebrain.nexus.iam.acls.AclEvent
import ch.epfl.bluebrain.nexus.iam.config.AppConfig.HttpConfig
import ch.epfl.bluebrain.nexus.iam.config.Settings
import ch.epfl.bluebrain.nexus.iam.permissions.PermissionsEvent
import ch.epfl.bluebrain.nexus.iam.realms.RealmEvent
import ch.epfl.bluebrain.nexus.iam.types.GrantType.Camel._
import ch.epfl.bluebrain.nexus.rdf.Iri.Url
import ch.epfl.bluebrain.nexus.rdf.implicits._
import io.circe.generic.extras.Configuration
import io.circe.generic.extras.semiauto._
import io.circe.parser._
import io.circe.syntax._
import io.circe.{Decoder, Encoder, Printer}


class EventSerializer(system: ExtendedActorSystem) extends SerializerWithStringManifest {
  private val utf8 = Charset.forName("UTF-8")

  private val printer = Printer.noSpaces.copy(dropNullValues = true)

  private[io] implicit val http: HttpConfig = Settings(system).appConfig.http

  private[io] implicit val config: Configuration = Configuration.default.withDiscriminator("@type")

  private[io] implicit val urlEncoder: Encoder[Url] =
    Encoder.encodeString.contramap(_.asUri)
  private[io] implicit val urlDecoder: Decoder[Url] =
    Decoder.decodeString.emap(Url.apply)

  private[io] implicit val permissionEventEncoder: Encoder[PermissionsEvent] = deriveConfiguredEncoder[PermissionsEvent]
  private[io] implicit val permissionEventDecoder: Decoder[PermissionsEvent] = deriveConfiguredDecoder[PermissionsEvent]
  private[io] implicit val aclEventEncoder: Encoder[AclEvent]                = deriveConfiguredEncoder[AclEvent]
  private[io] implicit val aclEventDecoder: Decoder[AclEvent]                = deriveConfiguredDecoder[AclEvent]
  private[io] implicit val realmEventEncoder: Encoder[RealmEvent]            = deriveConfiguredEncoder[RealmEvent]
  private[io] implicit val realmEventDecoder: Decoder[RealmEvent]            = deriveConfiguredDecoder[RealmEvent]

  override val identifier: Int = 1225

  override def manifest(o: AnyRef): String = o match {
    case _: PermissionsEvent => "permissions-event"
    case _: AclEvent         => "acl-event"
    case _: RealmEvent       => "realm-event"
    case other =>
      throw new IllegalArgumentException(
        s"Cannot determine manifest for unknown type: '${other.getClass.getCanonicalName}'"
      )
  }
  override def toBinary(o: AnyRef): Array[Byte] = o match {
    case ev: PermissionsEvent => ev.asJson.printWith(printer).getBytes(utf8)
    case ev: AclEvent         => ev.asJson.printWith(printer).getBytes(utf8)
    case ev: RealmEvent       => ev.asJson.printWith(printer).getBytes(utf8)
    case other =>
      throw new IllegalArgumentException(s"Cannot serialize unknown type: '${other.getClass.getCanonicalName}'")
  }
  override def fromBinary(bytes: Array[Byte], manifest: String): AnyRef = manifest match {
    case "permissions-event" =>
      val str = new String(bytes, utf8)
      decode[PermissionsEvent](str)
        .getOrElse(throw new IllegalArgumentException(s"Cannot deserialize value: '$str' to 'PermissionsEvent'"))
    case "acl-event" =>
      val str = new String(bytes, utf8)
      decode[AclEvent](str)
        .getOrElse(throw new IllegalArgumentException(s"Cannot deserialize value: '$str' to 'AclEvent'"))
    case "realm-event" =>
      val str = new String(bytes, utf8)
      decode[RealmEvent](str)
        .getOrElse(throw new IllegalArgumentException(s"Cannot deserialize value: '$str' to 'RealmEvent'"))
    case other =>
      throw new IllegalArgumentException(s"Cannot deserialize type with unknown manifest: '$other'")
  }
} 
Example 10
Source File: AggregateEventSerializer.scala    From akka-cqrs   with Apache License 2.0 5 votes vote down vote up
package com.productfoundry.akka.serialization

import akka.serialization.{BaseSerializer, SerializerWithStringManifest}
import com.productfoundry.akka.cqrs.AggregateEvent

trait AggregateEventSerializer[T <: AggregateEvent]
  extends SerializerWithStringManifest
    with BaseSerializer
    with EntityMessageSerializer {

  override final def manifest(o: AnyRef): String = {
    eventManifest(o.asInstanceOf[T])
  }

  override final def toBinary(o: AnyRef): Array[Byte] = {
    eventToBinary(o.asInstanceOf[T]).toByteArray
  }

  override final def fromBinary(bytes: Array[Byte], manifest: String): AnyRef = {
    if (eventFromBinary.isDefinedAt(manifest)) {
      eventFromBinary(manifest)(bytes)
    } else {
      throw UnknownEventException(manifest)
    }
  }
} 
Example 11
Source File: LocalCommitPublisher.scala    From akka-cqrs   with Apache License 2.0 5 votes vote down vote up
package com.productfoundry.akka.cqrs

import akka.serialization.{SerializationExtension, SerializerWithStringManifest}

import scala.util.Try


  override def handleCommit(commit: Commit, response: AggregateResponse): AggregateResponse = {
    val handleAttempt = for {
      serializer <- Try(serialization.findSerializerFor(commit).asInstanceOf[SerializerWithStringManifest])
      bytes <- Try(serializer.toBinary(commit))
      deserialized <- Try(serializer.fromBinary(bytes, serializer.manifest(commit)).asInstanceOf[Commit])
      validated <- Try (if (deserialized == commit) deserialized else throw new IllegalStateException(s"expected: $commit; actual: $deserialized"))
    } yield {
      context.system.eventStream.publish(validated)
    }

    handleAttempt.recover {
      case e => log.error(e, "Handling commit")
    }

    response
  }
} 
Example 12
Source File: PayloadSerializer.scala    From eventuate   with Apache License 2.0 5 votes vote down vote up
package com.rbmhtechnology.eventuate.serializer

import akka.actor.ExtendedActorSystem
import akka.serialization.SerializationExtension
import akka.serialization.SerializerWithStringManifest
import com.google.protobuf.ByteString
import com.rbmhtechnology.eventuate.BinaryPayload
import com.rbmhtechnology.eventuate.serializer.CommonFormats.PayloadFormat


class BinaryPayloadSerializer(system: ExtendedActorSystem) extends PayloadSerializer {

  override def payloadFormatBuilder(payload: AnyRef): PayloadFormat.Builder = {
    val binaryPayload = payload.asInstanceOf[BinaryPayload]
    val builder = PayloadFormat.newBuilder()
      .setPayload(binaryPayload.bytes)
      .setSerializerId(binaryPayload.serializerId)
      .setIsStringManifest(binaryPayload.isStringManifest)
    binaryPayload.manifest.foreach(builder.setPayloadManifest)
    builder
  }

  override def payload(payloadFormat: PayloadFormat): AnyRef = {
    BinaryPayload(
      payloadFormat.getPayload,
      payloadFormat.getSerializerId,
      if (payloadFormat.hasPayloadManifest) Some(payloadFormat.getPayloadManifest) else None,
      payloadFormat.getIsStringManifest)
  }
} 
Example 13
Source File: ProtobufAnySerializer.scala    From cloudstate   with Apache License 2.0 5 votes vote down vote up
package io.cloudstate.proxy

import akka.serialization.{BaseSerializer, SerializerWithStringManifest}
import akka.actor.ExtendedActorSystem
import com.google.protobuf.ByteString
import com.google.protobuf.any.{Any => pbAny}

final class ProtobufAnySerializer(override val system: ExtendedActorSystem)
    extends SerializerWithStringManifest
    with BaseSerializer {

  final override def manifest(o: AnyRef): String = o match {
    case any: pbAny => any.typeUrl
    case _ =>
      throw new IllegalArgumentException(s"$this only supports com.google.protobuf.any.Any, not ${o.getClass.getName}!")
  }

  final override def toBinary(o: AnyRef): Array[Byte] = o match {
    case any: pbAny => any.value.toByteArray
    case _ =>
      throw new IllegalArgumentException(s"$this only supports com.google.protobuf.any.Any, not ${o.getClass.getName}!")
  }

  final override def fromBinary(bytes: Array[Byte], manifest: String): AnyRef = manifest match {
    case null =>
      throw new IllegalArgumentException("null manifest detected instead of valid com.google.protobuf.any.Any.typeUrl")
    case typeUrl => pbAny(typeUrl, ByteString.copyFrom(bytes))
  }
} 
Example 14
Source File: EventSerializer.scala    From nexus   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.iam.io

import java.nio.charset.Charset

import akka.actor.ExtendedActorSystem
import akka.serialization.SerializerWithStringManifest
import ch.epfl.bluebrain.nexus.iam.acls.AclEvent
import ch.epfl.bluebrain.nexus.iam.permissions.PermissionsEvent
import ch.epfl.bluebrain.nexus.iam.realms.RealmEvent
import ch.epfl.bluebrain.nexus.iam.types.GrantType.Camel._
import ch.epfl.bluebrain.nexus.rdf.Iri.Url
import ch.epfl.bluebrain.nexus.rdf.implicits._
import ch.epfl.bluebrain.nexus.service.config.ServiceConfig.HttpConfig
import ch.epfl.bluebrain.nexus.service.config.Settings
import io.circe.generic.extras.Configuration
import io.circe.generic.extras.semiauto._
import io.circe.parser._
import io.circe.syntax._
import io.circe.{Decoder, Encoder, Printer}


class EventSerializer(system: ExtendedActorSystem) extends SerializerWithStringManifest {
  private val utf8 = Charset.forName("UTF-8")

  private val printer = Printer.noSpaces.copy(dropNullValues = true)

  implicit private[io] val http: HttpConfig = Settings(system).serviceConfig.http

  implicit private[io] val config: Configuration = Configuration.default.withDiscriminator("@type")

  implicit private[io] val urlEncoder: Encoder[Url] =
    Encoder.encodeString.contramap(_.asUri)
  implicit private[io] val urlDecoder: Decoder[Url] =
    Decoder.decodeString.emap(Url.apply)

  implicit private[io] val permissionEventEncoder: Encoder[PermissionsEvent] = deriveConfiguredEncoder[PermissionsEvent]
  implicit private[io] val permissionEventDecoder: Decoder[PermissionsEvent] = deriveConfiguredDecoder[PermissionsEvent]
  implicit private[io] val aclEventEncoder: Encoder[AclEvent]                = deriveConfiguredEncoder[AclEvent]
  implicit private[io] val aclEventDecoder: Decoder[AclEvent]                = deriveConfiguredDecoder[AclEvent]
  implicit private[io] val realmEventEncoder: Encoder[RealmEvent]            = deriveConfiguredEncoder[RealmEvent]
  implicit private[io] val realmEventDecoder: Decoder[RealmEvent]            = deriveConfiguredDecoder[RealmEvent]

  override val identifier: Int = 1225

  override def manifest(o: AnyRef): String                              =
    o match {
      case _: PermissionsEvent => "permissions-event"
      case _: AclEvent         => "acl-event"
      case _: RealmEvent       => "realm-event"
      case other               =>
        throw new IllegalArgumentException(
          s"Cannot determine manifest for unknown type: '${other.getClass.getCanonicalName}'"
        )
    }
  override def toBinary(o: AnyRef): Array[Byte]                         =
    o match {
      case ev: PermissionsEvent => ev.asJson.printWith(printer).getBytes(utf8)
      case ev: AclEvent         => ev.asJson.printWith(printer).getBytes(utf8)
      case ev: RealmEvent       => ev.asJson.printWith(printer).getBytes(utf8)
      case other                =>
        throw new IllegalArgumentException(s"Cannot serialize unknown type: '${other.getClass.getCanonicalName}'")
    }
  override def fromBinary(bytes: Array[Byte], manifest: String): AnyRef =
    manifest match {
      case "permissions-event" =>
        val str = new String(bytes, utf8)
        decode[PermissionsEvent](str)
          .getOrElse(throw new IllegalArgumentException(s"Cannot deserialize value: '$str' to 'PermissionsEvent'"))
      case "acl-event"         =>
        val str = new String(bytes, utf8)
        decode[AclEvent](str)
          .getOrElse(throw new IllegalArgumentException(s"Cannot deserialize value: '$str' to 'AclEvent'"))
      case "realm-event"       =>
        val str = new String(bytes, utf8)
        decode[RealmEvent](str)
          .getOrElse(throw new IllegalArgumentException(s"Cannot deserialize value: '$str' to 'RealmEvent'"))
      case other               =>
        throw new IllegalArgumentException(s"Cannot deserialize type with unknown manifest: '$other'")
    }
} 
Example 15
Source File: AkkaCoproductSerializer.scala    From nexus   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.commons.serialization

import akka.serialization.SerializerWithStringManifest
import shapeless._
import shapeless.ops.coproduct.Unifier


class AkkaCoproductSerializer[C <: Coproduct](override val identifier: Int)(implicit
    C: CoproductSerializer[C],
    U: Unifier[C]
) extends SerializerWithStringManifest {

  final override def manifest(o: AnyRef): String =
    C.manifest(o)
      .getOrElse(throw new IllegalArgumentException(s"Unable to compute manifest; unknown type '$o'"))

  final override def toBinary(o: AnyRef): Array[Byte] =
    C.toBinary(o)
      .getOrElse(throw new IllegalArgumentException(s"Unable to encode to binary; unknown type '$o'"))

  final override def fromBinary(bytes: Array[Byte], manifest: String): AnyRef =
    C.fromBinary(bytes, manifest)
      .map(c => c.unify.asInstanceOf[AnyRef])
      .getOrElse(throw new IllegalArgumentException(s"Unable to decode from binary; unknown manifest '$manifest'"))
} 
Example 16
Source File: EventSerializer.scala    From nexus   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.admin.persistence

import akka.actor.ExtendedActorSystem
import akka.serialization.SerializerWithStringManifest
import ch.epfl.bluebrain.nexus.admin.organizations.OrganizationEvent
import ch.epfl.bluebrain.nexus.admin.projects.ProjectEvent
import ch.epfl.bluebrain.nexus.commons.serialization.AkkaCoproductSerializer
import ch.epfl.bluebrain.nexus.rdf.implicits._
import ch.epfl.bluebrain.nexus.service.config.ServiceConfig.HttpConfig
import ch.epfl.bluebrain.nexus.service.config.Settings
import io.circe.generic.extras.Configuration
import io.circe.generic.extras.semiauto.{deriveConfiguredDecoder, deriveConfiguredEncoder}
import io.circe.{Decoder, Encoder}
import shapeless.{:+:, CNil}

import scala.annotation.nowarn

@nowarn("cat=unused")
class EventSerializer(system: ExtendedActorSystem) extends SerializerWithStringManifest {

  implicit private val httpConfig: HttpConfig = Settings(system).serviceConfig.http

  implicit private val config: Configuration = Configuration.default.withDiscriminator("@type")

  implicit private val projectEventDecoder: Decoder[ProjectEvent]           = deriveConfiguredDecoder[ProjectEvent]
  implicit private val projectEventEncoder: Encoder[ProjectEvent]           = deriveConfiguredEncoder[ProjectEvent]
  implicit private val organizationEventDecoder: Decoder[OrganizationEvent] = deriveConfiguredDecoder[OrganizationEvent]
  implicit private val organizationEventEncoder: Encoder[OrganizationEvent] = deriveConfiguredEncoder[OrganizationEvent]

  private val serializer = new AkkaCoproductSerializer[OrganizationEvent :+: ProjectEvent :+: CNil](1129)

  override val identifier: Int = serializer.identifier

  override def manifest(o: AnyRef): String = serializer.manifest(o)

  override def toBinary(o: AnyRef): Array[Byte] = serializer.toBinary(o)

  override def fromBinary(bytes: Array[Byte], manifest: String): AnyRef = serializer.fromBinary(bytes, manifest)
} 
Example 17
Source File: PayloadSerializer.scala    From akka-stream-eventsourcing   with Apache License 2.0 5 votes vote down vote up
package com.github.krasserm.ases.serializer

import akka.actor.ExtendedActorSystem
import akka.serialization.{SerializationExtension, SerializerWithStringManifest}
import com.github.krasserm.ases.serializer.PayloadFormatOuterClass.PayloadFormat
import com.google.protobuf.ByteString

import scala.util.Try

class PayloadSerializer(system: ExtendedActorSystem) {

  def payloadFormatBuilder(payload: AnyRef): PayloadFormat.Builder = {
    val serializer = SerializationExtension(system).findSerializerFor(payload)
    val builder = PayloadFormat.newBuilder()

    if (serializer.includeManifest) {
      val (isStringManifest, manifest) = serializer match {
        case s: SerializerWithStringManifest => (true, s.manifest(payload))
        case _ => (false, payload.getClass.getName)
      }
      builder.setIsStringManifest(isStringManifest)
      builder.setPayloadManifest(manifest)
    }
    builder.setSerializerId(serializer.identifier)
    builder.setPayload(ByteString.copyFrom(serializer.toBinary(payload)))
  }

  def payload(payloadFormat: PayloadFormat): AnyRef = {
    val payload = if (payloadFormat.getIsStringManifest)
      payloadFromStringManifest(payloadFormat)
    else if (payloadFormat.getPayloadManifest.nonEmpty)
      payloadFromClassManifest(payloadFormat)
    else
      payloadFromEmptyManifest(payloadFormat)

    payload.get
  }

  private def payloadFromStringManifest(payloadFormat: PayloadFormat): Try[AnyRef] = {
    SerializationExtension(system).deserialize(
      payloadFormat.getPayload.toByteArray,
      payloadFormat.getSerializerId,
      payloadFormat.getPayloadManifest
    )
  }

  private def payloadFromClassManifest(payloadFormat: PayloadFormat): Try[AnyRef]  = {
    val manifestClass = system.dynamicAccess.getClassFor[AnyRef](payloadFormat.getPayloadManifest).get
    SerializationExtension(system).deserialize(
      payloadFormat.getPayload.toByteArray,
      payloadFormat.getSerializerId,
      Some(manifestClass)
    )
  }

  private def payloadFromEmptyManifest(payloadFormat: PayloadFormat): Try[AnyRef]  = {
    SerializationExtension(system).deserialize(
      payloadFormat.getPayload.toByteArray,
      payloadFormat.getSerializerId,
      None
    )
  }
} 
Example 18
Source File: JsonSerializer.scala    From akka-persistence-couchbase   with Apache License 2.0 5 votes vote down vote up
package akka.persistence.couchbase
import akka.serialization.SerializerWithStringManifest
import com.couchbase.client.java.document.json.JsonObject
import com.couchbase.client.java.transcoder.JacksonTransformers


abstract class JsonSerializer extends SerializerWithStringManifest {
  def toJson(o: AnyRef): JsonObject
  def fromJson(json: JsonObject, manifest: String): AnyRef

  override def toBinary(o: AnyRef): Array[Byte] = {
    val json = toJson(o)
    val wrapper = JsonObject
      .create()
      .put("payload", json)
      .put("manifest", manifest(o))
    JacksonTransformers.MAPPER.writeValueAsBytes(wrapper)
  }

  override def fromBinary(bytes: Array[Byte], manifest: String): AnyRef = {
    val wrapper = JacksonTransformers.MAPPER.readValue(bytes, classOf[JsonObject])
    fromJson(wrapper.getObject("payload"), wrapper.getString("manifest"))
  }
} 
Example 19
Source File: ClusterMessageSerializer.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.internal.cluster

import akka.actor.ExtendedActorSystem
import akka.serialization.SerializerWithStringManifest
import akka.serialization.BaseSerializer
import com.lightbend.lagom.internal.cluster.ClusterDistribution.EnsureActive
import com.lightbend.lagom.internal.cluster.protobuf.msg.{ ClusterMessages => cm }

private[lagom] class ClusterMessageSerializer(val system: ExtendedActorSystem)
    extends SerializerWithStringManifest
    with BaseSerializer {
  val EnsureActiveManifest = "E"

  override def manifest(obj: AnyRef): String = obj match {
    case _: EnsureActive => EnsureActiveManifest
    case _ =>
      throw new IllegalArgumentException(s"Can't serialize object of type ${obj.getClass} in [${getClass.getName}]")
  }

  def toBinary(obj: AnyRef): Array[Byte] = obj match {
    case ea: EnsureActive => ensureActiveToProto(ea).toByteArray
    case _ =>
      throw new IllegalArgumentException(s"Can't serialize object of type ${obj.getClass} in [${getClass.getName}]")
  }

  private def ensureActiveToProto(ensureActive: EnsureActive): cm.EnsureActive = {
    cm.EnsureActive.newBuilder().setEntityId(ensureActive.entityId).build()
  }

  override def fromBinary(bytes: Array[Byte], manifest: String): AnyRef = manifest match {
    case EnsureActiveManifest => ensureActiveFromBinary(bytes)
    case _ =>
      throw new IllegalArgumentException(
        s"Unimplemented deserialization of message with manifest [$manifest] in [${getClass.getName}]"
      )
  }

  private def ensureActiveFromBinary(bytes: Array[Byte]): EnsureActive = {
    ensureActiveFromProto(cm.EnsureActive.parseFrom(bytes))
  }

  private def ensureActiveFromProto(ensureActive: cm.EnsureActive): EnsureActive = {
    EnsureActive(ensureActive.getEntityId)
  }
} 
Example 20
Source File: ClusterStartupTaskSerializer.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.internal.persistence.cluster

import akka.actor.ExtendedActorSystem
import akka.serialization.BaseSerializer
import akka.serialization.SerializerWithStringManifest
import com.lightbend.lagom.internal.persistence.cluster.ClusterStartupTaskActor.Execute

private[lagom] class ClusterStartupTaskSerializer(val system: ExtendedActorSystem)
    extends SerializerWithStringManifest
    with BaseSerializer {
  val ExecuteManifest = "E"

  override def manifest(obj: AnyRef) = obj match {
    case Execute => ExecuteManifest
    case _ =>
      throw new IllegalArgumentException(s"Can't serialize object of type ${obj.getClass} in [${getClass.getName}]")
  }

  override def toBinary(obj: AnyRef) = obj match {
    case Execute => Array.emptyByteArray
    case _ =>
      throw new IllegalArgumentException(s"Can't serialize object of type ${obj.getClass} in [${getClass.getName}]")
  }

  override def fromBinary(bytes: Array[Byte], manifest: String) = manifest match {
    case `ExecuteManifest` => Execute
    case _ =>
      throw new IllegalArgumentException(
        s"Unimplemented deserialization of message with manifest [$manifest] in [${getClass.getName}]"
      )
  }
} 
Example 21
Source File: PersistenceTckSerializer.scala    From kafka-journal   with MIT License 5 votes vote down vote up
package akka.persistence.journal

import java.io.NotSerializableException

import akka.persistence.journal.JournalPerfSpec.Cmd
import akka.serialization.SerializerWithStringManifest
import scodec.bits.BitVector
import scodec.{Codec, codecs}

class PersistenceTckSerializer extends SerializerWithStringManifest {
  import PersistenceTckSerializer._

  def identifier = 585506118

  def manifest(a: AnyRef): String = a match {
    case _: Cmd => cmdManifest
    case _      => illegalArgument(s"Cannot serialize message of ${ a.getClass } in ${ getClass.getName }")
  }

  def toBinary(a: AnyRef): Array[Byte] = {
    a match {
      case a: Cmd => cmdCodec.encode(a).require.toByteArray
      case _      => illegalArgument(s"Cannot serialize message of ${ a.getClass } in ${ getClass.getName }")
    }
  }

  def fromBinary(bytes: Array[Byte], manifest: String): AnyRef = {
    manifest match {
      case `cmdManifest` => cmdCodec.decode(BitVector.view(bytes)).require.value
      case _             => notSerializable(s"Cannot deserialize message for manifest $manifest in ${ getClass.getName }")
    }
  }

  private def notSerializable(msg: String) = throw new NotSerializableException(msg)

  private def illegalArgument(msg: String) = throw new IllegalArgumentException(msg)
}

object PersistenceTckSerializer {

  val cmdManifest = "A"

  implicit val cmdCodec: Codec[Cmd] = {
    val codec = codecs.utf8_32 :: codecs.int32
    codec.as[Cmd]
  }
} 
Example 22
Source File: HttpRequestSerializer.scala    From rokku   with Apache License 2.0 5 votes vote down vote up
package com.ing.wbaa.rokku.proxy.persistence.serializers

import java.nio.charset.Charset

import akka.http.scaladsl.model.{ HttpEntity, HttpRequest, RemoteAddress }
import akka.serialization.SerializerWithStringManifest
import com.ing.wbaa.rokku.proxy.data.{ User, UserRawJson }
import com.ing.wbaa.rokku.proxy.persistence.{ CurrentRequestsState, ExecutedRequestEvt }
import spray.json._

class HttpRequestSerializer extends SerializerWithStringManifest with HttpRequestConversionSupport {
  override def identifier: Int = 197642

  val Utf8 = Charset.forName("UTF-8")
  val HttpRequestManifest = classOf[ExecutedRequestEvt].getName
  val HttpRequestsManifest = classOf[CurrentRequestsState].getName

  def simplifiedHttpRequestString(e: HttpRequest) =
    SimplifiedHttpRequest(
      e.method.value,
      e.uri.toString(),
      convertAkkaHeadersToStrings(e.headers),
      HttpEntity.Empty.withContentType(e.entity.contentType).toString(),
      e.protocol.value
    ).toJson.toString

  def userSTSString(u: User) =
    UserRawJson(
      u.userName.value,
      Option(u.userGroups.map(g => g.value)),
      u.accessKey.value,
      u.secretKey.value,
      Option(u.userRole.value)).toJson.toString

  def remoteIPString(a: RemoteAddress) = SimplifiedRemoteAddress(a.value).toJson.toString()

  def toExecutedRequestEvt(r: String) = {
    val Array(hr, u, ip) = r.split("[|]")
    val httpRequest = toAkkaHttpRequest(hr.parseJson.convertTo[SimplifiedHttpRequest])
    val userSTS = User(u.parseJson.convertTo[UserRawJson])
    val simplifiedRemoteAddress = ip.parseJson.convertTo[SimplifiedRemoteAddress]

    ExecutedRequestEvt(httpRequest, userSTS, simplifiedRemoteAddress.toRemoteAddr)
  }

  override def manifest(o: AnyRef): String = o.getClass.getName

  override def toBinary(o: AnyRef): Array[Byte] =
    o match {
      case r: ExecutedRequestEvt =>
        s"${simplifiedHttpRequestString(r.httpRequest)}|${userSTSString(r.userSTS)}|${remoteIPString(r.clientIPAddress)}".getBytes(Utf8)

      case c: CurrentRequestsState =>
        c.requests.map { re =>
          s"${simplifiedHttpRequestString(re.httpRequest)}|${userSTSString(re.userSTS)}|${remoteIPString(re.clientIPAddress)}"
        }.mkString("|-").getBytes(Utf8)

      case e: IllegalArgumentException =>
        throw new IllegalArgumentException(s"Unable to serialize to bytes, class: ${o.getClass} ${e.getMessage}")
    }

  override def fromBinary(bytes: Array[Byte], manifest: String): AnyRef = {
    manifest match {
      case s: String if s == HttpRequestManifest =>
        val storedRequest = new String(bytes, Utf8)
        toExecutedRequestEvt(storedRequest)

      case s: String if s == HttpRequestsManifest =>
        val storedRequests = new String(bytes, Utf8)
        val requestsList: List[String] = storedRequests.split("[|-]{2}").toList
        CurrentRequestsState(requestsList.map(toExecutedRequestEvt))

      case _ => throw new IllegalArgumentException(s"Unable to de-serialize from bytes for manifest: $manifest")
    }
  }
}