io.firebus.Payload Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of firebus-core Show documentation
Show all versions of firebus-core Show documentation
Firebus core functionality
package io.firebus;
import java.io.StringReader;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
public class Payload
{
public byte[] data;
public HashMap metadata;
public Payload()
{
metadata = new HashMap();
data = new byte[0];
}
public Payload(byte[] d)
{
metadata = new HashMap();
data = d;
}
public Payload(String s)
{
metadata = new HashMap();
data = s.getBytes();
}
public Payload(HashMap md, byte[] d)
{
if(md != null)
metadata = md;
else
metadata = new HashMap();
data = d;
}
public byte[] serialise()
{
int len = 4;
if(!metadata.isEmpty())
len += metadata.toString().length();
if(data != null)
len += data.length;
ByteBuffer bb = ByteBuffer.allocate(len);
if(!metadata.isEmpty())
{
String metadataStr = metadata.toString();
bb.putInt(metadataStr.length());
bb.put(metadataStr.getBytes(), 0, metadataStr.length());
}
else
{
bb.putInt(0);
}
if(data != null)
{
bb.put(data);
}
return bb.array();
}
public static Payload deserialise(byte[] encodedMessage)
{
if(encodedMessage != null && encodedMessage.length > 0)
{
ByteBuffer bb = ByteBuffer.wrap(encodedMessage);
int metadataLen = bb.getInt();
String metadataStr = new String(encodedMessage, bb.position(), metadataLen);
bb.position(bb.position() + metadataLen);
byte[] data = new byte[bb.remaining()];
System.arraycopy(encodedMessage, bb.position(), data, 0, bb.remaining());
HashMap metadata = new HashMap();
try
{
Properties props = new Properties();
props.load(new StringReader(metadataStr.substring(1, metadataStr.length() - 1).replace(", ", "\n")));
for (Map.Entry
© 2015 - 2024 Weber Informatics LLC | Privacy Policy