1 package com.ubermq.jms.common.datagram.impl; 2 3 import com.ubermq.jms.common.datagram.*; 4 import com.ubermq.kernel.*; 5 import java.nio.*; 6 7 12 public class DelimitedDatagramFactory 13 implements IDatagramFactory 14 { 15 private final byte[] startOfMessage, 16 endOfMessage; 17 18 28 public DelimitedDatagramFactory(byte[] startOfMessage, 29 byte[] endOfMessage) 30 { 31 this.startOfMessage = startOfMessage; 32 this.endOfMessage = endOfMessage; 33 } 34 35 45 public DelimitedDatagramFactory(byte[] endOfMessage) 46 { 47 this(new byte[0], endOfMessage); 48 } 49 50 69 public int frame(ByteBuffer bb) 70 throws java.io.IOException 71 { 72 int som = findSequence(bb, startOfMessage); 76 if (som >= 0) { 77 int eom = findSequence((ByteBuffer)bb.position(som), endOfMessage); 78 if (eom >= 0) { 79 return eom - som + endOfMessage.length; 81 } 82 } 83 84 return Integer.MAX_VALUE; 86 } 87 88 95 private int findSequence(ByteBuffer bb, byte[] seq) 96 { 97 int limit = bb.limit() - seq.length + 1; 99 for (int i = bb.position(); i < limit; i++) 100 { 101 int j; 102 for (j = 0; j < seq.length; j++) 103 { 104 byte b = bb.get(i + j); 105 if (b != seq[j]) 106 break; 107 } 108 109 if (j == seq.length) { 111 return i; 112 } 113 } 114 115 return -1; 116 } 117 118 132 public IDatagram incoming(ByteBuffer bb) throws IllegalArgumentException 133 { 134 bb.position(startOfMessage.length).limit(bb.limit() - endOfMessage.length); 136 137 int type = bb.get(); 138 IDatagram d = DatagramFactory.getInstance().createDatagramInstance(type); 139 140 try { 141 d.incoming(bb); 142 return d; 143 } 144 catch (java.io.IOException e) { 145 throw new IllegalArgumentException (); 146 } 147 } 148 149 160 public void outgoing(ByteBuffer bb, IDatagram d) 161 { 162 bb.put(startOfMessage); 163 bb.put((byte) (d.getDatagramType() & 0xFF)); 164 d.outgoing(bb); 165 bb.put(endOfMessage); 166 } 167 168 169 } 170 | Popular Tags |