public @Override void write(java.io.Writer w, final Object inst) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); XMLEncoder e = new XMLEncoder(out); e.setExceptionListener(new ExceptionListener() { public @Override void exceptionThrown(Exception x) { Logger.getLogger(XMLBeanConvertor.class.getName()).log(Level.INFO, "Problem writing " + inst, x); } }); ClassLoader ccl = Thread.currentThread().getContextClassLoader(); try { // XXX would inst.getClass().getClassLoader() be more appropriate? ClassLoader ccl2 = Lookup.getDefault().lookup(ClassLoader.class); if (ccl2 != null) { Thread.currentThread().setContextClassLoader(ccl2); } e.writeObject(inst); } finally { Thread.currentThread().setContextClassLoader(ccl); } e.close(); String data = new String(out.toByteArray(), "UTF-8"); data = data.replaceFirst("<java", "<!DOCTYPE xmlbeans PUBLIC \"-//NetBeans//DTD XML beans 1.0//EN\" \"http://www.netbeans.org/dtds/xml-beans-1_0.dtd\">\n<java"); w.write(data); }
/** * Sets up the XMLEnconder. */ public XMLEncoder getXMLEncoder(OutputStream out) { XMLEncoder e = new XMLEncoder(out); e.setExceptionListener(new ExceptionListener() { public void exceptionThrown(Exception e1) { logger.error("", e1); } }); e.setPersistenceDelegate(BeanUser.class, new DefaultPersistenceDelegate(new String[] { "name" })); e.setPersistenceDelegate(Key.class, new DefaultPersistenceDelegate( new String[] { "owner", "key" })); e.setPersistenceDelegate(HostMask.class, new DefaultPersistenceDelegate(new String[] { "mask" })); return e; }
/** Evaluates the attributes and creates a Context instance. * If the creation of the Context instance fails the ElementHandler * is marked as failed which may affect the parent handler other. * * @param attributes Attributes of the XML tag. */ public final void start(Attributes attributes, ExceptionListener exceptionListener) { try { // lets the subclass create the appropriate Context instance context = startElement(attributes, exceptionListener); } catch (AssemblyException pe) { Throwable t = pe.getCause(); if (t instanceof Exception) exceptionListener.exceptionThrown((Exception) t); else throw new InternalError("Unexpected Throwable type in AssemblerException. Please file a bug report."); notifyContextFailed(); return; } }
protected final Context startElement(Attributes attributes, ExceptionListener exceptionListener) throws AssemblyException { // note: simple elements should not have any attributes. We inform // the user of this syntactical but uncritical problem by sending // an IllegalArgumentException for each unneccessary attribute int size = attributes.getLength(); for (int i = 0; i < size; i++) { String attributeName = attributes.getQName(i); Exception e = new IllegalArgumentException( "Unneccessary attribute '" + attributeName + "' discarded."); exceptionListener.exceptionThrown(e); } return context = new ObjectContext(); }
/** * Serialize all the EventData items into an XML representation. * * @param map the Map to transform * @return an XML String containing all the EventDAta items. */ public static String toXML(Map<String, Object> map) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { XMLEncoder encoder = new XMLEncoder(baos); encoder.setExceptionListener(new ExceptionListener() { public void exceptionThrown(Exception exception) { exception.printStackTrace(); } }); encoder.writeObject(map); encoder.close(); return baos.toString(); } catch (Exception e) { e.printStackTrace(); return null; } }
/** * プラグインブラックリストの読み込み * * @param listener ExceptionListener * @return プラグインブラックリスト */ private Set<String> getBlackList(ExceptionListener listener) { Set<String> blackList = Collections.emptySet(); InputStream in = Launcher.class.getClassLoader().getResourceAsStream("logbook/plugin-black-list"); //$NON-NLS-1$ if (in != null) { try (BufferedReader r = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8))) { blackList = r.lines() .filter(l -> l.length() >= 64) .map(l -> l.substring(0, 64)) .collect(Collectors.toSet()); } catch (IOException e) { listener.exceptionThrown(e); } } return blackList; }
/** * Writes the objet and CLOSES the stream. Uses the persistence delegate registered in this class. * * @param os The stream to write to. Will be closed. * @param o The object to be serialized. * @param listener The listener to recieve the exeptions if there are any. If <code>null</code> not used. */ void writeXMLObject(final OutputStream os, final Object o, final ExceptionListener listener) { final ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(LayoutUtilCommon.class.getClassLoader()); final XMLEncoder encoder = new XMLEncoder(os); if (listener != null) { encoder.setExceptionListener(listener); } encoder.writeObject(o); encoder.close(); // Must be closed to write. Thread.currentThread().setContextClassLoader(oldClassLoader); }
/** * Writes an object to XML. * * @param out The boject out to write to. Will not be closed. * @param o The object to write. */ public synchronized void writeAsXML(final ObjectOutput out, final Object o) throws IOException { if (writeOutputStream == null) { writeOutputStream = new ByteArrayOutputStream(16384); } writeOutputStream.reset(); writeXMLObject(writeOutputStream, o, new ExceptionListener() { @Override public void exceptionThrown(final Exception e) { LOGGER.error(e); } }); final byte[] buf = writeOutputStream.toByteArray(); out.writeInt(buf.length); out.write(buf); }
public void exceptionThrown(Exception ex) { Object[] ls = listeners.toArray(); if (ls.length == 0) Logger.getLogger(ExceptionListenerSupport.class.getName()).log(Level.SEVERE, null, ex); else { boolean informed = false; for (Object o : ls) if (o instanceof ExceptionListener) { ((ExceptionListener) o).exceptionThrown(ex); informed = true; } else Logger.getLogger(ExceptionListenerSupport.class.getName()).warning(String.format("Not an instance of exception listener: %s", o.toString())); if (!informed) Logger.getLogger(ExceptionListenerSupport.class.getName()).log(Level.SEVERE, null, ex); } }
public void testInitialize_NoGetter() throws Exception { MockEncoder enc = new MockEncoder(); MockPersistenceDelegate pd = new MockPersistenceDelegate(); MockNoGetterBean b = new MockNoGetterBean(); b.setName("myName"); enc.setExceptionListener(new ExceptionListener() { public void exceptionThrown(Exception e) { CallVerificationStack.getInstance().push(e); } }); enc.writeObject(b); CallVerificationStack.getInstance().clear(); MockNoGetterBean b2 = (MockNoGetterBean) enc.get(b); b2.setName("yourName"); b2.setLabel("hehe"); pd.initialize(MockNoGetterBean.class, b, b2, enc); assertTrue(CallVerificationStack.getInstance().empty()); }
public void testInitialize_NullClass() { MockPersistenceDelegate pd = new MockPersistenceDelegate(); Encoder enc = new Encoder(); Object o1 = new Object(); Object o2 = new Object(); // enc.setPersistenceDelegate(MockFooStop.class, // new MockPersistenceDelegate()); try { enc.setExceptionListener(new ExceptionListener() { public void exceptionThrown(Exception e) { CallVerificationStack.getInstance().push(e); } }); pd.initialize(null, o1, o2, enc); fail("Should throw NullPointerException!"); } catch (NullPointerException ex) { // expected } assertTrue(CallVerificationStack.getInstance().empty()); }
public void testInitialize_NullInstances() { MockPersistenceDelegate pd = new MockPersistenceDelegate(); Encoder enc = new Encoder(); MockFoo b = new MockFoo(); b.setName("myName"); // enc.setPersistenceDelegate(MockFooStop.class, // new MockPersistenceDelegate()); enc.setExceptionListener(new ExceptionListener() { public void exceptionThrown(Exception e) { CallVerificationStack.getInstance().push(e); } }); try { pd.initialize(MockFoo.class, null, b, enc); fail("Should throw NullPointerException!"); } catch (NullPointerException ex) { // expected } assertTrue(CallVerificationStack.getInstance().empty()); pd.initialize(MockFoo.class, b, null, enc); assertFalse(CallVerificationStack.getInstance().empty()); }
public void test_Constructor_Normal() throws Exception { XMLDecoder xmlDecoder; xmlDecoder = new XMLDecoder(new ByteArrayInputStream(xml123bytes)); assertEquals(null, xmlDecoder.getOwner()); final Vector<Exception> exceptions = new Vector<Exception>(); ExceptionListener el = new ExceptionListener() { public void exceptionThrown(Exception e) { exceptions.addElement(e); } }; xmlDecoder = new XMLDecoder(new ByteArrayInputStream(xml123bytes), this, el); assertEquals(el, xmlDecoder.getExceptionListener()); assertEquals(this, xmlDecoder.getOwner()); }
public void testReadObject_Repeated() throws Exception { final Vector<Exception> exceptionList = new Vector<Exception>(); final ExceptionListener exceptionListener = new ExceptionListener() { public void exceptionThrown(Exception e) { exceptionList.addElement(e); } }; XMLDecoder xmlDecoder = new XMLDecoder(new ByteArrayInputStream( xml123bytes)); xmlDecoder.setExceptionListener(exceptionListener); assertEquals(new Integer(1), xmlDecoder.readObject()); assertEquals(new Integer(2), xmlDecoder.readObject()); assertEquals(new Integer(3), xmlDecoder.readObject()); xmlDecoder.close(); assertEquals(0, exceptionList.size()); }
public void testSetExceptionListener_Called() throws Exception { class MockExceptionListener implements ExceptionListener { private boolean isCalled = false; public void exceptionThrown(Exception e) { isCalled = true; } public boolean isCalled() { return isCalled; } } XMLDecoder xmlDecoder = new XMLDecoder(new ByteArrayInputStream( "<java><string/>".getBytes("UTF-8"))); MockExceptionListener mockListener = new MockExceptionListener(); xmlDecoder.setExceptionListener(mockListener); assertFalse(mockListener.isCalled()); // Real Parsing should occur in method of ReadObject rather constructor. assertNotNull(xmlDecoder.readObject()); assertTrue(mockListener.isCalled()); }
/** * Serializes the TreeMap. * * @throws IOException */ public void commit() throws IOException { saveClassLoader(); XMLEncoder enc = null; try { switchClassLoaders(); enc = new XMLEncoder(new SafeFileOutputStream(nukeFile)); enc.setExceptionListener(new ExceptionListener() { public void exceptionThrown(Exception e) { logger.error(e, e); } }); enc.setPersistenceDelegate(LRUMap.class, new DefaultPersistenceDelegate(new String[] { "maxSize" } )); enc.writeObject(_nukes); } catch (IOException ex) { throw new IOException(ex.getMessage()); } finally { if (enc != null) enc.close(); } setPreviousClassLoader(); }
/** * @throws InterruptedException * @throws KeeperException */ protected void registerNode() throws KeeperException, InterruptedException { // register and watch node ID Util.checkThenCreateZooNode(path + "/" + id_path,null,Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT,zoo); zoo.getChildren(path + "/" + id_path, true); // start watching byte[] b = (addr.getHostString() + ";" + addr.getPort()).getBytes(); // store the SocketAddress // special case for EC2 inter-region ring; publish public IP String public_ip = System.getenv("EC2"); if(public_ip != null){ b = (public_ip + ";" + addr.getPort()).getBytes(); // store the SocketAddress logger.warn("Publish env(EC2) in zookeeper: " + new String(b) + "!"); } Util.checkThenCreateZooNode(path + "/" + id_path + "/" + nodeID,b,Ids.OPEN_ACL_UNSAFE,CreateMode.EPHEMERAL, zoo, new ExceptionListener() { @Override public void exceptionThrown(Exception e) { logger.error("Node ID " + nodeID + " in topology " + topologyID + " already registred!"); } }); }
public static void main(String[] args) throws Exception { StringBuilder sb = new StringBuilder(256); sb.append("file:"); sb.append(System.getProperty("test.src", ".")); sb.append(File.separatorChar); sb.append("test.jar"); URL[] url = {new URL(sb.toString())}; URLClassLoader cl = new URLClassLoader(url); Class type = cl.loadClass("test.Test"); if (type == null) { throw new Error("could not find class test.Test"); } InputStream stream = new ByteArrayInputStream(DATA.getBytes()); ExceptionListener el = new ExceptionListener() { public void exceptionThrown(Exception exception) { throw new Error("unexpected exception", exception); } }; XMLDecoder decoder = new XMLDecoder(stream, null, el, cl); Object object = decoder.readObject(); decoder.close(); if (!type.equals(object.getClass())) { throw new Error("unexpected " + object.getClass()); } }
public Object loadLocal() throws FileNotFoundException { Window frame = getFrame(); // Choose the file to load. JFileChooser fileChooser = new JFileChooser( _directoryName ); fileChooser.setDialogTitle( "Load File" ); int rval = fileChooser.showOpenDialog( frame ); _directoryName = fileChooser.getCurrentDirectory().getAbsolutePath(); File selectedFile = fileChooser.getSelectedFile(); if( rval == JFileChooser.CANCEL_OPTION || selectedFile == null ) { return null; } // XML decode directly from the file. Object object = null; String filename = selectedFile.getAbsolutePath(); FileInputStream fis = new FileInputStream( filename ); BufferedInputStream bis = new BufferedInputStream( fis ); XMLDecoder decoder = new XMLDecoder( bis ); decoder.setExceptionListener( new ExceptionListener() { private int errors = 0; // Report the first recoverable exception. public void exceptionThrown( Exception e ) { if( errors == 0 ) { showError( QWIResources.getString( "Load.error.decode" ), e ); errors++; } } } ); object = decoder.readObject(); decoder.close(); return object; }
private void saveJNLP( Serializable object ) throws Exception { final JFrame frame = PhetApplication.getInstance().getPhetFrame(); // XML encode into a byte output stream. ByteArrayOutputStream baos = new ByteArrayOutputStream(); XMLEncoder encoder = new XMLEncoder( baos ); encoder.setExceptionListener( new ExceptionListener() { private int errors = 0; // Report the first recoverable exception. public void exceptionThrown( Exception e ) { if( errors == 0 ) { showError( QWIResources.getString( "Save.error.encode" ), e ); errors++; } } } ); encoder.writeObject( object ); encoder.close(); if( object == null ) { throw new Exception( QWIResources.getString( "XML encoding failed" ) ); } // Convert to a byte input stream. ByteArrayInputStream inputStream = new ByteArrayInputStream( baos.toByteArray() ); // Get the JNLP service for saving files. FileSaveService fss = (FileSaveService)ServiceManager.lookup( "javax.jnlp.FileSaveService" ); if( fss == null ) { throw new UnavailableServiceException( "JNLP FileSaveService is unavailable" ); } // Save the configuration to a file. FileContents fc = fss.saveFileDialog( null, null, inputStream, _directoryName ); if( fc != null ) { _directoryName = getDirectoryName( fc.getName() ); } }
private Object loadJNLP() throws UnavailableServiceException, IOException { Window frame = getFrame(); // Get the JNLP service for opening files. FileOpenService fos = (FileOpenService)ServiceManager.lookup( "javax.jnlp.FileOpenService" ); if( fos == null ) { throw new UnavailableServiceException( "JNLP FileOpenService is unavailable" ); } // Read the configuration from a file. FileContents fc = fos.openFileDialog( _directoryName, null ); if( fc == null ) { return null; } _directoryName = getDirectoryName( fc.getName() ); // Convert the FileContents to an input stream. InputStream inputStream = fc.getInputStream(); // XML-decode the input stream. Object object = null; XMLDecoder decoder = new XMLDecoder( inputStream ); decoder.setExceptionListener( new ExceptionListener() { private int errors = 0; // Report the first recoverable exception. public void exceptionThrown( Exception e ) { if( errors == 0 ) { showError( QWIResources.getString( "Load.error.decode" ), e ); errors++; } } } ); object = decoder.readObject(); decoder.close(); return object; }