Example usage for java.beans XMLEncoder XMLEncoder

List of usage examples for java.beans XMLEncoder XMLEncoder

Introduction

In this page you can find the example usage for java.beans XMLEncoder XMLEncoder.

Prototype

public XMLEncoder(OutputStream out) 

Source Link

Document

Creates a new XML encoder to write out JavaBeans to the stream out using an XML encoding.

Usage

From source file:org.cesecore.util.HashMapTest.java

@SuppressWarnings("rawtypes")
@Test/*from w  w w  .  j a va 2 s .  c  o m*/
public void testHashMapStrangeCharsSafe() throws Exception {
    HashMap<String, Comparable> h = new HashMap<String, Comparable>();
    h.put("foo0", Boolean.FALSE);
    h.put("foo1", "\0001\0002fooString");
    h.put("foo2", Integer.valueOf(2));
    h.put("foo3", Boolean.TRUE);
    h.put("foo4", "");
    HashMap<Object, Object> a = new Base64PutHashMap();
    a.putAll(h);

    // Write to XML
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    XMLEncoder encoder = new XMLEncoder(baos);
    encoder.writeObject(a);
    encoder.close();
    String data = baos.toString("UTF8");
    //log.error(data);

    try {
        XMLDecoder decoder = new XMLDecoder(new ByteArrayInputStream(data.getBytes("UTF8")));
        HashMap<?, ?> b = (HashMap<?, ?>) decoder.readObject();
        decoder.close();
        @SuppressWarnings("unchecked")
        HashMap<Object, Object> c = new Base64GetHashMap(b);
        assertEquals(((Boolean) c.get("foo0")).booleanValue(), false);
        assertEquals(((Boolean) c.get("foo3")).booleanValue(), true);
        assertEquals(((String) c.get("foo1")), "\0001\0002fooString");
        assertEquals(((String) c.get("foo4")), "");
        assertEquals(((Integer) c.get("foo2")).intValue(), 2);

    } catch (ClassCastException e) {
        assertTrue(false);
    }
}

From source file:com.clustercontrol.plugin.impl.AsyncTask.java

/**
 * SerializableXML???/*from   w  ww.j  a  v  a 2s. c  o m*/
 * @param obj Serializable
 * @return ??XML
 * @throws IOException
 */
public static String encodeXML(Serializable obj) throws IOException {
    ByteArrayOutputStream baos = null;
    XMLEncoder enc = null;
    String xml = null;

    try {
        baos = new ByteArrayOutputStream();
        enc = new XMLEncoder(baos);
        enc.writeObject(obj);
        xml = baos.toString("UTF-8");
    } catch (UnsupportedEncodingException e) {
        log.warn(e);
    } finally {
        if (enc != null) {
            enc.close();
        }
        if (baos != null) {
            baos.close();
        }
    }

    return xml;
}

From source file:de.willuhn.jameica.hbci.io.csv.ProfileUtil.java

/**
 * Speichert die Profile.//from  w  w  w.  j av  a  2s . c  o  m
 * @param format das Format.
 * @param profiles die zu speichernden Profile.
 */
public static void store(Format format, List<Profile> profiles) {
    if (format == null) {
        Application.getMessagingFactory().sendMessage(
                new StatusBarMessage(i18n.tr("Kein Format ausgewhlt"), StatusBarMessage.TYPE_ERROR));
        return;
    }

    if (profiles == null) {
        Application.getMessagingFactory().sendMessage(
                new StatusBarMessage(i18n.tr("Keine Profile angegeben"), StatusBarMessage.TYPE_ERROR));
        return;
    }

    // 2. Mal schauen, ob wir ein gespeichertes Profil fuer das Format haben
    File dir = new File(Application.getPluginLoader().getPlugin(HBCI.class).getResources().getWorkPath(),
            "csv");
    if (!dir.exists()) {
        Logger.info("creating dir: " + dir);
        if (!dir.mkdirs()) {
            Application.getMessagingFactory()
                    .sendMessage(new StatusBarMessage(
                            i18n.tr("Ordner {0} kann nicht erstellt werden", dir.getAbsolutePath()),
                            StatusBarMessage.TYPE_ERROR));
            return;
        }
    }

    File file = new File(dir, format.getClass().getName() + ".xml");

    Logger.info("writing csv profile " + file);
    XMLEncoder encoder = null;
    try {
        encoder = new XMLEncoder(new BufferedOutputStream(new FileOutputStream(file)));
        encoder.setExceptionListener(new ExceptionListener() {
            public void exceptionThrown(Exception e) {
                throw new RuntimeException(e);
            }
        });

        for (Profile p : profiles) {
            // Das System-Profil wird nicht mit gespeichert
            if (p.isSystem())
                continue;

            // Ebenso Profile ohne Namen.
            if (StringUtils.trimToNull(p.getName()) == null)
                continue;

            encoder.writeObject(p);
        }
    } catch (Exception e) {
        Logger.error("unable to store profile " + file, e);
    } finally {
        if (encoder != null) {
            try {
                encoder.close();
            } catch (Exception e) {
                /* useless */}
        }
    }
}

From source file:org.cesecore.util.HashMapTest.java

@SuppressWarnings("rawtypes")
@Test/*from  w w  w.j a va 2 s  . c  o m*/
public void testHashMapNormalCharsSafe() throws Exception {
    HashMap<String, Comparable> h = new HashMap<String, Comparable>();
    h.put("foo0", Boolean.FALSE);
    h.put("foo1", "fooString");
    h.put("foo2", Integer.valueOf(2));
    h.put("foo3", Boolean.TRUE);
    h.put("foo4", "");
    HashMap<Object, Object> a = new Base64PutHashMap();
    a.putAll(h);

    // Write to XML
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    XMLEncoder encoder = new XMLEncoder(baos);
    encoder.writeObject(a);
    encoder.close();
    String data = baos.toString("UTF8");
    //log.error(data);

    try {
        XMLDecoder decoder = new XMLDecoder(new ByteArrayInputStream(data.getBytes("UTF8")));
        HashMap<?, ?> b = (HashMap<?, ?>) decoder.readObject();
        decoder.close();
        @SuppressWarnings("unchecked")
        HashMap<Object, Object> c = new Base64GetHashMap(b);
        assertEquals(((Boolean) c.get("foo0")).booleanValue(), false);
        assertEquals(((Boolean) c.get("foo3")).booleanValue(), true);
        assertEquals(((String) c.get("foo4")), "");
        assertEquals(((String) c.get("foo1")), "fooString");
        assertEquals(((Integer) c.get("foo2")).intValue(), 2);

    } catch (ClassCastException e) {
        assertTrue(false);
    }
}

From source file:net.commerce.zocalo.experiment.config.SessionConfigurationTest.java

private byte[] writeObjToXmlBytes(Object config) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    //        FileOutputStream fos = null;
    //        try {
    //            fos = new FileOutputStream("temp.xml");
    //        } catch (FileNotFoundException e) {
    //            e.printStackTrace();
    //        }/* ww  w .j  a  va  2 s  . c  o m*/
    //        XMLEncoder fenc = new XMLEncoder(fos);
    //        fenc.writeObject(config);
    //        fenc.close();
    XMLEncoder enc = new XMLEncoder(baos);
    enc.writeObject(config);
    enc.close();
    return baos.toByteArray();
}

From source file:lu.lippmann.cdb.graph.GraphUtil.java

/**
 * /*from   w  w w.  j  a  va2s  .co  m*/
 * @param g
 * @return
 */
public static String saveGraphWithOperation(final GraphWithOperations g) {
    final ArrayList<GraphOperation> operations = new ArrayList<GraphOperation>(g.getOperations());
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final XMLEncoder xmlEncoder = new XMLEncoder(baos);
    xmlEncoder.setExceptionListener(new ExceptionListener() {
        public void exceptionThrown(final Exception e) {
            throw new IllegalStateException(e);
        }
    });

    xmlEncoder.writeObject(new GraphTO(g.getId(), operations, g.getUntitledVertexCount(),
            g.getUntitledEdgeCount(), g.getVariables()));
    xmlEncoder.close();
    return baos.toString();
}

From source file:net.chaosserver.timelord.data.XmlDataReaderWriter.java

/**
 * Writes out the timelordData object to the default filename in the
 * user's home directory. Also generates a backup version of the file.
 *
 * @param timelordData the data to write to file
 * @param outputFile the file to output to
 * @throws TimelordDataException indicates an error writing the
 *         data out to file./*from w  w w  . j ava 2 s .co  m*/
 */
public void writeTimelordData(TimelordData timelordData, File outputFile) throws TimelordDataException {
    Calendar yesterday = Calendar.getInstance();
    yesterday.add(Calendar.DAY_OF_YEAR, -1);

    File homeDirectory = new File(System.getProperty("user.home"));

    try {
        FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);

        XMLEncoder xmlEncoder = new XMLEncoder(bufferedOutputStream);
        xmlEncoder.writeObject(timelordData);
        xmlEncoder.close();

        File backupFile = new File(homeDirectory, (DEFAULT_FILENAME + "."
                + startWeekFormat.format(yesterday.getTime()) + DEFAULT_EXTENSION + ".gzip"));
        fileOutputStream = new FileOutputStream(backupFile);
        bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
        GZIPOutputStream zipOutputStream = new GZIPOutputStream(bufferedOutputStream);

        xmlEncoder = new XMLEncoder(zipOutputStream);
        xmlEncoder.writeObject(timelordData);
        xmlEncoder.close();
    } catch (FileNotFoundException e) {
        throw new TimelordDataException("Failed to output", e);
    } catch (IOException e) {
        throw new TimelordDataException("Failed to output", e);
    }
}

From source file:gov.llnl.lc.smt.command.config.SmtConfig.java

public static boolean writeConfigFile(String fileName, Map<String, String> config) {
    boolean success = false;
    logger.info("Writing config to: " + fileName);
    if ((fileName != null) && (config != null)) {
        FileOutputStream fos;/*  ww w  .  ja  va 2s  .  co m*/
        try {
            fos = new FileOutputStream(fileName);
            XMLEncoder xenc = new XMLEncoder(fos);

            // save this file name within the config
            config.put(SmtProperty.SMT_WRITE_CONFIG.getName(), fileName);

            // Write object.
            xenc.writeObject(config);
            xenc.close();
            success = true;
        } catch (FileNotFoundException e) {
            logger.severe("Unable to write to: " + fileName);
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } else {

    }
    return success;
}

From source file:resources.ResourceManager.java

public static void saveLayoutTable(File file, LayoutTableModel tableModel) {
    try {//from ww w . ja  v a  2  s . c o  m
        final XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(new FileOutputStream(file)));
        encoder.writeObject(tableModel.getLayoutTableItemList());
        encoder.close();
    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:com.btisystems.pronx.ems.App.java

private static void saveNotificationRegistry(final String packageName, final NotificationMeta meta) {
    final File notificationRegistryDoc = getNotificationRegistryDocumentName(packageName);
    final File notificationRegistryDir = notificationRegistryDoc.getParentFile();
    if (Files.notExists(notificationRegistryDir.toPath())) {
        notificationRegistryDir.mkdirs();
    }//  www.  j a  v  a 2 s.c  o m
    try (XMLEncoder encoder = new XMLEncoder(
            new BufferedOutputStream(new FileOutputStream(notificationRegistryDoc)))) {
        encoder.writeObject(meta);
        encoder.writeObject(meta);
    } catch (final Exception e) {
        LOG.error("Exception saving Notification Registry: {}", e.getMessage(), e);
    }
}