Example usage for java.beans XMLDecoder readObject

List of usage examples for java.beans XMLDecoder readObject

Introduction

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

Prototype

public Object readObject() 

Source Link

Document

Reads the next object from the underlying input stream.

Usage

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;
    try {//from  w  w w . j  a  va 2 s.c  o m
        encoder = new XMLDecoder(byteArrayInputStream);
        encoder.setExceptionListener(new LogDecoderExceptionListener(key));
        return encoder.readObject();
    } finally {
        if (encoder != null) {
            encoder.close();
        }
    }
}

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

@SuppressWarnings("rawtypes")
@Test/*from ww w  .  j a  v  a 2  s  . co m*/
public void testHashMapStrangeCharsSafe() throws Exception {
    HashMap<String, Comparable> h = new HashMap<String, Comparable>();
    h.put("foo0", Boolean.FALSE);
    h.put("foo1", "\0001\0002fooString");
    h.put("foo2", Integer.valueOf(2));
    h.put("foo3", Boolean.TRUE);
    h.put("foo4", "");
    HashMap<Object, Object> a = new Base64PutHashMap();
    a.putAll(h);

    // 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();
        @SuppressWarnings("unchecked")
        HashMap<Object, Object> c = new Base64GetHashMap(b);
        assertEquals(((Boolean) c.get("foo0")).booleanValue(), false);
        assertEquals(((Boolean) c.get("foo3")).booleanValue(), true);
        assertEquals(((String) c.get("foo1")), "\0001\0002fooString");
        assertEquals(((String) c.get("foo4")), "");
        assertEquals(((Integer) c.get("foo2")).intValue(), 2);

    } catch (ClassCastException e) {
        assertTrue(false);
    }
}

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

@SuppressWarnings("rawtypes")
@Test//  w w w . ja  va  2  s  .c om
public void testHashMapNormalCharsSafe() throws Exception {
    HashMap<String, Comparable> h = new HashMap<String, Comparable>();
    h.put("foo0", Boolean.FALSE);
    h.put("foo1", "fooString");
    h.put("foo2", Integer.valueOf(2));
    h.put("foo3", Boolean.TRUE);
    h.put("foo4", "");
    HashMap<Object, Object> a = new Base64PutHashMap();
    a.putAll(h);

    // 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();
        @SuppressWarnings("unchecked")
        HashMap<Object, Object> c = new Base64GetHashMap(b);
        assertEquals(((Boolean) c.get("foo0")).booleanValue(), false);
        assertEquals(((Boolean) c.get("foo3")).booleanValue(), true);
        assertEquals(((String) c.get("foo4")), "");
        assertEquals(((String) c.get("foo1")), "fooString");
        assertEquals(((Integer) c.get("foo2")).intValue(), 2);

    } catch (ClassCastException e) {
        assertTrue(false);
    }
}

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

@SuppressWarnings("rawtypes")
@Test//from   w ww.  j  a 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: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
 *///from   w w  w. j  ava 2s  . 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.ejbca.extra.db.SubMessages.java

/**
 * Method use by db api to load a persisted submessage
 * @param cACertChain is the CA chain that signed the RA and CAService keystore
 * @param crls could be set to null to disable CRL checking
 *///from   w  w w  .j av  a 2s.c o m
void load(String data, PrivateKey userKey, Collection cACertChain, Collection crls) {
    try {
        submessages.clear();
        java.beans.XMLDecoder decoder = new java.beans.XMLDecoder(
                new java.io.ByteArrayInputStream(data.getBytes("UTF8")));
        isSigned = ((Boolean) decoder.readObject()).booleanValue();
        isEncrypted = ((Boolean) decoder.readObject()).booleanValue();
        byte[] messagedata = Base64.decode(((String) decoder.readObject()).getBytes());
        decoder.close();

        if (isEncrypted) {
            messagedata = ExtRAMsgHelper.decryptData(userKey, messagedata);
        }

        if (isSigned) {
            ParsedSignatureResult result = ExtRAMsgHelper.verifySignature(cACertChain, crls, messagedata);
            if (!result.isValid()) {
                throw new SignatureException("Signature not valid");
            }
            this.signerCert = result.getSignerCert();
            messagedata = result.getContent();
        }

        ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(messagedata));
        ArrayList<HashMap> savearray = (ArrayList<HashMap>) ois.readObject();

        Iterator<HashMap> iter = savearray.iterator();
        while (iter.hasNext()) {
            HashMap map = iter.next();
            ISubMessage submessage = SubMessageFactory.createInstance(map);
            submessage.loadData(map);
            submessages.add(submessage);
        }
        ois.close();
    } catch (Exception e) {
        log.error("Error reading persistent SubMessages.", e);
    }
}

From source file:psidev.psi.mi.filemakers.xmlMaker.structure.FlatFile.java

public void load(XMLDecoder ois) {
    firstLineForTitles = ((Boolean) ois.readObject()).booleanValue();
    lineSeparator = (String) ois.readObject();
    /** TODO: if file not found -> open a filechooser */
    separators = (HashMap<String, String>) ois.readObject();
    String filePath = (String) ois.readObject();
}

From source file:psidev.psi.mi.filemakers.xmlFlattener.XmlFlattenerGui.java

public void load() {
    try {//from  w  ww  .j av  a2s .  c  om
        String directory = Utils.lastVisitedMappingDirectory;
        if (directory == null)
            directory = Utils.lastVisitedDirectory;

        JFileChooser fc = new JFileChooser(directory);

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

        Utils.lastVisitedDirectory = fc.getSelectedFile().getPath();
        Utils.lastVisitedMappingDirectory = fc.getSelectedFile().getPath();

        try {
            FileInputStream fin = new FileInputStream(fc.getSelectedFile());

            JAXBContext jaxbContext = JAXBContext.newInstance(TreeMapping.class);
            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            TreeMapping treeMapping = (TreeMapping) jaxbUnmarshaller.unmarshal(fin);
            ((XsdTreeStructImpl) treePanel.xsdTree).loadMapping(treeMapping);
            fin.close();
        } catch (JAXBException jbe) {
            System.out.println("Not a JAXB file, try with old format");
            FileInputStream fin = new FileInputStream(fc.getSelectedFile());
            // Create XML encoder.
            XMLDecoder xdec = new XMLDecoder(fin);
            /* get mapping */
            TreeMapping treeMapping = (TreeMapping) xdec.readObject();
            ((XsdTreeStructImpl) treePanel.xsdTree).loadMapping(treeMapping);
            xdec.close();
            fin.close();
        }

        /* tree */

        treePanel.updatePreview();

        treePanel.setTreeSelectionListener();
        treePanel.setCellRenderer();
        treePanel.xsdTree.check();
        treePanel.reload();
    } catch (FileNotFoundException fe) {
        treePanel.xsdTree.getMessageManager().sendMessage("unable to load mapping file (file not found)",
                MessageManagerInt.errorMessage);
        log.error("unable to load mapping file", fe);
    } catch (IOException ex) {
        treePanel.xsdTree.getMessageManager().sendMessage(
                "unable to load mapping file (unable to read the file, IO exception)",
                MessageManagerInt.errorMessage);
        log.error("unable to load mapping file", ex);
    } catch (SAXException ex) {
        treePanel.xsdTree.getMessageManager().sendMessage(
                "unable to load mapping file (problem for parsing the XML file)",
                MessageManagerInt.errorMessage);
        log.error("xml problem", ex);
    } catch (NoSuchElementException ex) {
        treePanel.xsdTree.getMessageManager().sendMessage(
                "unable to load mapping file (an element is missing in the mapping file, maybe this file is too old and not compatible anymore)",
                MessageManagerInt.errorMessage);
        log.error("xml problem", ex);
    } catch (ClassCastException ex) {
        treePanel.xsdTree.getMessageManager().sendMessage(
                "unable to load mapping file (it doesn't seem to be a mapping file)",
                MessageManagerInt.errorMessage);
        log.error("xml problem", ex);
    }
}

From source file:com.jk.framework.util.FakeRunnable.java

/**
 * To object.//ww  w  .j av a  2s. c o  m
 *
 * @param xml
 *            the xml
 * @return the object
 */
// ////////////////////////////////////////////////////////////////////
public static Object toObject(final String xml) {
    // XStream x = createXStream();
    // return x.fromXML(xml);
    // try {
    final ByteArrayInputStream out = new ByteArrayInputStream(xml.getBytes());
    final XMLDecoder encoder = new XMLDecoder(out);
    final Object object = encoder.readObject();
    //
    encoder.close();
    return object;
    // } catch (Exception e) {
    // System.err.println("Failed to decode object : \n" + xml);
    // return null;
    // }
    // return null;
}

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

private void load(File mappingFile) {
    try {//from w w  w  . j ava 2s . 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);
    }

}