Example usage for java.beans XMLDecoder XMLDecoder

List of usage examples for java.beans XMLDecoder XMLDecoder

Introduction

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

Prototype

public XMLDecoder(InputSource is) 

Source Link

Document

Creates a new decoder to parse XML archives created by the XMLEncoder class.

Usage

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

@SuppressWarnings("rawtypes")
@Test/*from w  w  w .  j a v  a2s. 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:com.icesoft.applications.faces.address.MatchAddressDB.java

/**
 * Decodes the stored XML wrapper object representation of the address
 * database and maps the entries as MatchCity, MatchState, and MatchZip
 * objects.//from w w  w. j  a  v a2 s.c o  m
 *
 * @see XAddressDataWrapper
 */
private void loadXDB() {

    //each of these contains a city, state, and zip value
    XAddressDataWrapper xData = null;

    //for decoding the wrapper objects
    XMLDecoder xDecode = null;

    try {
        //load andunzip the xml file
        GZIPInputStream in = new GZIPInputStream(MatchAddressDB.class.getResourceAsStream("address.xml.gz"));

        //xml decoding mechanism
        xDecode = new XMLDecoder(new BufferedInputStream(in));
        xData = (XAddressDataWrapper) xDecode.readObject();

    } catch (Exception e) {
        if (log.isDebugEnabled())
            log.debug("Database not found.");
    }

    if (xDecode == null)
        return;

    //loop through every entry in the xml file
    MatchBean city;
    MatchState state;
    MatchZip zip;

    while (xData != null) {

        //create zip, city and state objects
        zip = (MatchZip) zipMap.get((xData.getZip()));

        //new zip
        if (zip == null) {
            zip = new MatchZip(xData.getZip(), xData.getCity(), xData.getState());
            zipMap.put((xData.getZip()), zip);

            city = new MatchCity(xData.getCity(), xData.getState());

            state = (MatchState) stateMap.get((xData.getState()));

            //new state
            if (state == null) {
                state = new MatchState(xData.getState());
                stateMap.put((xData.getState()), state);

            }
            city = state.addCity((MatchCity) city);
            ((MatchCity) city).addZip(zip);
        }
        //get the next encoded object
        try {
            xData = (XAddressDataWrapper) xDecode.readObject();
        }
        //end of file
        catch (ArrayIndexOutOfBoundsException e) {
            if (log.isDebugEnabled())
                log.debug("Reached end of XML file.");
            return;
        }

    }
    //close the XML decoder
    xDecode.close();
}

From source file:org.sakaiproject.tool.gradebook.GradebookArchive.java

/**
 * Read a gradebook archive from an xml input stream.
 *
 * @param xml The input stream containing the serialized gradebook archive
 * @return A gradebook archive object modeling the data in the xml stream
 *//*from w  w  w  .j  a  v a2 s.co m*/
public void readArchive(String xml) {
    ByteArrayInputStream in = new ByteArrayInputStream(xml.getBytes());
    XMLDecoder decoder = new XMLDecoder(new BufferedInputStream(in));
    GradebookArchive archive = (GradebookArchive) decoder.readObject();
    decoder.close();
    this.gradebook = archive.getGradebook();
    this.courseGrade = archive.getCourseGrade();
    this.assignments = archive.getAssignments();
}

From source file:org.settings4j.objectresolver.JavaXMLBeansObjectResolver.java

@Override
protected Object contentToObject(final String key, final Properties properties, final byte[] content,
        final ContentResolver contentResolver) {
    final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(content);
    XMLDecoder encoder = null;//w  w  w . ja va 2 s . c o m
    try {
        encoder = new XMLDecoder(byteArrayInputStream);
        encoder.setExceptionListener(new LogDecoderExceptionListener(key));
        return encoder.readObject();
    } finally {
        if (encoder != null) {
            encoder.close();
        }
    }
}

From source file:com.icesoft.icefaces.tutorial.component.autocomplete.AutoCompleteDictionary.java

private static void init() {
    // Raw list of xml cities.
    List cityList = null;/*from w w w  .j  a  v a  2  s .  com*/

    // load the city dictionary from the compressed xml file.

    // get the path of the compressed file
    HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
    String basePath = session.getServletContext().getRealPath("/WEB-INF/resources");
    basePath += "/city.xml.zip";

    // extract the file
    ZipEntry zipEntry;
    ZipFile zipFile;
    try {
        zipFile = new ZipFile(basePath);
        zipEntry = zipFile.getEntry("city.xml");
    } catch (Exception e) {
        log.error("Error retrieving records", e);
        return;
    }

    // get the xml stream and decode it.
    if (zipFile.size() > 0 && zipEntry != null) {
        try {
            BufferedInputStream dictionaryStream = new BufferedInputStream(zipFile.getInputStream(zipEntry));
            XMLDecoder xDecoder = new XMLDecoder(dictionaryStream);
            // get the city list.
            cityList = (List) xDecoder.readObject();
            dictionaryStream.close();
            zipFile.close();
            xDecoder.close();
        } catch (ArrayIndexOutOfBoundsException e) {
            log.error("Error getting city list, not city objects", e);
            return;
        } catch (IOException e) {
            log.error("Error getting city list", e);
            return;
        }
    }

    // Finally load the object from the xml file.
    if (cityList != null) {
        dictionary = new ArrayList(cityList.size());
        City tmpCity;
        for (int i = 0, max = cityList.size(); i < max; i++) {
            tmpCity = (City) cityList.get(i);
            if (tmpCity != null && tmpCity.getCity() != null) {
                dictionary.add(new SelectItem(tmpCity, tmpCity.getCity()));
            }
        }
        cityList.clear();
        // finally sort the list
        Collections.sort(dictionary, LABEL_COMPARATOR);
    }

}

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

/**
 * @return Reads the Set of QueryInformation from the specified XML file and returns it.
 *///from  w  w  w.ja v  a  2s  . c o m
@SuppressWarnings("unchecked")
protected Set<QueryInformation> readQueryInformationSet() {
    final FileInputStream fis;
    try {
        fis = new FileInputStream(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 BufferedInputStream bis = new BufferedInputStream(fis);
    final XMLDecoder xmlDecoder = new XMLDecoder(bis);
    try {
        return (Set<QueryInformation>) xmlDecoder.readObject();
    } finally {
        xmlDecoder.close();
    }
}

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

/**
 * Reads the timelordData using the default file name.
 *
 * @return a timelordData object as read from file.
 * @throws TimelordDataException indicates an error reading in the file
 *///  w  w w  .j  ava2 s. c o m
public TimelordData readTimelordData() throws TimelordDataException {

    /*
     * Need to do a sed on these two items:
     * net.chaosserver.timetracker.data.TimeTrackerData =
     *     net.chaosserver.timelord.data.TimelordData
     *
     * net.chaosserver.timetracker.data.TimeTrackerTask =
     *     net.chaosserver.timelord.data.TimelordTask
     */
    TimelordData timelordData;

    /*
    File homeDirectory = new File(System.getProperty("user.home"));
    File[] datafile = homeDirectory.listFiles(this);
    */
    File datafile = new File(
            System.getProperty("user.home") + File.separatorChar + DEFAULT_FILENAME + DEFAULT_EXTENSION);

    if (!datafile.exists()) {
        File oldfile = new File(
                System.getProperty("user.home") + File.separatorChar + "TimeTrackerData" + DEFAULT_EXTENSION);

        if (oldfile.exists()) {
            if (log.isInfoEnabled()) {
                log.info("Found older version of the file, " + "running the converstion.");
            }
            try {
                convertTrackerToLord(oldfile, datafile);
            } catch (IOException e) {
                throw new TimelordDataException("Failed to convert file", e);
            }
        }
    }

    if (datafile.exists()) {
        try {
            FileInputStream fileInputStream = new FileInputStream(datafile);
            BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
            XMLDecoder xmlDecoder = new XMLDecoder(bufferedInputStream);
            timelordData = (TimelordData) xmlDecoder.readObject();
            timelordData.setTimelordReaderWriter(this);

            if (log.isInfoEnabled()) {
                log.info("Finished loading [" + datafile + "]");
            }
        } catch (FileNotFoundException e) {
            throw new TimelordDataException("Failed to read", e);
        }
    } else {
        if (log.isInfoEnabled()) {
            log.info("Failed to find [" + datafile + "]");
        }
        timelordData = new TimelordData();
    }

    return timelordData;
}

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

<T> T loadProperty(String name, Class<T> clazz) {
    if (directory == null) {
        return null;
    }//from   www  .  jav a2  s.c  om
    synchronized (directory) {
        try (XMLDecoder decoder = new XMLDecoder(
                new BufferedInputStream(new FileInputStream(new File(directory, name))))) {
            try {
                return clazz.cast(decoder.readObject());
            } catch (ClassCastException ex) {
                Tools.showError(ex);
                return null;
            } catch (Exception ex) {
                //probably user messed up with files
                Tools.showError(ex);
                return null;
            }
        } catch (FileNotFoundException ex) {
            //ignore, we have not saved yet a property with this name
        }
    }
    return null;
}

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

@SuppressWarnings("unchecked")
public void loadIndex() {
    File file = new File(userDir + "/DupFind.index.gz");
    outputPrinter.print("Loading index ... ");
    if (file.exists() && file.isFile()) {
        try (XMLDecoder xdec = new XMLDecoder(new GZIPInputStream(new FileInputStream(file)))) {
            fileIndex.clear();//  w ww  .  ja va 2s.co m
            fileIndex.putAll((Map<String, FileEntry>) xdec.readObject());
            outputPrinter.println("done. " + fileIndex.size() + " files in index.");
        } catch (Exception e) {
            System.err.println(e);
        }
    } else {
        outputPrinter.println("failed. Creating new index.");
        fileIndex.clear();
    }
}

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

private void load(File mappingFile) {
    try {/*from www.  j  av  a 2 s .c  o m*/
        FileInputStream fin = new FileInputStream(mappingFile);

        Utils.lastVisitedDirectory = mappingFile.getPath();
        Utils.lastVisitedMappingDirectory = mappingFile.getPath();
        //Utils.lastMappingFile = mappingFile.getName();
        // Create XML encoder.
        XMLDecoder xdec = new XMLDecoder(fin);

        /* get mapping */
        Mapping mapping = (Mapping) xdec.readObject();

        /* flat files */
        flatFileTabbedPanel.flatFileContainer.flatFiles = new ArrayList();

        for (int i = 0; i < mapping.flatFiles.size(); i++) {
            FlatFileMapping ffm = (FlatFileMapping) mapping.flatFiles.get(i);
            FlatFile f = new FlatFile();
            if (ffm != null) {
                f.lineSeparator = ffm.lineSeparator;
                f.firstLineForTitles = ffm.fisrtLineForTitle;
                f.setSeparators(ffm.getSeparators());

                try {
                    URL url = new File(ffm.getFileURL()).toURL();
                    if (url != null)
                        f.load(url);
                } catch (FileNotFoundException fe) {
                    JOptionPane.showMessageDialog(new JFrame(), "Unable to load file" + ffm.getFileURL(),
                            "[PSI makers: PSI maker] load flat file", JOptionPane.ERROR_MESSAGE);
                }
            }
            treePanel.flatFileTabbedPanel.flatFileContainer.addFlatFile(f);
        }
        treePanel.flatFileTabbedPanel.reload();

        /* dictionaries */
        dictionnaryLists.dictionaries.dictionaries = new ArrayList();

        for (int i = 0; i < mapping.getDictionaries().size(); i++) {
            DictionaryMapping dm = (DictionaryMapping) mapping.getDictionaries().get(i);
            Dictionary d = new Dictionary();

            try {
                URL url = null;
                if (dm.getFileURL() != null)
                    url = new File(dm.getFileURL()).toURL();
                if (url != null)
                    d = new Dictionary(url, dm.getSeparator(), dm.caseSensitive);
                else
                    d = new Dictionary();
            } catch (FileNotFoundException fe) {
                JOptionPane.showMessageDialog(new JFrame(), "Unable to load file" + dm.getFileURL(),
                        "[PSI makers: PSI maker] load dictionnary", JOptionPane.ERROR_MESSAGE);
                d = new Dictionary();
            }
            treePanel.dictionaryPanel.dictionaries.addDictionary(d);
        }
        treePanel.dictionaryPanel.reload();

        /* tree */
        TreeMapping treeMapping = mapping.getTree();

        File schema = new File(treeMapping.getSchemaURL());
        try {
            treePanel.loadSchema(schema);
            ((XsdTreeStructImpl) treePanel.xsdTree).loadMapping(treeMapping);

            treePanel.xsdTree.check();
            treePanel.reload();

            /* set titles for flat files */
            for (int i = 0; i < mapping.flatFiles.size(); i++) {
                try {
                    flatFileTabbedPanel.tabbedPane.setTitleAt(i,
                            ((XsdNode) xsdTree.getAssociatedFlatFiles().get(i)).toString());
                } catch (IndexOutOfBoundsException e) {
                    /** TODO: manage exception */
                }
            }

        } catch (FileNotFoundException fe) {
            JOptionPane.showMessageDialog(new JFrame(), "File not found: " + schema.getName(), "[PSI makers]",
                    JOptionPane.ERROR_MESSAGE);
        } catch (IOException ioe) {
            JOptionPane.showMessageDialog(new JFrame(), "Unable to load file" + ioe.toString(), "[PSI makers]",
                    JOptionPane.ERROR_MESSAGE);
        }
        xdec.close();
        fin.close();
    } catch (FileNotFoundException fe) {
        JOptionPane.showMessageDialog(new JFrame(), "Unable to load mapping" + mappingFile.getName(),
                "[PSI makers: PSI maker] load mapping", JOptionPane.ERROR_MESSAGE);
    } catch (IOException ioe) {
        JOptionPane.showMessageDialog(new JFrame(), "IO error, unable to load mapping",
                "[PSI makers: PSI maker] load mapping", JOptionPane.ERROR_MESSAGE);
    } catch (NoSuchElementException nsee) {
        nsee.printStackTrace();
        JOptionPane.showMessageDialog(new JFrame(), "Unable to load file", "[PSI makers]",
                JOptionPane.ERROR_MESSAGE);
    }

}