
org.zbus.remoting.MessageCodec Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of zbus-client Show documentation
Show all versions of zbus-client Show documentation
lightweight message queue, service bus
The newest version!
package org.zbus.remoting;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import org.zbus.remoting.znet.Codec;
import org.zbus.remoting.znet.IoBuffer;
public class MessageCodec implements Codec{
@Override
public IoBuffer encode(Object obj) {
if(!(obj instanceof Message)){
throw new RuntimeException("Message unknown");
}
Message msg = (Message)obj;
IoBuffer buf = IoBuffer.allocate(msg.estimatedSize()+256);
buf.put(msg.getMetaString()+"\r\n");
Map headers = msg.getHead();
int contentLength = 0;
if(msg.getBody() != null){
contentLength = msg.getBody().length;
}
String lenKey = "content-length";
Iterator> iter = headers.entrySet().iterator();
while(iter.hasNext()){
Entry e = iter.next();
buf.put(e.getKey() + ": " + e.getValue() + "\r\n");
}
if(!headers.containsKey(lenKey)){
buf.put(lenKey + ": " + contentLength + "\r\n");
}
buf.put("\r\n");
if(msg.getBody() != null){
buf.put(msg.getBody());
}
buf.flip();
return buf;
}
@Override
public Object decode(IoBuffer buf) {
int headerIdx = findHeaderEnd(buf);
if(headerIdx == -1) return null;
int headerLen = headerIdx+1-buf.position();
buf.mark();
Message msg = new Message();
msg.decodeHeaders(buf.array(), buf.position(), headerLen);
buf.position(buf.position()+headerLen);
String contentLength = msg.getHeadOrParam("content-length");
if(contentLength == null){ //just head
return msg;
}
int bodyLen = Integer.valueOf(contentLength);
if(buf.remaining()
© 2015 - 2025 Weber Informatics LLC | Privacy Policy