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:edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty.java

/** for debugging */
public void xmlToSysOut() {
    XMLEncoder e = new XMLEncoder(System.out);
    e.writeObject(this);
}

From source file:org.openmrs.reporting.ReportObjectXMLEncoder.java

@SuppressWarnings("unchecked")
public String toXmlString() {
    ByteArrayOutputStream arr = new ByteArrayOutputStream();
    EnumDelegate enumDelegate = new EnumDelegate();

    XMLEncoder enc = new XMLEncoder(new BufferedOutputStream(arr));
    enc.setPersistenceDelegate(User.class, new UserDelegate());
    enc.setPersistenceDelegate(Location.class, new LocationDelegate());
    enc.setPersistenceDelegate(Cohort.class, new CohortDelegate());
    enc.setPersistenceDelegate(Concept.class, new ConceptDelegate());
    enc.setPersistenceDelegate(Drug.class, new DrugDelegate());
    enc.setPersistenceDelegate(Encounter.class, new EncounterDelegate());
    enc.setPersistenceDelegate(Patient.class, new PatientDelegate());
    enc.setPersistenceDelegate(Program.class, new ProgramDelegate());
    enc.setPersistenceDelegate(ProgramWorkflow.class, new ProgramWorkflowDelegate());
    enc.setPersistenceDelegate(ProgramWorkflowState.class, new ProgramWorkflowStateDelegate());
    enc.setPersistenceDelegate(ConceptAnswer.class, new ConceptAnswerDelegate());
    enc.setPersistenceDelegate(EncounterType.class, new EncounterTypeDelegate());
    enc.setPersistenceDelegate(PersonAttributeType.class, new PersonAttributeTypeDelegate());
    enc.setPersistenceDelegate(ConceptNumeric.class, new ConceptNumericDelegate());

    Set<Class> alreadyAdded = new HashSet<Class>();
    {//from ww  w  .  jav  a2 s . co m
        List<Class> enumClasses = new ArrayList<Class>();
        enumClasses.add(PatientSetService.Modifier.class);
        enumClasses.add(PatientSetService.TimeModifier.class);
        enumClasses.add(PatientSetService.BooleanOperator.class);
        enumClasses.add(PatientSetService.GroupMethod.class);
        for (Class clz : enumClasses) {
            enc.setPersistenceDelegate(clz, enumDelegate);
            alreadyAdded.add(clz);
        }

    }
    // This original implementation won't handle enums that aren't direct properties of the bean, but I'm leaving it here anyway.
    for (Field f : this.objectToEncode.getClass().getDeclaredFields()) {
        Class clz = f.getType();
        if (clz.isEnum() && !alreadyAdded.contains(clz)) {
            try {
                enc.setPersistenceDelegate(clz, enumDelegate);
                alreadyAdded.add(clz);
            } catch (Exception e) {
                log.error("ReportObjectXMLEncoder failed to write enumeration " + f.getName(), e);
            }
        }
    }
    log.debug("objectToEncode.type: " + objectToEncode.getClass());
    enc.writeObject(this.objectToEncode);
    enc.close();

    return arr.toString();
}

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

@SuppressWarnings("rawtypes")
@Test//from w ww  .ja v  a2  s  .c o m
public void testHashMapStrangeChars() throws Exception {
    HashMap<String, Comparable> a = new HashMap<String, Comparable>();
    a.put("foo0", Boolean.FALSE);
    a.put("foo1", "\0001\0002fooString");
    a.put("foo2", Integer.valueOf(2));
    a.put("foo3", Boolean.TRUE);

    // 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();
        assertEquals(((Boolean) b.get("foo0")).booleanValue(), false);
        // We can get two different errors, I don't know if it is different java versions or what...
        // The important thing is that we do expect an error to occur here
    } catch (ClassCastException e) {
        return;
    } catch (ArrayIndexOutOfBoundsException e) {
        return;
    }
    String javaver = System.getProperty("java.version");
    System.out.println(javaver);
    if (StringUtils.contains(javaver, "1.6") || StringUtils.contains(javaver, "1.7")
            || StringUtils.contains(javaver, "1.8")) {
        // In java 1.6 the above does work because it encodes the special characters
        //   <string><char code="#0"/>1<char code="#0"/>2fooString</string> 
        assertTrue(true);
    } else {
        // In java 1.5 the above does not work, because it will insert bad xml-characters 
        // so the test will fail if we got here.
        assertTrue(false);
    }
}

From source file:org.seasar.cadhelin.ControllerMetadata.java

public void saveConverterSettings(OutputStream os) {
    XMLEncoder encoder = new XMLEncoder(os);
    encoder.writeObject(getConverters());
    encoder.close();
}

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)
 *///from w  ww  .  j  a  v  a2s.  co  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:org.geomajas.plugin.deskmanager.domain.types.XmlSerialisationType.java

private String toXmlString(Object value) {
    if (value == null) {
        return null;
    }/*from   w  w  w .  j  a v  a  2 s. com*/
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        XMLEncoder encoder = new XMLEncoder(baos);
        encoder.writeObject(value);
        encoder.close();
        String result = baos.toString(ENCODING);
        baos.close();
        return result;
    } catch (IOException e) {
        e.printStackTrace();
        IllegalArgumentException ex = new IllegalArgumentException("cannot disassemble the object", e);
        throw ex;
    }
}

From source file:de.wpsverlinden.dupfind.FileIndexer.java

public void saveIndex() {
    File outFile = new File(userDir + "/DupFind.index.gz");
    outputPrinter.print("Saving index ... ");
    try (XMLEncoder xenc = new XMLEncoder(new GZIPOutputStream(new FileOutputStream(outFile)))) {
        xenc.writeObject(fileIndex);/*from   www. jav  a 2s.  c om*/
        xenc.flush();
        outputPrinter.println("done.  " + fileIndex.size() + " files in index.");
    } catch (IOException e) {
        System.err.println(e);
    }
}

From source file:org.languagetool.gui.LocalStorage.java

void saveProperty(String name, Object obj) {
    if (directory == null) {
        return;/*  w  w w .  j a  v a2 s.  c om*/
    }
    synchronized (directory) {
        try (XMLEncoder encoder = new XMLEncoder(
                new BufferedOutputStream(new FileOutputStream(new File(directory, name))))) {
            encoder.writeObject(obj);
        } catch (FileNotFoundException ex) {
            Tools.showError(ex);
        }
    }
}

From source file:org.clickframes.testframes.TestRunner.java

/**
 * Use this advanced interface to only run tests approved by this filter
 *
 * @param appspec/*www .  j  av  a2  s  . c  o m*/
 * @param filenameFilter
 * @return
 * @throws Exception
 *
 * @author Vineet Manohar
 */
private static ProjectTestResults runAllTestSuits(TestProfile testProfile, Techspec techspec, Appspec appspec,
        String filterName, FileFilter fileFilter) throws Exception {
    // prepare tests
    TestPreparationUtil.prepareAllTestSuites(testProfile, techspec, appspec, filterName, fileFilter);

    File suiteTargetDirectory = new File(
            "target" + File.separator + "clickframes" + File.separator + "selenium" + File.separator
                    + ClickframeUtils.convertSlashToPathSeparator(filterName) + File.separator + "tests");

    Properties properties = new Properties();

    properties.put("browser", testProfile.getBrowser());

    properties.put("suite", suiteTargetDirectory.getAbsolutePath());

    if (testProfile.getBaseUrl() != null) {
        properties.put("startURL", testProfile.getBaseUrl());
    }

    File resultsDir = new File(
            "target" + File.separator + "clickframes" + File.separator + "selenium" + File.separator
                    + ClickframeUtils.convertSlashToPathSeparator(filterName) + File.separator + "results");

    FileUtils.deleteDirectory(resultsDir);
    resultsDir.mkdirs();
    properties.put("result", resultsDir.getAbsolutePath());

    // prepare user extensions
    File userExtensionsFile = new File(System.getProperty("java.io.tmpdir"), "user-extensions.js");
    if (userExtensionsFile.exists()) {
        userExtensionsFile.delete();
    }

    IOUtils.copy(TestRunner.class.getResourceAsStream("/user-extensions.js"),
            new FileOutputStream(userExtensionsFile));
    properties.put("userExtensions", userExtensionsFile.getAbsolutePath());

    MultiHTMLSuiteRunner runner = null;

    boolean hasFiles = true;

    if (hasFiles) {
        runner = MultiHTMLSuiteRunner.execute(properties);
    }

    ProjectTestResults projectTestResults = createFrom(runner);

    // serialize the projectTestResults using java serialization
    XMLEncoder e = new XMLEncoder(
            new BufferedOutputStream(new FileOutputStream(new File(resultsDir, "testResults.xml"))));
    e.writeObject(projectTestResults);
    e.close();

    // write test result summary
    writeTestResultSummaryFile(techspec, appspec, projectTestResults, filterName);

    // aggregrateTestResults(techspec, appspec, filterName);

    return projectTestResults;
}

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

/**
 * @param queryInformationSet The Set of QueryInformation to persist to the specified XML file.
 *///from   ww w.j  ava 2  s. c  o m
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();
    }
}