1 7 package java.beans; 8 9 import com.sun.beans.ObjectHandler; 10 11 import java.io.InputStream ; 12 import java.io.IOException ; 13 14 import java.lang.ref.Reference ; 15 import java.lang.ref.WeakReference ; 16 17 import org.xml.sax.SAXException ; 18 19 import javax.xml.parsers.SAXParserFactory ; 20 import javax.xml.parsers.ParserConfigurationException ; 21 import javax.xml.parsers.SAXParser ; 22 23 51 public class XMLDecoder { 52 private InputStream in; 53 private Object owner; 54 private ExceptionListener exceptionListener; 55 private ObjectHandler handler; 56 private Reference clref; 57 58 66 public XMLDecoder(InputStream in) { 67 this(in, null); 68 } 69 70 78 public XMLDecoder(InputStream in, Object owner) { 79 this(in, owner, null); 80 } 81 82 91 public XMLDecoder(InputStream in, Object owner, ExceptionListener exceptionListener) { 92 this(in, owner, exceptionListener, null); 93 } 94 95 110 public XMLDecoder(InputStream in, Object owner, 111 ExceptionListener exceptionListener, ClassLoader cl) { 112 this.in = in; 113 setOwner(owner); 114 setExceptionListener(exceptionListener); 115 setClassLoader(cl); 116 } 117 118 119 125 private void setClassLoader(ClassLoader cl) { 126 if (cl != null) { 127 this.clref = new WeakReference (cl); 128 } 129 } 130 131 137 private ClassLoader getClassLoader() { 138 if (clref != null) { 139 return (ClassLoader )clref.get(); 140 } 141 return null; 142 } 143 144 148 public void close() { 149 if (in != null) { 150 try { 151 in.close(); 152 } 153 catch (IOException e) { 154 getExceptionListener().exceptionThrown(e); 155 } 156 } 157 } 158 159 169 public void setExceptionListener(ExceptionListener exceptionListener) { 170 this.exceptionListener = exceptionListener; 171 } 172 173 181 public ExceptionListener getExceptionListener() { 182 return (exceptionListener != null) ? exceptionListener : 183 Statement.defaultExceptionListener; 184 } 185 186 196 public Object readObject() { 197 if (in == null) { 198 return null; 199 } 200 if (handler == null) { 201 SAXParserFactory factory = SAXParserFactory.newInstance(); 202 try { 203 SAXParser saxParser = factory.newSAXParser(); 204 handler = new ObjectHandler(this, getClassLoader()); 205 saxParser.parse(in, handler); 206 } 207 catch (ParserConfigurationException e) { 208 getExceptionListener().exceptionThrown(e); 209 } 210 catch (SAXException se) { 211 Exception e = se.getException(); 212 getExceptionListener().exceptionThrown((e == null) ? se : e); 213 } 214 catch (IOException ioe) { 215 getExceptionListener().exceptionThrown(ioe); 216 } 217 } 218 return handler.dequeueResult(); 219 } 220 221 228 public void setOwner(Object owner) { 229 this.owner = owner; 230 } 231 232 239 public Object getOwner() { 240 return owner; 241 } 242 } 243 | Popular Tags |