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.latticesoft.util.common.FileUtil.java

/**
 * Write an object into the xmlfile/*w  w w . ja  v  a2 s . c om*/
 * @param filename the name of the file to output to
 * @param o the object to be serialized
 */
public static void writeToXmlFile(String filename, Object o) {
    if (o == null || filename == null) {
        return;
    }
    XMLEncoder encoder = null;
    try {
        encoder = new XMLEncoder(new BufferedOutputStream(new FileOutputStream(filename)));
        encoder.writeObject(o);
    } catch (Exception e) {
        if (log.isErrorEnabled()) {
            log.error(e);
        }
    } finally {
        try {
            encoder.close();
        } catch (Exception e) {
        }
    }
}

From source file:net.sf.taverna.t2.provenance.lineageservice.EventProcessor.java

/**
 * log raw event to file system//from   w w w.  j a  v a 2s  .  co m
 * 
 * @param content
 * @param eventType
 * @throws IOException
 */
public void saveEvent(ProvenanceItem provenanceItem, SharedVocabulary eventType) throws IOException {

    // HACK -- XMLEncoder fails on IterationEvents and there is no way to catch the exception...
    // so avoid this case
    if (eventType.equals(SharedVocabulary.ITERATION_EVENT_TYPE)) {
        return;
    }

    //      System.out.println("saveEvent: start");

    File f1 = null;

    f1 = new File(TEST_EVENTS_FOLDER);
    FileUtils.forceMkdir(f1);

    String fname = "event_" + eventCnt++ + "_" + eventType + ".xml";
    File f = new File(f1, fname);

    //      FileWriter fw = new FileWriter(f);

    XMLEncoder en = new XMLEncoder(new BufferedOutputStream(new FileOutputStream(f)));

    en.setExceptionListener(new ExceptionListener() {
        public void exceptionThrown(Exception e) {
            logger.warn("XML encoding ERROR", e);
            return;
        }
    });

    logger.debug("saving to " + f); // save event for later inspection
    logger.debug(provenanceItem);

    en.writeObject(provenanceItem);

    logger.debug("writer ok");
    en.close();
    logger.debug("closed");

    //      fw.write(content);
    //      fw.flush();
    //      fw.close();

    //      FileWriter fw = new FileWriter(f);
    //      fw.write(content);
    //      fw.flush();
    //      fw.close();

    //      System.out.println("saved as file " + fname);

}

From source file:com.alvermont.terraj.planet.ui.MainFrame.java

private void saveParamsItemActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_saveParamsItemActionPerformed
{//GEN-HEADEREND:event_saveParamsItemActionPerformed

    final int choice = xmlChooser.showSaveDialog(this);

    if (choice == JFileChooser.APPROVE_OPTION) {
        try {//from ww  w. ja  v  a2 s  . com
            if (!xmlChooser.getFileContents().canRead() || (JOptionPane.showConfirmDialog(this,
                    "This file already exists. Do you want to\n" + "overwrite it?", "Replace File?",
                    JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)) {
                final OutputStream target = xmlChooser.getFileContents().getOutputStream(true);

                final XMLEncoder enc = new XMLEncoder(target);

                enc.writeObject(params);

                enc.close();
                target.close();
            }
        } catch (IOException ioe) {
            log.error("Error writing xml file", ioe);

            JOptionPane.showMessageDialog(this,
                    "Error: " + ioe.getMessage() + "\nCheck log file for full details", "Error Saving",
                    JOptionPane.ERROR_MESSAGE);
        }
    }
}

From source file:ddf.catalog.source.solr.SolrProviderTest.java

@Test
public void testExtensibleMetacards() throws IngestException, UnsupportedQueryException {

    deleteAllIn(provider);//from w  w  w.  j  a  va 2  s . com

    String brandNewField1 = "description";
    String brandNewFieldValue1 = "myDescription";

    /* BASIC STRINGS */
    Set<AttributeDescriptor> descriptors = new HashSet<AttributeDescriptor>();
    descriptors.add(new AttributeDescriptorImpl(Metacard.ID, true, true, true, false, BasicTypes.STRING_TYPE));
    descriptors
            .add(new AttributeDescriptorImpl(brandNewField1, true, true, true, false, BasicTypes.STRING_TYPE));
    MetacardTypeImpl mType = new MetacardTypeImpl("custom1", descriptors);
    MetacardImpl customMetacard = new MetacardImpl(mType);
    // customMetacard.setAttribute("id", "44567880");
    customMetacard.setAttribute(brandNewField1, brandNewFieldValue1);

    create(customMetacard);

    // search id
    Query query = new QueryImpl(filterBuilder.attribute("id").like().text("*"));

    QueryRequest request = new QueryRequestImpl(query);

    SourceResponse response = provider.query(request);

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

    assertEquals("custom1", response.getResults().get(0).getMetacard().getMetacardType().getName());

    assertThat(response.getResults().get(0).getMetacard().getMetacardType().getAttributeDescriptors(),
            equalTo(descriptors));

    // search title - *
    query = new QueryImpl(filterBuilder.attribute(brandNewField1).like().text("*"));

    request = new QueryRequestImpl(query);

    response = provider.query(request);

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

    assertEquals("custom1", response.getResults().get(0).getMetacard().getMetacardType().getName());

    assertThat(response.getResults().get(0).getMetacard().getMetacardType().getAttributeDescriptors(),
            equalTo(descriptors));

    // search title - exact
    query = new QueryImpl(filterBuilder.attribute(brandNewField1).equalTo().text(brandNewFieldValue1));

    request = new QueryRequestImpl(query);

    response = provider.query(request);

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

    // search negative

    query = new QueryImpl(filterBuilder.attribute(brandNewField1).like().text("no"));

    request = new QueryRequestImpl(query);

    response = provider.query(request);

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

    // NEW TYPE

    String brandNewXmlField1 = "author";
    String brandNewXmlFieldValue1 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n"
            + "<author>john doe</author>";

    descriptors = new HashSet<AttributeDescriptor>();
    descriptors.add(new AttributeDescriptorImpl(Metacard.ID, true, true, true, false, BasicTypes.STRING_TYPE));
    descriptors
            .add(new AttributeDescriptorImpl(brandNewXmlField1, true, true, true, false, BasicTypes.XML_TYPE));
    mType = new MetacardTypeImpl("34ga$^TGHfg:/", descriptors);
    customMetacard = new MetacardImpl(mType);
    // customMetacard.setAttribute(Metacard.ID, "44567880");
    customMetacard.setAttribute(brandNewXmlField1, brandNewXmlFieldValue1);

    create(customMetacard);

    // Two Ids
    query = new QueryImpl(filterBuilder.attribute(Metacard.ID).like().text("*"));

    request = new QueryRequestImpl(query);

    response = provider.query(request);

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

    // search xml
    query = new QueryImpl(filterBuilder.attribute(brandNewXmlField1).like().caseSensitiveText("doe"));

    request = new QueryRequestImpl(query);

    response = provider.query(request);

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

    assertEquals("34ga$^TGHfg:/", response.getResults().get(0).getMetacard().getMetacardType().getName());

    assertThat(response.getResults().get(0).getMetacard().getMetacardType().getAttributeDescriptors(),
            equalTo(descriptors));

    // search xml - negative
    query = new QueryImpl(filterBuilder.attribute(brandNewXmlField1).like().text("author"));

    request = new QueryRequestImpl(query);

    response = provider.query(request);

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

    // EVERYTHING ELSE type
    String doubleField = "hertz";
    double doubleFieldValue = 16065.435;

    String floatField = "inches";
    float floatFieldValue = 4.435f;

    String intField = "count";
    int intFieldValue = 4;

    String longField = "milliseconds";
    long longFieldValue = 987654322111L;

    String byteField = "bytes";
    byte[] byteFieldValue = { 86 };

    String booleanField = "expected";
    boolean booleanFieldValue = true;

    String dateField = "lost";
    Date dateFieldValue = new Date();

    String geoField = "geo";
    String geoFieldValue = GULF_OF_GUINEA_POINT_WKT;

    String shortField = "daysOfTheWeek";
    short shortFieldValue = 1;

    String objectField = "payload";
    BevelBorder objectFieldValue = new BevelBorder(BevelBorder.RAISED);

    descriptors = new HashSet<AttributeDescriptor>();
    descriptors.add(new AttributeDescriptorImpl(Metacard.ID, true, true, true, false, BasicTypes.STRING_TYPE));
    descriptors.add(new AttributeDescriptorImpl(doubleField, true, true, false, false, BasicTypes.DOUBLE_TYPE));
    descriptors.add(new AttributeDescriptorImpl(floatField, true, true, false, false, BasicTypes.FLOAT_TYPE));
    descriptors.add(new AttributeDescriptorImpl(intField, true, true, false, false, BasicTypes.INTEGER_TYPE));
    descriptors.add(new AttributeDescriptorImpl(longField, true, true, false, false, BasicTypes.LONG_TYPE));
    descriptors.add(new AttributeDescriptorImpl(byteField, false, true, false, false, BasicTypes.BINARY_TYPE));
    descriptors
            .add(new AttributeDescriptorImpl(booleanField, true, true, false, false, BasicTypes.BOOLEAN_TYPE));
    descriptors.add(new AttributeDescriptorImpl(dateField, true, true, false, false, BasicTypes.DATE_TYPE));
    descriptors.add(new AttributeDescriptorImpl(geoField, true, true, false, false, BasicTypes.GEO_TYPE));
    descriptors.add(new AttributeDescriptorImpl(shortField, true, true, false, false, BasicTypes.SHORT_TYPE));
    descriptors
            .add(new AttributeDescriptorImpl(objectField, false, true, false, false, BasicTypes.OBJECT_TYPE));

    mType = new MetacardTypeImpl("numbersMT", descriptors);

    customMetacard = new MetacardImpl(mType);
    // customMetacard.setAttribute(Metacard.ID, "245gasg324");
    customMetacard.setAttribute(doubleField, doubleFieldValue);
    customMetacard.setAttribute(floatField, floatFieldValue);
    customMetacard.setAttribute(intField, intFieldValue);
    customMetacard.setAttribute(longField, longFieldValue);
    customMetacard.setAttribute(byteField, byteFieldValue);
    customMetacard.setAttribute(booleanField, booleanFieldValue);
    customMetacard.setAttribute(dateField, dateFieldValue);
    customMetacard.setAttribute(geoField, geoFieldValue);
    customMetacard.setAttribute(shortField, shortFieldValue);
    customMetacard.setAttribute(objectField, objectFieldValue);

    create(customMetacard);

    // Three Ids
    query = new QueryImpl(filterBuilder.attribute(Metacard.ID).like().text("*"));

    request = new QueryRequestImpl(query);

    response = provider.query(request);

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

    // search double
    query = new QueryImpl(filterBuilder.attribute(doubleField).greaterThan().number(doubleFieldValue - 1.0));

    request = new QueryRequestImpl(query);

    response = provider.query(request);

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

    // search int
    query = new QueryImpl(filterBuilder.attribute(intField).greaterThan().number(intFieldValue - 1));

    request = new QueryRequestImpl(query);

    response = provider.query(request);

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

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

    assertThat(resultMetacard.getAttribute(Metacard.ID), notNullValue());
    assertThat((Double) (resultMetacard.getAttribute(doubleField).getValue()), equalTo(doubleFieldValue));
    assertThat((Integer) (resultMetacard.getAttribute(intField).getValue()), equalTo(intFieldValue));
    assertThat((Float) (resultMetacard.getAttribute(floatField).getValue()), equalTo(floatFieldValue));
    assertThat((Long) (resultMetacard.getAttribute(longField).getValue()), equalTo(longFieldValue));
    assertThat((byte[]) (resultMetacard.getAttribute(byteField).getValue()), equalTo(byteFieldValue));
    assertThat((Boolean) (resultMetacard.getAttribute(booleanField).getValue()), equalTo(booleanFieldValue));
    assertThat((Date) (resultMetacard.getAttribute(dateField).getValue()), equalTo(dateFieldValue));
    assertThat((String) (resultMetacard.getAttribute(geoField).getValue()), equalTo(geoFieldValue));
    assertThat((Short) (resultMetacard.getAttribute(shortField).getValue()), equalTo(shortFieldValue));
    assertThat((BevelBorder) (resultMetacard.getAttribute(objectField).getValue()),
            instanceOf(BevelBorder.class));

    /*
     * 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()));

    // search short
    query = new QueryImpl(filterBuilder.attribute(shortField).greaterThanOrEqualTo().number(shortFieldValue));

    request = new QueryRequestImpl(query);

    response = provider.query(request);

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

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

}

From source file:de.huxhorn.lilith.swing.ApplicationPreferences.java

private boolean writeSourceLists(Map<String, Set<String>> sourceLists) {
    File appPath = getStartupApplicationPath();
    File file = new File(appPath, SOURCE_LISTS_XML_FILENAME);
    XMLEncoder e = null;// w  w  w. ja v  a 2 s.  c  om
    Throwable error = null;
    try {
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
        e = new XMLEncoder(bos);
        e.writeObject(sourceLists);
    } catch (FileNotFoundException ex) {
        error = ex;
    } finally {
        if (e != null) {
            e.close();
        }
    }
    if (error != null) {
        if (logger.isWarnEnabled())
            logger.warn("Exception while writing source lists!", error);
        return false;
    }
    return true;
}

From source file:de.huxhorn.lilith.swing.ApplicationPreferences.java

private boolean writeConditions(List<SavedCondition> conditions) {
    File appPath = getStartupApplicationPath();
    File file = new File(appPath, CONDITIONS_XML_FILENAME);
    XMLEncoder e = null;//from   w  ww  .  j ava  2s  . c o m
    Throwable error = null;
    try {
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
        e = new XMLEncoder(bos);
        e.writeObject(conditions);
        if (logger.isInfoEnabled())
            logger.info("Wrote conditions {}.", conditions);
    } catch (FileNotFoundException ex) {
        error = ex;
    } finally {
        if (e != null) {
            e.close();
        }
    }
    if (error != null) {
        if (logger.isWarnEnabled())
            logger.warn("Exception while writing source lists!", error);
        return false;
    }
    return true;
}

From source file:de.huxhorn.lilith.swing.ApplicationPreferences.java

private boolean writeColumnLayout(File file,
        List<PersistentTableColumnModel.TableColumnLayoutInfo> layoutInfos) {
    XMLEncoder e = null;/*w  ww  .j a  v  a2  s. c  o m*/
    Throwable error = null;
    try {
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
        e = new XMLEncoder(bos);
        e.writeObject(layoutInfos);
        if (logger.isInfoEnabled())
            logger.info("Wrote layouts {} to file '{}'.", layoutInfos, file.getAbsolutePath());
    } catch (FileNotFoundException ex) {
        error = ex;
    } finally {
        if (e != null) {
            e.close();
        }
    }
    if (error != null) {
        if (logger.isWarnEnabled())
            logger.warn("Exception while writing layouts to file '" + file.getAbsolutePath() + "'!", error);
        return false;
    }
    return true;
}

From source file:com.projity.pm.graphic.frames.GraphicManager.java

/**
 * Encode the current workspace and store it off in lastWorkspace.
 * Currently I use an XML format for easier debugging. It could be serialized as binary as well since
 * all objects in the graph implement Serializable
 *
 *///from w  w  w . java  2  s.  c  o  m
private void encodeWorkspaceXML() {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(stream));
    encoder.writeObject(createWorkspace(SavableToWorkspace.VIEW));
    encoder.close();
    lastWorkspace = stream.toString();
    //      System.out.println(lastWorkspace);
}

From source file:org.ejbca.core.protocol.ws.EjbcaWS.java

@Override
public byte[] getProfile(int profileId, String profileType)
        throws AuthorizationDeniedException, EjbcaException, UnknownProfileTypeException {
    final EjbcaWSHelper ejbhelper = new EjbcaWSHelper(wsContext, authorizationSession, caAdminSession,
            caSession, certificateProfileSession, certificateStoreSession, endEntityAccessSession,
            endEntityProfileSession, hardTokenSession, endEntityManagementSession, webAuthenticationSession,
            cryptoTokenManagementSession);
    final AuthenticationToken admin = ejbhelper.getAdmin();
    final IPatternLogger logger = TransactionLogger.getPatternLogger();
    logAdminName(admin, logger);/*from   www  .  j a v  a  2 s.c om*/

    UpgradeableDataHashMap profile = null;
    if (StringUtils.equalsIgnoreCase(profileType, "eep")) {
        profile = endEntityProfileSession.getEndEntityProfileNoClone(profileId);
        if (profile == null) {
            throw EjbcaWSHelper.getEjbcaException(
                    new EndEntityProfileNotFoundException(
                            "Could not find end entity profile with ID '" + profileId + "' in the database."),
                    null, ErrorCode.EE_PROFILE_NOT_EXISTS, null);
        }
    } else if (StringUtils.equalsIgnoreCase(profileType, "cp")) {
        profile = certificateProfileSession.getCertificateProfile(profileId);
        if (profile == null) {
            throw EjbcaWSHelper.getEjbcaException(
                    new CertificateProfileDoesNotExistException(
                            "Could not find certificate profile with ID '" + profileId + "' in the database."),
                    null, ErrorCode.CERT_PROFILE_NOT_EXISTS, null);
        }
    } else {
        throw new UnknownProfileTypeException("Unknown profile type '" + profileType
                + "'. Recognized types are 'eep' for End Entity Profiles and 'cp' for Certificate Profiles");
    }

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    XMLEncoder encoder = new XMLEncoder(baos);
    encoder.writeObject(profile.saveData());
    encoder.close();
    byte[] ba = baos.toByteArray();
    try {
        baos.close();
    } catch (IOException e) {
        throw EjbcaWSHelper.getInternalException(e, logger);
    } finally {
        logger.writeln();
        logger.flush();
    }
    return ba;
}