forked from KNEMC/KLALB
104 lines
2.2 KiB
Java
104 lines
2.2 KiB
Java
package org.kne.cloud.network.srv6;
|
|
|
|
import java.io.EOFException;
|
|
import java.io.IOException;
|
|
import java.io.Serializable;
|
|
import java.nio.ByteBuffer;
|
|
import java.nio.channels.ReadableByteChannel;
|
|
import java.nio.channels.WritableByteChannel;
|
|
import java.nio.charset.Charset;
|
|
|
|
import org.kne.cloud.network.MultiProtocolSocketAddress;
|
|
|
|
import com.google.gson.Gson;
|
|
import com.google.gson.GsonBuilder;
|
|
|
|
public class JsonDataPacket extends KLALBRoutingProtocolPacket implements Serializable{
|
|
|
|
private Object userCallback;
|
|
|
|
|
|
public Object getUserCallback() {
|
|
return userCallback;
|
|
}
|
|
|
|
public void setUserCallback(Object userCallback) {
|
|
this.userCallback = userCallback;
|
|
}
|
|
|
|
@Override
|
|
protected long getHeaderSize() {
|
|
return HEADER_LENGTH;
|
|
}
|
|
|
|
private String data;
|
|
|
|
private static final int HEADER_LENGTH=3;
|
|
|
|
private static Gson gson;
|
|
static{
|
|
GsonBuilder gb=new GsonBuilder();
|
|
MultiProtocolSocketAddress.registerToGsonBuilder(gb);
|
|
gson=gb.create();
|
|
}
|
|
|
|
public String getData() {
|
|
return data;
|
|
}
|
|
|
|
public KLALBRoutingProtocolJsonData getDecodedData() {
|
|
return gson.fromJson(data,KLALBRoutingProtocolJsonData.class );
|
|
}
|
|
|
|
public JsonDataPacket(String data) {
|
|
super(JSON_DATA);
|
|
this.data=data;
|
|
}
|
|
|
|
public JsonDataPacket(KLALBRoutingProtocolJsonData data) {
|
|
this(gson.toJson(data));
|
|
}
|
|
|
|
|
|
public JsonDataPacket(ByteBuffer bb) {
|
|
super(bb);
|
|
}
|
|
|
|
|
|
@Override
|
|
public String toString() {
|
|
return "JsonDATA "+getData();
|
|
}
|
|
|
|
|
|
|
|
@Override
|
|
public void writeToChannel(WritableByteChannel dto) throws IOException {
|
|
byte[]bta=data.getBytes(Charset.forName("UTF-8"));
|
|
getHeader().putChar(1,(char) bta.length);
|
|
super.writeToChannel(dto);
|
|
dto.write(ByteBuffer.wrap(bta));
|
|
}
|
|
|
|
@Override
|
|
public void readFromChannel(ReadableByteChannel din) throws IOException {
|
|
super.readFromChannel(din);
|
|
int lth=getHeader().getChar(1);
|
|
byte[]b=new byte[lth];
|
|
ByteBuffer wp= ByteBuffer.wrap(b);
|
|
while(wp.hasRemaining()){
|
|
if(din.read(wp)==-1) {
|
|
throw new EOFException();
|
|
}
|
|
}
|
|
data=new String(b, Charset.forName("UTF-8"));
|
|
}
|
|
|
|
@Override
|
|
public long getTotalLength() {
|
|
return HEADER_LENGTH+data.getBytes(Charset.forName("UTF-8")).length;
|
|
}
|
|
|
|
|
|
}
|