1 20 package org.apache.mina.filter.codec.serialization; 21 22 import java.io.NotSerializableException ; 23 import java.io.Serializable ; 24 25 import org.apache.mina.common.ByteBuffer; 26 import org.apache.mina.common.IoSession; 27 import org.apache.mina.filter.codec.ProtocolEncoder; 28 import org.apache.mina.filter.codec.ProtocolEncoderAdapter; 29 import org.apache.mina.filter.codec.ProtocolEncoderOutput; 30 31 38 public class ObjectSerializationEncoder extends ProtocolEncoderAdapter { 39 private int maxObjectSize = Integer.MAX_VALUE; 41 44 public ObjectSerializationEncoder() { 45 } 46 47 53 public int getMaxObjectSize() { 54 return maxObjectSize; 55 } 56 57 63 public void setMaxObjectSize(int maxObjectSize) { 64 if (maxObjectSize <= 0) { 65 throw new IllegalArgumentException ("maxObjectSize: " 66 + maxObjectSize); 67 } 68 69 this.maxObjectSize = maxObjectSize; 70 } 71 72 public void encode(IoSession session, Object message, 73 ProtocolEncoderOutput out) throws Exception { 74 if (!(message instanceof Serializable )) { 75 throw new NotSerializableException (); 76 } 77 78 ByteBuffer buf = ByteBuffer.allocate(64); 79 buf.setAutoExpand(true); 80 buf.putObject(message); 81 82 int objectSize = buf.position() - 4; 83 if (objectSize > maxObjectSize) { 84 buf.release(); 85 throw new IllegalArgumentException ( 86 "The encoded object is too big: " + objectSize + " (> " 87 + maxObjectSize + ')'); 88 } 89 90 buf.flip(); 91 out.write(buf); 92 } 93 } 94 | Popular Tags |