You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

103 lines
2.8 KiB

package seng302.Networking.MessageDecoders;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Arrays;
/**
* Created by hba56 on 20/04/17.
*/
public class XMLMessageDecoder {
private byte messageVersionNumber;
private short ackNumber;
private long timeStamp;
private byte xmlMsgSubType;
private short sequenceNumber;
private short xmlMsgLength;
private String xmlMessage;
private byte[] bytes;
public XMLMessageDecoder(byte[] bytes) {
this.bytes = bytes;
}
public void decode() {
byte[] ackNumberBytes = Arrays.copyOfRange(bytes, 1, 3);
byte[] timeStampBytes = Arrays.copyOfRange(bytes, 3, 9);
byte[] sequenceNumberBytes = Arrays.copyOfRange(bytes, 10, 12);
byte[] xmlMsgLengthBytes = Arrays.copyOfRange(bytes, 12, 14);
byte[] xmlMessagebytes = Arrays.copyOfRange(bytes, 14, bytes.length);
this.xmlMsgSubType = bytes[9];
this.messageVersionNumber = bytes[0];
this.ackNumber = bytesToShort(ackNumberBytes);
this.timeStamp = bytesToLong(timeStampBytes);
this.sequenceNumber = bytesToShort(sequenceNumberBytes);
this.xmlMsgLength = bytesToShort(xmlMsgLengthBytes);
this.xmlMessage = new String(xmlMessagebytes);
}
private short bytesToShort(byte[] bytesShort) {
ByteBuffer byteBuffer = ByteBuffer.allocate(2);
byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
byteBuffer.put(bytesShort[0]);
byteBuffer.put(bytesShort[1]);
short shortVal = byteBuffer.getShort(0);
return shortVal;
}
private long bytesToLong(byte[] bytesLong) {
ByteBuffer byteBuffer = ByteBuffer.allocate(8);
byteBuffer.order(ByteOrder.BIG_ENDIAN);
byteBuffer.put((byte) 0);
byteBuffer.put((byte) 0);
byteBuffer.put(bytesLong[0]);
byteBuffer.put(bytesLong[1]);
byteBuffer.put(bytesLong[2]);
byteBuffer.put(bytesLong[3]);
byteBuffer.put(bytesLong[4]);
byteBuffer.put(bytesLong[5]);
// System.out.println("====decode====");
// for (byte i:byteBuffer.array()
// ) {
// System.out.println(i);
// }
// System.out.println("====decode====");
long longVal = byteBuffer.getLong(0);
return longVal;
}
public byte getMessageVersionNumber() {
return messageVersionNumber;
}
public short getAckNumber() {
return ackNumber;
}
public long getTimeStamp() {
return timeStamp;
}
public byte getXmlMsgSubType() {
return xmlMsgSubType;
}
public short getSequenceNumber() {
return sequenceNumber;
}
public short getXmlMsgLength() {
return xmlMsgLength;
}
public String getXmlMessage() {
return xmlMessage;
}
}