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); }
private static void setPersistenceDelegates(XMLEncoder encoder, Class<?>[] types) { if (types != null && types.length > 0) { PersistenceDelegate persistenceDelegate = new EnumPersistenceDelegate(); for (int i = 0; i < types.length; i++) { encoder.setPersistenceDelegate(types[i], persistenceDelegate); } } // Handle "BiGDecimal" manually (has no default constructor) encoder.setPersistenceDelegate(BigDecimal.class, new BigDecimalPersistenceDelegate()); encoder.setPersistenceDelegate(byte[].class, new ByteArrayPersistenceDelegate()); encoder.setPersistenceDelegate(UUID.class, new UUIDDelegate()); }
/** * Get the price model data for the given context and locales * * @return the price model data as an XML encoded list of strings */ @GET @Produces(MediaType.TEXT_PLAIN) public Response getPriceModel() { FileBilling fb = new FileBilling(); splitParametersToList(contextKeys); splitParametersToList(contextValues); List<String> priceModelContent = fb.getPriceModel(contextKeys, contextValues, locales); ByteArrayOutputStream bos = new ByteArrayOutputStream(); try (XMLEncoder xmlEncoder = new XMLEncoder(bos)) { xmlEncoder.writeObject(priceModelContent); } String serializedList = ""; try { serializedList = bos.toString(StandardCharsets.UTF_8.name()); } catch (UnsupportedEncodingException e) { } return Response.ok(serializedList).build(); }
private static void prepareTestData(final int amount) { final int actualYear = new GregorianCalendar().get(Calendar.YEAR); final Collection<Customer> customers = new LinkedList<>(); for (int i = 1; i <= amount; i++) { final Calendar birthday = new GregorianCalendar(); birthday.set(Calendar.YEAR, random(actualYear - 100, actualYear)); birthday.set(Calendar.DAY_OF_YEAR, random(1, birthday.getActualMaximum(Calendar.DAY_OF_YEAR))); final Customer customer = new Customer(); customer.setId(i); customer.setName(UUID.randomUUID().toString().replaceAll("[^a-z]", "")); customer.setBirthday(birthday); customer.setTransactions(random(0, 100)); customers.add(customer); } try (final XMLEncoder encoder = new XMLEncoder(new FileOutputStream(CustomerReportJobConfig.XML_FILE))) { encoder.writeObject(customers); } catch (final FileNotFoundException e) { log.error(e.getMessage(), e); System.exit(-1); } }
/** * 把java的可序列化的对象(实现Serializable接口)序列化保存到XML文件里面,如果想一次保存多个可序列化对象请用集合进行封装 * 保存时将会用现在的对象原来的XML文件内容 * @param obj 要序列化的可序列化的对象 * @param fileName 带完全的保存路径的文件名 * @throws FileNotFoundException 指定位置的文件不存在 * @throws IOException 输出时发生异常 * @throws Exception 其他运行时异常 */ public static void objectXmlEncoder(Object obj,String fileName) throws FileNotFoundException,IOException,Exception { //创建输出文件 File fo = new File(fileName); //文件不存在,就创建该文件 if(!fo.exists()) { //先创建文件的目录 String path = fileName.substring(0,fileName.lastIndexOf('.')); File pFile = new File(path); pFile.mkdirs(); } //创建文件输出流 FileOutputStream fos = new FileOutputStream(fo); //创建XML文件对象输出类实例 XMLEncoder encoder = new XMLEncoder(fos); //对象序列化输出到XML文件 encoder.writeObject(obj); encoder.flush(); //关闭序列化工具 encoder.close(); //关闭输出流 fos.close(); }
public static void saveAnObjectXML(Object obj, String path) { try { // Serialize object into XML XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream( new FileOutputStream(path))); encoder.writeObject(obj); encoder.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } }
public static void main(String[] args) { XMLEncoder encoder = new XMLEncoder(System.out); encoder.setPersistenceDelegate(Test4646747.class, new MyPersistenceDelegate()); // WARNING: This can eat up a lot of memory Object[] obs = new Object[10000]; while (obs != null) { try { obs = new Object[obs.length + obs.length / 3]; } catch (OutOfMemoryError error) { obs = null; } } PersistenceDelegate pd = encoder.getPersistenceDelegate(Test4646747.class); if (!(pd instanceof MyPersistenceDelegate)) throw new Error("persistence delegate has been lost"); }
public void run() { // run thread a few time // object stays the same but NullPointerException appears randomly // on dual proccessor a lock is generated for (int i = 0; i < THREAD_LENGTH; i++) { // create XMLEncoder to ByteArrayOutputStream // this is to exclude file locking problems XMLEncoder encoder = new XMLEncoder(new ByteArrayOutputStream()); encoder.setExceptionListener(this); // write the object // will see randomly null pointer exceptions // a bug as object is same through different encode phases encoder.writeObject(this.object); //close encoder encoder.close(); } System.out.println(Thread.currentThread().getName() + " is finished"); }
static void test(AbstractTest object) { ByteArrayOutputStream output = new ByteArrayOutputStream(); XMLEncoder encoder = new XMLEncoder(output); encoder.setPersistenceDelegate( object.getClass(), new DefaultPersistenceDelegate(new String[] {"value"})); encoder.writeObject(object); encoder.close(); System.out.print(output); ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray()); XMLDecoder decoder = new XMLDecoder(input); AbstractTest result = (AbstractTest) decoder.readObject(); decoder.close(); if (object.getValue() != result.getValue()) throw new Error("Should be " + object); }
/** * This code abstracted because it relies on java.beans.* which is not always available * e.g. on Android */ @Override public void doSave( OutputStream out, Map usersMap ) { UserManagerConfig config = new UserManagerConfig(); List users = new ArrayList( usersMap.values() ); config.setUsers(users); XMLEncoder encoder = new XMLEncoder( new BufferedOutputStream( out ) ); encoder.writeObject(config); encoder.close(); }
public static byte[] objectToXml(Object obj,ClassLoader cl){ if(cl == null){ return objectToXml(obj); } ByteArrayOutputStream bos = new ByteArrayOutputStream(); XMLEncoder xml = new XMLEncoder(bos); //HACK ClassLoader oldLoader = Thread.currentThread().getContextClassLoader(); if (cl != oldLoader && cl != null){ try{ Thread.currentThread().setContextClassLoader(cl); xml.writeObject(obj); }catch(Exception e){e.printStackTrace();} finally { Thread.currentThread().setContextClassLoader(oldLoader); } }else{ xml.writeObject(obj); } xml.close(); return bos.toByteArray(); }
/** * To xml. * * @param obj * the obj * @return the string */ // //////////////////////////////////////////////////////////////////// public static String toXml(final Object obj) { final ByteArrayOutputStream out = new ByteArrayOutputStream(); // XStream x = createXStream(); // String xml = x.toXML(obj); // return xml; final XMLEncoder e = new XMLEncoder(out); e.setExceptionListener(new XmlEncoderExceptionListener()); // e.setPersistenceDelegate(Object.class, new MyPersistenceDelegate()); e.writeObject(obj); e.close(); return out.toString(); // return null; }
private void saveWorkspaceToFile(File file) { try { FileOutputStream fos = new FileOutputStream(file); XMLEncoder encoder = new XMLEncoder(fos); encoder.writeObject(config); encoder.close(); recentMenu.addRecentWorkspace(file); } catch (FileNotFoundException e) { GUIHelper.showMessage(this, "An error occured while saving to " + file.getPath(), JOptionPane.ERROR_MESSAGE); } GUIHelper.showMessage(this, "Workspace saved to " + file.getPath(), JOptionPane.INFORMATION_MESSAGE); actionSaveWorkspaceAs.setEnabled(true); }
public static void save(File fout, SkeletonBean obj) throws IOException { FileOutputStream fos = new FileOutputStream(fout); try { XMLEncoder enc = new XMLEncoder(fos); enc.writeObject(obj); enc.close(); } catch (Exception ex) { throw new IOException(ex.toString()); } finally { fos.close(); } }
/** * Configure the serialization of the File. */ @Override protected void setupXML(XMLEncoder enc) { super.setupXML(enc); PropertyDescriptor[] pdArr; try { pdArr = Introspector.getBeanInfo(VirtualFileSystemFile.class) .getPropertyDescriptors(); } catch (IntrospectionException e) { logger.error("I don't know what to do here", e); throw new RuntimeException(e); } for (PropertyDescriptor pd : pdArr) { // logger.debug("PropertyDescriptor - VirtualFileSystemFile - " // + pd.getDisplayName()); if (transientListFile.contains(pd.getName())) { pd.setValue("transient", Boolean.TRUE); } } // needed to create a VFSFile object during unserialization enc.setPersistenceDelegate(VirtualFileSystemFile.class, new DefaultPersistenceDelegate(new String[] { "username", "group", "size", "slaves" })); }
@Override protected void setupXML(XMLEncoder enc) { super.setupXML(enc); PropertyDescriptor[] pdArr; try { pdArr = Introspector.getBeanInfo(VirtualFileSystemLink.class) .getPropertyDescriptors(); } catch (IntrospectionException e) { logger.error("I don't know what to do here", e); throw new RuntimeException(e); } for (int x = 0; x < pdArr.length; x++) { // logger.debug("PropertyDescriptor - VirtualFileSystemLink - " // + pdArr[x].getDisplayName()); if (transientListLink.contains(pdArr[x].getName())) { pdArr[x].setValue("transient", Boolean.TRUE); } } enc.setPersistenceDelegate(VirtualFileSystemLink.class, new DefaultPersistenceDelegate(new String[] { "username", "group", "linkPath" })); }
public void writeToDisk() throws IOException { if (_purged) return; XMLEncoder out = null; try { out = _um.getXMLEncoder(new SafeFileOutputStream(_um .getUserFile(getName()))); ClassLoader prevCL = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(CommonPluginUtils.getClassLoaderForObject(this)); out.writeObject(this); Thread.currentThread().setContextClassLoader(prevCL); logger.debug("Wrote userfile for " + this.getName()); } finally { if (out != null) out.close(); } }
/** * 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; }
/** * 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; } }
@Override protected void initialize(Class type, Object oldInstance, Object newInstance, Encoder out) { // p("image painter delegate called"); super.initialize(type, oldInstance, newInstance, out); //p("old instance = " + oldInstance); //p("owner = " + ((XMLEncoder)out).getOwner()); PersistenceOwner owner = (PersistenceOwner)((XMLEncoder)out).getOwner(); ImagePainter ip = (ImagePainter)oldInstance; // p("need to convert string: " + ip.getImageString()); // String s = owner.toXMLURL(ip.getImageString()); // p("converted to: " + s); //out.writeExpression(new Expression(oldInstance,owner,"fromXMLURL",new Object[]{ip.getImageString()})); //out.writeStatement(new Statement(owner,"fromXMLURL",new Object[]{ip.getImageString()})); //out.writeStatement(new Statement(oldInstance,"setImageString",new Object[]{ //new Expression(oldInstance,owner,"fromXMLURL",new Object[]{ip.getImageString()}) //})); out.writeStatement(new Statement(oldInstance,"setResolver",new Object[]{owner})); // out.writeStatement(new Statement(oldInstance,"setImageString",new Object[]{s})); }
/** * @param original * @return */ public T serializeAndDeserialize(T original) { java.io.ByteArrayOutputStream out = new DebuggingByteArrayOutputStream(4096); XMLEncoder encoder = new XMLEncoder(out); encoder.writeObject(original); encoder.close(); dumpByteArray(out.toByteArray()); java.io.ByteArrayInputStream in = new java.io.ByteArrayInputStream(out.toByteArray()); XMLDecoder decoder = new XMLDecoder(in); T deserialized = (T)decoder.readObject(); decoder.close(); return deserialized; }
public void testArtifactRepositoryImplSerialization() throws MalformedURLException { ArtifactSource as = new ArtifactSourceImpl( WellKnownOID.VA_DOCUMENT.getCanonicalValue(), "42", new URL[]{new URL("http://localhost/app/file")}, new URL[]{new URL("http://localhost/app/file")} ); ArtifactSourceMemento asm = as.getMemento(); ByteArrayOutputStream out = new ByteArrayOutputStream(); XMLEncoder encoder = new XMLEncoder( out ); encoder.writeObject(asm); encoder.close(); System.out.println( new String(out.toByteArray()) ); XMLDecoder decoder = new XMLDecoder(new ByteArrayInputStream(out.toByteArray())); ArtifactSourceMemento asm2 = (ArtifactSourceMemento)decoder.readObject(); assertEquals(asm, asm2); }
public void testSiteImplSerialization() throws MalformedURLException { ArtifactSource as = new SiteImpl( "660", "Name", "Nm", "localhost", 9300, "localhist", 8080, "42" ); ArtifactSourceMemento asm = as.getMemento(); ByteArrayOutputStream out = new ByteArrayOutputStream(); XMLEncoder encoder = new XMLEncoder( out ); encoder.writeObject(asm); encoder.close(); System.out.println( new String(out.toByteArray()) ); XMLDecoder decoder = new XMLDecoder(new ByteArrayInputStream(out.toByteArray())); ArtifactSourceMemento asm2 = (ArtifactSourceMemento)decoder.readObject(); assertEquals(asm, asm2); }
/** * Saves the state of the UserSettings to an XML file. * * @param xmlFileName * Path to saved object * @return if the settings could be saved */ public boolean saveXmlEncodedBean(String xmlFileName) { boolean succeeded = false; try (XMLEncoder encoder = new XMLEncoder( new BufferedOutputStream(new FileOutputStream(xmlFileName)))) { encoder.writeObject(this); succeeded = true; } catch (FileNotFoundException e) { System.err.println("Failed to write file " + xmlFileName + "."); } return succeeded; }