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.settings4j.objectresolver.JavaXMLBeansObjectResolverTest.java

private byte[] objectToContent(final Object value) {
    final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

    final XMLEncoder encoder = new XMLEncoder(byteArrayOutputStream);
    encoder.setExceptionListener(new LogEncoderExceptionListener(value));

    LOG.debug("START Writing Object {} with XMLEncoder", value.getClass().getName());
    encoder.writeObject(value);/*from   www  .jav a 2  s. c  o  m*/
    LOG.debug("FINISH Writing Object {} with XMLEncoder", value.getClass().getName());

    encoder.flush();
    encoder.close();
    return byteArrayOutputStream.toByteArray();
}

From source file:org.ejbca.ui.web.admin.certprof.ProfilesExportServlet.java

private byte[] getProfileBytes(UpgradeableDataHashMap profile) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    XMLEncoder encoder = new XMLEncoder(baos);
    encoder.writeObject(profile.saveData());
    encoder.close();//  www  .  j av a  2  s . c o m
    byte[] ba = baos.toByteArray();
    baos.close();
    return ba;
}

From source file:org.shaman.database.Benchmark.java

private void printSaveLoadTimes(Record... roots) throws IOException, ClassNotFoundException {
    //result array
    final int subpassCount = 5;
    long[][] saveTimes = new long[4][roots.length * subpassCount];
    long[][] loadTimes = new long[4][roots.length * subpassCount];

    DecimalFormat format = new DecimalFormat("0000");
    System.out.println("\ntime to save / load  (ms):");
    System.out.println("passes     database     serial    compressed     xml");
    System.out.println("           save\\load   save\\load   save\\load   save\\load");

    //for every data graph
    for (int i = 0; i < roots.length; i++) {
        File f1 = File.createTempFile("benchmark1", ".db");
        File f2 = File.createTempFile("benchmark2", ".serial");
        File f3 = File.createTempFile("benchmark3", ".serial");
        File f4 = File.createTempFile("benchmark4", ".xml");
        Record root = roots[i];/*from  w  w w  . ja  v  a 2  s. com*/

        //save it multiple times
        for (int j = 0; j < subpassCount; j++) {
            int index = i * subpassCount + j;
            //delete files from previous pass
            f1.delete();
            f2.delete();
            f3.delete();
            f4.delete();

            long time1, time2;

            //database
            Database db = new Database(root);
            time1 = getTime();
            db.save(f1, FailOnErrorHandler.INSTANCE);
            time2 = getTime();
            saveTimes[0][index] = time2 - time1;

            //memory database
            //            time1 = getTime();
            //            ArrayOutput outp = new ArrayOutput();
            //            db.save(outp, FailOnErrorHandler.INSTANCE);
            //            outp.writeTo(f1b);
            //            time2 = getTime();
            //            saveTimes[0][index] = time2-time1;

            //uncompressed serialization
            time1 = getTime();
            OutputStream out = new BufferedOutputStream(new FileOutputStream(f2));
            ObjectOutputStream dos = new ObjectOutputStream(out);
            dos.writeObject(root);
            dos.close();
            time2 = getTime();
            saveTimes[1][index] = time2 - time1;

            //compressed serialization
            time1 = getTime();
            out = new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream(f3)));
            dos = new ObjectOutputStream(out);
            dos.writeObject(root);
            dos.close();
            time2 = getTime();
            saveTimes[2][index] = time2 - time1;

            //xml
            time1 = getTime();
            out = new BufferedOutputStream(new FileOutputStream(f4));
            XMLEncoder xml = new XMLEncoder(out);
            xml.writeObject(root);
            xml.close();
            time2 = getTime();
            saveTimes[3][index] = time2 - time1;
        }

        //load it multiple times
        for (int j = 0; j < subpassCount; j++) {
            int index = i * subpassCount + j;
            long time1, time2;

            //database
            time1 = getTime();
            Database db = new Database(f1, FailOnErrorHandler.INSTANCE);
            time2 = getTime();
            if (j == 0) {
                assertEquals(root, db.getRoot());
            }
            loadTimes[0][index] = time2 - time1;

            //memory database
            //            time1 = getTime();
            //            db = new Database(new StreamInput(f1b), FailOnErrorHandler.INSTANCE);
            //            time2 = getTime();
            //            if (j==0) {
            //               assertEquals(root, db.getRoot());
            //            }
            //            loadTimes[1][index] = time2-time1;

            //uncompressed serialization
            time1 = getTime();
            InputStream in = new BufferedInputStream(new FileInputStream(f2));
            ObjectInputStream dis = new ObjectInputStream(in);
            Object o = dis.readObject();
            dis.close();
            time2 = getTime();
            if (j == 0) {
                if (o instanceof SerializableStringMap) {
                    ((SerializableStringMap) o).postLoad();
                }
                assertEquals(root, o);
            }
            loadTimes[1][index] = time2 - time1;

            //compressed serialization
            time1 = getTime();
            in = new GZIPInputStream(new BufferedInputStream(new FileInputStream(f3)));
            dis = new ObjectInputStream(in);
            o = dis.readObject();
            dis.close();
            time2 = getTime();
            if (j == 0) {
                if (o instanceof SerializableStringMap) {
                    ((SerializableStringMap) o).postLoad();
                }
                assertEquals(root, o);
            }
            loadTimes[2][index] = time2 - time1;

            //xml
            time1 = getTime();
            in = new BufferedInputStream(new FileInputStream(f4));
            XMLDecoder xml = new XMLDecoder(in);
            o = xml.readObject();
            in.close();
            time2 = getTime();
            if (j == 0) {
                if (o instanceof SerializableStringMap) {
                    ((SerializableStringMap) o).postLoad();
                }
                assertEquals(root, o);
            }
            loadTimes[3][index] = time2 - time1;
        }
        //delete files
        f1.delete();
        f2.delete();
        f3.delete();
        f4.delete();

        //print this pass
        for (int j = 0; j < subpassCount; j++) {
            int index = i * subpassCount + j;
            System.out.print("pass " + (i + 1) + '\\' + (j + 1) + "   ");
            for (int h = 0; h < 4; h++) {
                //System.out.printf(format4, saveTimes[h][index]*getTimeMultiplicator());
                System.out.print(format.format(saveTimes[h][index] * getTimeMultiplicator()));
                System.out.print('\\');
                //System.out.printf(format4, loadTimes[h][index]*getTimeMultiplicator());
                System.out.print(format.format(loadTimes[h][index] * getTimeMultiplicator()));
                System.out.print("   ");
            }
            System.out.println();
        }
    }

}

From source file:psidev.psi.mi.filemakers.xmlMaker.XmlMakerGui.java

public void save() {
    try {//from w  w w .  j a va  2s.  com
        JFileChooser fc;
        if (Utils.lastVisitedMappingDirectory != null) {
            fc = new JFileChooser(Utils.lastVisitedMappingDirectory);
        } else
            fc = new JFileChooser(".");

        int returnVal = fc.showSaveDialog(new JFrame());
        if (returnVal != JFileChooser.APPROVE_OPTION) {
            return;
        }

        FileOutputStream fos = new FileOutputStream(fc.getSelectedFile());

        // Create XML encoder.
        XMLEncoder xenc = new XMLEncoder(fos);

        Mapping mapping = new Mapping();
        mapping.setTree(((XsdTreeStructImpl) treePanel.xsdTree).getMapping());

        /* dictionaries */
        for (int i = 0; i < treePanel.dictionaryPanel.dictionaries.getDictionaries().size(); i++) {
            //            DictionaryMapping dm = ((Dictionary) xsdTree.dictionaries
            //                  .getDictionaries().get(i)).getMapping();
            mapping.dictionaries.add(((Dictionary) xsdTree.dictionaries.getDictionaries().get(i)).getMapping());
        }

        /* flat files */
        for (int i = 0; i < xsdTree.flatFiles.flatFiles.size(); i++) {
            //            FlatFileMapping fm = (xsdTree.flatFiles.getFlatFile(i))
            //                  .getMapping();
            mapping.flatFiles.add((xsdTree.flatFiles.getFlatFile(i)).getMapping());
        }

        xenc.writeObject(mapping);

        xenc.close();
        fos.close();
    } catch (FileNotFoundException fe) {
        JOptionPane.showMessageDialog(new JFrame(), "Unable to write file",
                "[PSI makers: PSI maker] save mapping", JOptionPane.ERROR_MESSAGE);
    } catch (Exception ex) {
        System.out.println("pb: " + ex);
        StackTraceElement[] s = ex.getStackTrace();
        for (int i = 0; i < s.length; i++) {
            System.out.println(s[i]);
        }
    }
}

From source file:jeplus.JEPlusProject.java

/**
 * Save this project to an XML file/*from  ww w. jav  a  2s  .  c o m*/
 * @param fn The File object associated with the file to which the contents will be saved
 * @return Successful or not
 */
public boolean saveAsXML(File fn) {
    boolean success = true;

    // Write project file
    XMLEncoder encoder;
    try {
        encoder = new XMLEncoder(new BufferedOutputStream(new FileOutputStream(fn)));
        // Clear external parameters and rvx file reference fields before saving the project
        // These files are for importing only
        this.ParamFile = null;
        this.RvxFile = null;
        encoder.writeObject(this);
        encoder.close();
        // get new location of project file
        String dir = fn.getAbsoluteFile().getParent();
        dir = dir.concat(dir.endsWith(File.separator) ? "" : File.separator);
        this.updateBaseDir(dir);
        this.ContentChanged = false;
    } catch (FileNotFoundException ex) {
        logger.error("Failed to create " + fn + " for writing project.", ex);
        success = false;
    }
    return success;
}

From source file:ddf.catalog.source.solr.provider.SolrProviderExtensibleMetacards.java

@Test
public void queryInteger() throws UnsupportedQueryException {
    Query query = new QueryImpl(getFilterBuilder().attribute(intField).greaterThan().number(intFieldValue - 1));

    QueryRequest request = new QueryRequestImpl(query);

    SourceResponse response = provider.query(request);

    assertEquals(1, response.getResults().size());

    Metacard resultMetacard = response.getResults().get(0).getMetacard();

    assertThat(resultMetacard.getAttribute(Metacard.ID), notNullValue());
    assertThat(resultMetacard.getAttribute(doubleField).getValue(), equalTo(doubleFieldValue));
    assertThat(resultMetacard.getAttribute(intField).getValue(), equalTo(intFieldValue));
    assertThat(resultMetacard.getAttribute(floatField).getValue(), equalTo(floatFieldValue));
    assertThat(resultMetacard.getAttribute(longField).getValue(), equalTo(longFieldValue));
    assertThat(resultMetacard.getAttribute(byteField).getValue(), equalTo(byteFieldValue));
    assertThat(resultMetacard.getAttribute(booleanField).getValue(), equalTo(true));
    assertThat(resultMetacard.getAttribute(dateField).getValue(), equalTo(dateFieldValue));
    assertThat(resultMetacard.getAttribute(geoField).getValue(), equalTo(geoFieldValue));
    assertThat(resultMetacard.getAttribute(shortField).getValue(), equalTo(shortFieldValue));
    assertThat(resultMetacard.getAttribute(objectField).getValue(), instanceOf(BevelBorder.class));
    /*//from   ww w  .  ja v a 2s  .c  o m
     * Going to use the XMLEncoder. If it writes out the objects the same way in xml, then they
     * are the same.
     */
    ByteArrayOutputStream beveledBytesStreamFromSolr = new ByteArrayOutputStream();
    XMLEncoder solrXMLEncoder = new XMLEncoder(new BufferedOutputStream(beveledBytesStreamFromSolr));
    solrXMLEncoder.writeObject((resultMetacard.getAttribute(objectField).getValue()));
    solrXMLEncoder.close();

    ByteArrayOutputStream beveledBytesStreamOriginal = new ByteArrayOutputStream();
    XMLEncoder currendEncoder = new XMLEncoder(new BufferedOutputStream(beveledBytesStreamOriginal));
    currendEncoder.writeObject(objectFieldValue);
    currendEncoder.close();

    assertThat(beveledBytesStreamFromSolr.toByteArray(), equalTo(beveledBytesStreamOriginal.toByteArray()));
}

From source file:com.db4o.sync4o.ui.Db4oSyncSourceConfigPanel.java

private static void showTestUI() {

    // Make sure we have nice window decorations.
    JFrame.setDefaultLookAndFeelDecorated(true);

    // Create and set up the window.
    JFrame frame = new JFrame("Db4oSyncSourceConfigPanel Test Harness");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // Create and set up the content pane.
    final Db4oSyncSource source = new Db4oSyncSource();
    Db4oSyncSourceConfigPanel p = new Db4oSyncSourceConfigPanel();
    p.setManagementObject(new SyncSourceManagementObject(source, null, null, null, null));
    p.updateForm();/*  ww w. j  a  va 2  s  .c o m*/
    p.setOpaque(true); // content panes must be opaque
    frame.setContentPane(p);

    frame.addWindowListener(new WindowAdapter() {

        public void windowClosing(WindowEvent ev) {

            XMLEncoder encoder = null;
            try {
                FileOutputStream s = new FileOutputStream("test.xml");
                encoder = new XMLEncoder(s);
                encoder.setExceptionListener(new ExceptionListener() {
                    public void exceptionThrown(Exception exception) {
                        exception.printStackTrace();
                    }
                });
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                System.exit(-1);
            }
            encoder.writeObject((Object) source);
            encoder.flush();
            encoder.close();

        }

    });

    // Display the window.
    frame.pack();
    frame.setVisible(true);

}

From source file:statechum.analysis.learning.Visualiser.java

protected void setVisualiserKeyBindings() {
    persistAction = new graphAction("saveLayout", "save the layout of the visible graph") {

        /** Serial number. */
        private static final long serialVersionUID = 1L;

        @Override//from   w ww. j av a 2 s  .c  o m
        public void actionPerformed(@SuppressWarnings("unused") ActionEvent e) {
            XMLEncoder encoder = null;
            try {
                if (propName >= 0) {
                    String fileName = getLayoutFileName(graphs.get(currentGraph));
                    encoder = new XMLEncoder(new FileOutputStream(fileName));
                    Map<Integer, DoublePair> layout = ((XMLPersistingLayout) viewer.getModel().getGraphLayout())
                            .persist();
                    encoder.writeObject(layout);
                    XMLAffineTransformSerialised trV = new XMLAffineTransformSerialised();
                    trV.setFromAffineTransform(viewer.getViewTransformer().getTransform());
                    encoder.writeObject(trV);
                    XMLAffineTransformSerialised trL = new XMLAffineTransformSerialised();
                    trL.setFromAffineTransform(viewer.getLayoutTransformer().getTransform());
                    encoder.writeObject(trL);
                    ((XMLModalGraphMouse) viewer.getGraphMouse()).store(encoder);
                    encoder.writeObject(layoutOptions.get(currentGraph));
                    encoder.close();
                    encoder = null;
                }
            } catch (Exception e1) {
                e1.printStackTrace();
            } finally {
                if (encoder != null) {
                    encoder.close();
                    encoder = null;
                }
            }
        }
    };
    keyToActionMap.put(KeyEvent.VK_F2, persistAction);
    keyToActionMap.put(KeyEvent.VK_F3,
            new graphAction("loadLayout", "loads the previously saved layout into the visible graph") {

                /** Serial number. */
                private static final long serialVersionUID = 2L;

                @Override
                public void actionPerformed(@SuppressWarnings("unused") ActionEvent e) {
                    reloadLayout(false, true);
                }
            });
    keyToActionMap.put(KeyEvent.VK_F9,
            new graphAction("loadPreviousLayout", "loads the layout of the previous graph in the list") {

                /** Serial number. */
                private static final long serialVersionUID = 3L;

                @Override
                public void actionPerformed(@SuppressWarnings("unused") ActionEvent e) {
                    if (currentGraph > 0) {
                        restoreLayout(false, currentGraph - 1);
                    }
                }
            });

    pickAction = new graphAction("pick", "Switches Jung into picking mode") {

        /** Serial number. */
        private static final long serialVersionUID = 7L;

        @Override
        public void actionPerformed(@SuppressWarnings("unused") ActionEvent e) {
            ((XMLModalGraphMouse) viewer.getGraphMouse()).setMode(ModalGraphMouse.Mode.PICKING);
        }
    };
    keyToActionMap.put(KeyEvent.VK_F11, pickAction);

    transformAction = new graphAction("transform", "Switches Jung into transformation mode") {

        /** Serial number. */
        private static final long serialVersionUID = 8L;

        @Override
        public void actionPerformed(@SuppressWarnings("unused") ActionEvent e) {
            ((XMLModalGraphMouse) viewer.getGraphMouse()).setMode(ModalGraphMouse.Mode.TRANSFORMING);
        }
    };
    keyToActionMap.put(KeyEvent.VK_F12, transformAction);

    keyToActionMap.put(KeyEvent.VK_UP, new graphAction("previous", "loads the previous graph") {

        /** Serial number. */
        private static final long serialVersionUID = 9L;

        @Override
        public void actionPerformed(@SuppressWarnings("unused") ActionEvent e) {
            if (currentGraph > 0) {
                --currentGraph;
                reloadLayout(false, true);
            }
        }
    });
    keyToActionMap.put(KeyEvent.VK_DOWN, new graphAction("next", "loads the next graph") {

        /** Serial number. */
        private static final long serialVersionUID = 10L;

        @Override
        public void actionPerformed(@SuppressWarnings("unused") ActionEvent e) {
            if (currentGraph < graphs.size() - 1) {
                ++currentGraph;
                reloadLayout(false, true);
            }
        }
    });

    keyToActionMap.put(KeyEvent.VK_F, new graphAction("negatives", "toggles negatives on or off") {

        /** Serial number. */
        private static final long serialVersionUID = 11L;

        @Override
        public void actionPerformed(@SuppressWarnings("unused") ActionEvent e) {
            LayoutOptions options = layoutOptions.get(currentGraph);
            if (options != null) {
                options.showNegatives = !options.showNegatives;
                reloadLayout(false, false);
            }
        }
    });
    keyToActionMap.put(KeyEvent.VK_I, new graphAction("ignored states", "toggles ignored states on or off") {

        /** Serial number. */
        private static final long serialVersionUID = 12L;

        @Override
        public void actionPerformed(@SuppressWarnings("unused") ActionEvent e) {
            LayoutOptions options = layoutOptions.get(currentGraph);
            if (options != null) {
                options.showIgnored = !options.showIgnored;
                reloadLayout(false, false);
            }
        }
    });
    keyToActionMap.put(KeyEvent.VK_PAGE_DOWN, new graphAction("refine", "reduces the abstraction level") {

        /** Serial number. */
        private static final long serialVersionUID = 13L;

        @Override
        public void actionPerformed(@SuppressWarnings("unused") ActionEvent e) {
            LayoutOptions options = layoutOptions.get(currentGraph);
            if (options != null && options.componentsToPick < Integer.MAX_VALUE) {
                options.componentsToPick++;
                reloadLayout(false, false);
            }
        }
    });
    keyToActionMap.put(KeyEvent.VK_PAGE_UP, new graphAction("abstract", "increases abstraction level") {

        /** Serial number. */
        private static final long serialVersionUID = 14L;

        @Override
        public void actionPerformed(@SuppressWarnings("unused") ActionEvent e) {
            LayoutOptions options = layoutOptions.get(currentGraph);
            if (options != null && options.componentsToPick != Integer.MAX_VALUE
                    && options.componentsToPick > 0) {
                --options.componentsToPick;
                reloadLayout(false, false);
            }
        }
    });
}

From source file:org.shaman.database.Benchmark.java

/**
 * prints the file size/*from  w ww  . j av a  2s  . co  m*/
 * @param roots the roots from the different passes
 */
private void printFileSizes(Record... roots) throws IOException {
    //result array
    int size;

    String format = "%1$,11d";
    System.out.println("passes       database          serial      compressed             xml");

    //save it
    for (int i = 0; i < roots.length; i++) {
        Record root = roots[i];
        System.out.print("pass " + (i + 1) + "   ");
        //database
        ArrayOutput ao = new ArrayOutput();
        Database db = new Database(root);
        db.save(ao, FailOnErrorHandler.INSTANCE);
        size = ao.getTotalSize();
        System.out.printf(format, size);
        System.out.print("B    ");

        //uncompressed serialization
        CountingOutputStream out = new CountingOutputStream(new NullOutputStream());
        ObjectOutputStream dos = new ObjectOutputStream(out);
        dos.writeObject(root);
        dos.flush();
        size = out.getCount();
        System.out.printf(format, size);
        System.out.print("B    ");

        //compressed serialization
        out.resetCount();
        dos = new ObjectOutputStream(new GZIPOutputStream(out));
        dos.writeObject(root);
        dos.flush();
        size = out.getCount();
        System.out.printf(format, size);
        System.out.print("B    ");

        //xml
        out.resetCount();
        XMLEncoder xml = new XMLEncoder(out);
        xml.writeObject(root);
        xml.flush();
        size = out.getCount();
        System.out.printf(format, size);
        System.out.println("B");
    }

}

From source file:com.swingtech.commons.util.ClassUtil.java

/**
 * NOTE: When using this to print an object it will not display the
 * primitive type boolean. Must use the wrapper class. All other primitives
 * work fine.//from ww  w  .ja v a  2 s  .c o  m
 *
 * NOTE: If an int value has a 0 it won't display.
 *
 * NOTE: Object must have a public constructor.
 *
 * @param object
 * @return
 */
public static String getXMLForObject(final Object object) {
    ByteArrayOutputStream baos = null;
    XMLEncoder e = null;

    baos = new ByteArrayOutputStream();
    e = new XMLEncoder(new BufferedOutputStream(baos));

    e.setPersistenceDelegate(Date.class, new PersistenceDelegate() {
        @Override
        protected Expression instantiate(final Object oldInstance, final Encoder out) {
            final Date date = (Date) oldInstance;
            final Long time = new Long(date.getTime());
            return new Expression(date, date.getClass(), "new", new Object[] { time });
        }
    });

    e.setPersistenceDelegate(BigDecimal.class, new PersistenceDelegate() {
        @Override
        protected Expression instantiate(final Object oldInstance, final Encoder out) {
            final BigDecimal bigDec = (BigDecimal) oldInstance;
            final double doubleVal = bigDec.doubleValue();
            return new Expression(bigDec, bigDec.getClass(), "new", new Object[] { new Double(doubleVal) });
        }
    });

    e.writeObject(object);
    e.close();

    return baos.toString();
}