1 22 package org.jboss.aop.util; 23 24 import java.io.ByteArrayInputStream ; 25 import java.io.ByteArrayOutputStream ; 26 import java.io.IOException ; 27 import java.io.ObjectInput ; 28 import java.io.ObjectOutput ; 29 import java.io.OutputStream ; 30 import java.util.Arrays ; 31 32 40 public class MarshalledValue 41 implements java.io.Externalizable 42 { 43 44 private static final long serialVersionUID = -1527598981234110311L; 45 46 51 private byte[] serializedForm = null; 52 53 56 private int hashCode; 57 private boolean isHashComputed = false; 58 59 private ByteArrayOutputStream baos = null; 60 61 64 public MarshalledValue() 65 { 66 super(); 67 } 68 69 public MarshalledValue(Object obj) throws IOException 70 { 71 baos = new ByteArrayOutputStream (); 72 MarshalledValueOutputStream mvos = new MarshalledValueOutputStream(baos); 73 mvos.writeObject(obj); 74 mvos.flush(); 75 76 serializedForm = baos.toByteArray(); 77 78 isHashComputed = false; 79 } 80 81 public Object get() throws IOException , ClassNotFoundException 82 { 83 if (serializedForm == null) 84 return null; 85 86 ByteArrayInputStream bais = new ByteArrayInputStream (serializedForm); 87 MarshalledValueInputStream mvis = new MarshalledValueInputStream(bais); 88 return mvis.readObject(); 89 } 90 91 public byte[] toByteArray() 92 { 93 return serializedForm; 94 } 95 96 public int size() 97 { 98 int size = serializedForm != null ? serializedForm.length : 0; 99 return size; 100 } 101 102 107 public int hashCode() 108 { 109 if (!isHashComputed) 112 { 113 int hash = 0; 114 for (int i = 0; i < serializedForm.length; i++) 115 { 116 hash = 31 * hash + serializedForm[i]; 117 } 118 119 hashCode = hash; 120 } 121 122 return hashCode; 123 } 124 125 public boolean equals(Object obj) 126 { 127 if( this == obj ) 128 return true; 129 130 boolean equals = false; 131 if( obj instanceof MarshalledValue ) 132 { 133 MarshalledValue mv = (MarshalledValue) obj; 134 if( serializedForm == mv.serializedForm ) 135 { 136 equals = true; 137 } 138 else 139 { 140 equals = Arrays.equals(serializedForm, mv.serializedForm); 141 } 142 } 143 return equals; 144 } 145 146 159 public void readExternal(ObjectInput in) throws IOException , ClassNotFoundException 160 { 161 int length = in.readInt(); 162 serializedForm = null; 163 if( length > 0 ) 164 { 165 serializedForm = new byte[length]; 166 in.readFully(serializedForm); 167 } 168 isHashComputed = false; 169 } 170 171 187 public void writeExternal(ObjectOutput out) throws IOException 188 { 189 out.writeInt(baos.size()); 190 baos.writeTo((OutputStream )out); 191 } 192 } 193 | Popular Tags |