1 25 26 package org.objectweb.easybeans.component.smartclient.message; 27 28 import java.io.UnsupportedEncodingException ; 29 import java.nio.ByteBuffer ; 30 import java.nio.CharBuffer ; 31 import java.nio.charset.CharacterCodingException ; 32 import java.nio.charset.Charset ; 33 import java.nio.charset.CharsetDecoder ; 34 35 import org.objectweb.easybeans.component.smartclient.api.Message; 36 import org.objectweb.easybeans.component.smartclient.api.ProtocolConstants; 37 38 43 public abstract class AbsMessage implements Message { 44 45 49 public ByteBuffer getMessage() { 50 ByteBuffer subMessage = getSubMessage(); 51 52 int length = HEADER_SIZE; 54 if (subMessage != null) { 55 length += subMessage.capacity(); 56 } 57 58 ByteBuffer byteBuffer = ByteBuffer.allocate(length); 60 61 byteBuffer.put(ProtocolConstants.PROTOCOL_VERSION); 63 byteBuffer.put(getOpCode()); 64 if (subMessage != null) { 65 byteBuffer.putInt(subMessage.capacity()); 66 } 67 68 if (subMessage != null) { 70 subMessage.position(0); 71 byteBuffer.put(subMessage); 72 } 73 74 byteBuffer.position(0); 76 77 return byteBuffer; 79 } 80 81 85 public abstract byte getOpCode(); 86 87 91 public abstract ByteBuffer getSubMessage(); 92 93 94 99 protected ByteBuffer encode(final String str) { 100 byte[] bytes = null; 101 try { 102 bytes = str.getBytes("UTF-8"); 103 } catch (UnsupportedEncodingException e) { 104 e.printStackTrace(); 106 } 107 ByteBuffer buffer = ByteBuffer.allocate(bytes.length); 108 buffer.put(bytes); 109 return buffer; 110 111 } 112 113 118 protected String decode(final ByteBuffer buffer) { 119 Charset charset = Charset.forName("UTF-8"); 120 CharsetDecoder charsetDecoder = charset.newDecoder(); 121 122 CharBuffer charBuffer = null; 123 try { 124 charBuffer = charsetDecoder.decode(buffer); 125 } catch (CharacterCodingException e) { 126 throw new IllegalStateException ("Invalid characted encoding", e); 127 } 128 return charBuffer.toString(); 129 } 130 131 } 132 | Popular Tags |