Example usage for java.beans XMLEncoder close

List of usage examples for java.beans XMLEncoder close

Introduction

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

Prototype

public void close() 

Source Link

Document

This method calls flush , writes the closing postamble and then closes the output stream associated with this stream.

Usage

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();
    byte[] ba = baos.toByteArray();
    baos.close();//from www .ja v a 2 s  .  c o m
    return ba;
}

From source file:edu.wisc.my.portlets.bookmarks.dao.file.FileSystemBookmarkStore.java

/**
 * @see edu.wisc.my.portlets.bookmarks.dao.BookmarkStore#storeBookmarkSet(edu.wisc.my.portlets.bookmarks.domain.BookmarkSet)
 *///  w w w . j ava2  s.c o  m
public void storeBookmarkSet(BookmarkSet bookmarkSet) {
    if (bookmarkSet == null) {
        throw new IllegalArgumentException("AddressBook may not be null");
    }

    final File storeFile = this.getStoreFile(bookmarkSet.getOwner(), bookmarkSet.getName());

    try {
        final FileOutputStream fos = new FileOutputStream(storeFile);
        final BufferedOutputStream bos = new BufferedOutputStream(fos);
        final XMLEncoder e = new XMLEncoder(bos);
        try {
            e.writeObject(bookmarkSet);
        } finally {
            e.close();
        }
    } catch (FileNotFoundException fnfe) {
        final String errorMsg = "Error storing BookmarkSet='" + bookmarkSet + "' to file='" + storeFile + "'";
        logger.error(errorMsg, fnfe);
        throw new DataAccessResourceFailureException(errorMsg, fnfe);
    }
}

From source file:edu.wisc.my.stats.dao.xml.XmlQueryInformationDao.java

/**
 * @param queryInformationSet The Set of QueryInformation to persist to the specified XML file.
 */// w  w  w.j a  va  2  s . c om
protected void writeQueryInformationSet(Set<QueryInformation> queryInformationSet) {
    final FileOutputStream fos;
    try {
        fos = new FileOutputStream(this.storeFile);
    } catch (FileNotFoundException fnfe) {
        final String errorMessage = "The specified storeFile='" + this.storeFile + "' could not be found.";
        this.logger.error(errorMessage, fnfe);
        throw new IllegalArgumentException(errorMessage, fnfe);
    }

    final BufferedOutputStream bos = new BufferedOutputStream(fos);
    final XMLEncoder xmlEncoder = new XMLEncoder(bos);
    try {
        xmlEncoder.writeObject(queryInformationSet);
        xmlEncoder.flush();
    } finally {
        xmlEncoder.close();
    }
}

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 a v  a  2 s  .c o 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:lu.lippmann.cdb.graph.GraphUtil.java

/**
 * //from w  w w  . j ava2s.  c  o 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:org.ejbca.extra.db.SubMessages.java

/**
 * Method used to persist the set of submessages
 * @return a String representation of the data
 *//*from   w  w w. j a  v  a2 s. c  o m*/
String save() {
    String retval = null;

    ArrayList savearray = new ArrayList();

    Iterator<ISubMessage> iter = submessages.iterator();
    while (iter.hasNext()) {
        ISubMessage next = iter.next();
        savearray.add(next.saveData());
    }

    try {
        java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(savearray);
        byte[] messagedata = baos.toByteArray();

        if (isSigned) {
            messagedata = ExtRAMsgHelper.signData(userKey, userCert, messagedata);
        }

        if (isEncrypted) {
            messagedata = ExtRAMsgHelper.encryptData(encCert, messagedata);
        }

        java.io.ByteArrayOutputStream baos2 = new java.io.ByteArrayOutputStream();

        java.beans.XMLEncoder encoder = new java.beans.XMLEncoder(baos2);
        encoder.writeObject(Boolean.valueOf(isSigned));
        encoder.writeObject(Boolean.valueOf(isEncrypted));
        encoder.writeObject(new String(Base64.encode(messagedata)));
        encoder.close();
        retval = baos2.toString("UTF8");
    } catch (Exception e) {
        log.error("Error writing persistent SubMessages.", e);
    }

    return retval;
}

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  www .  ja  va 2  s  .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: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];// w  w  w  .j  a v  a  2  s .c  o m

        //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: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   www  . j  a  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();
}

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);/*w  ww  .  j av  a2  s . co  m*/
    LOG.debug("FINISH Writing Object {} with XMLEncoder", value.getClass().getName());

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