All Downloads are FREE. Search and download functionalities are using the official Maven repository.

sss.openstar.message.MessagePayloadDecoder.scala Maven / Gradle / Ivy

package sss.openstar.message


import sss.ancillary.Logging
import sss.openstar.eventbus.MessageInfoComposite
import sss.openstar.message.payloads.MessageEcryption.EncryptedMessage
import sss.openstar.message.payloads.serialize._
import sss.openstar.message.payloads._

import scala.util.{Failure, Success, Try}
/**
  * Created by alan on 12/13/16.
  */
object MessagePayloadDecoder extends Logging {

  object MessagePayloadType extends Enumeration {
    type MessagePayloadType = Value
    val EncryptedMessageType = Value(1.toByte)
    val ChessMessageType = Value(2.toByte)
    val NewQuorumMemberType = Value(3.toByte)
    val TicTacToeType = Value(4.toByte)
    val PaywalledMessageType = Value(5.toByte)
    val NewContactType = Value(6.toByte)
    val CompletedNewContactType = Value(7.toByte)

  }

  import MessagePayloadType._

  private val messageInfos =
    MessageInfoComposite[EncryptedMessage](EncryptedMessageType.id.toByte, classOf[EncryptedMessage], MessageEncryptionSerializer) :+
    MessageInfoComposite[NewQuorumMemberMessage](NewQuorumMemberType.id.toByte, classOf[NewQuorumMemberMessage],  NewQuorumMemberSerializer) :+
    MessageInfoComposite[TicTacToeGameMessage](TicTacToeType.id.toByte, classOf[TicTacToeGameMessage], TicTacToeGameSerializer) :+
    MessageInfoComposite[PaywalledMessage](PaywalledMessageType.id.toByte, classOf[PaywalledMessage], PaywalledMessageSerializer) :+
    MessageInfoComposite[NewContactMessage](NewContactType.id.toByte, classOf[NewContactMessage], NewContactSerializer) :+
    MessageInfoComposite[CompletedNewContactMessage](CompletedNewContactType.id.toByte, classOf[CompletedNewContactMessage], CompletedNewContactSerializer)



  private [message] def fromPayload(payload: MessagePayload): Option[MessageComposite] = {
    messageInfos.find(payload.payloadType).flatMap { info =>
      Try(info.fromBytes(payload.payload)) match {
        case Failure(e) =>
          log.warn(s"Failed to extract msg of type ${payload.payloadType} to ${info}")
          log.warn(e.toString)
          None
        case Success(decoded) =>
          Option(decoded.asInstanceOf[MessageComposite])
      }
    }
  }

  def toPayloadOpt(m: MessageComposite): Option[MessagePayload] =
      messageInfos
        .findByClass(m)
        .map(info =>
          MessagePayload(info.msgCode, info.toBytes(m))
        )


  def toPayload(m: MessageComposite): MessagePayload =
    toPayloadOpt(m)
      .getOrElse(
        throw new IllegalArgumentException(s"No info for class ${m.getClass}")
      )
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy