Example usage for java.beans XMLDecoder close

List of usage examples for java.beans XMLDecoder close

Introduction

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

Prototype

public void close() 

Source Link

Document

This method closes the input stream associated with this stream.

Usage

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

@SuppressWarnings("rawtypes")
@Test/*from   w ww.  java2 s.  c  om*/
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:edu.wisc.my.portlets.bookmarks.dao.file.FileSystemBookmarkStore.java

/**
 * @see edu.wisc.my.portlets.bookmarks.dao.BookmarkStore#getBookmarkSet(java.lang.String, java.lang.String)
 *//*from www .  j  av  a 2 s. c  om*/
public BookmarkSet getBookmarkSet(String owner, String name) {
    final File storeFile = this.getStoreFile(owner, name);

    //Ok if the file doesn't exist, the user hasn't stored one yet.
    if (!storeFile.exists()) {
        return null;
    }

    try {
        final FileInputStream fis = new FileInputStream(storeFile);
        final BufferedInputStream bis = new BufferedInputStream(fis);
        final XMLDecoder d = new XMLDecoder(bis);

        try {
            final BookmarkSet bs = (BookmarkSet) d.readObject();
            return bs;
        } finally {
            d.close();
        }
    } catch (FileNotFoundException fnfe) {
        final String errorMsg = "Error reading BookmarkSet for owner='" + owner + "', name='" + name
                + "' from file='" + storeFile + "'";
        logger.error(errorMsg, fnfe);
        throw new DataAccessResourceFailureException(errorMsg);
    }
}

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

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
 *///w  ww.  ja v 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:com.jk.framework.util.FakeRunnable.java

/**
 * To object.//from  w  w  w .j  a v a  2 s  .  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.xmlFlattener.XmlFlattenerGui.java

public void load() {
    try {/*from  w  w w  .  j a v  a  2 s.co  m*/
        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:org.jtrfp.trcl.gui.ConfigWindow.java

private boolean readSettingsFromFile(File f) {
    try {/*w ww  .  ja  va  2s  .  c om*/
        FileInputStream is = new FileInputStream(f);
        XMLDecoder xmlDec = new XMLDecoder(is);
        xmlDec.setExceptionListener(new ExceptionListener() {
            @Override
            public void exceptionThrown(Exception e) {
                e.printStackTrace();
            }
        });
        TRConfiguration src = (TRConfiguration) xmlDec.readObject();
        xmlDec.close();
        if (config != null)
            BeanUtils.copyProperties(config, src);
        else
            config = src;
    } catch (Exception e) {
        JOptionPane.showMessageDialog(this, "Failed to read the specified file:\n" + e.getLocalizedMessage(),
                "File read failure", JOptionPane.ERROR_MESSAGE);
        return false;
    }
    return true;
}

From source file:org.latticesoft.util.common.FileUtil.java

/**
 * Reads an object from a xml file// w w  w. j a  v a 2s.  com
 * @param filename the filename to read from
 * @return the object
 */
public static Object readFromXmlFile(String filename) {
    if (filename == null) {
        return null;
    }
    XMLDecoder decoder = null;
    Object o = null;
    try {
        decoder = new XMLDecoder(new BufferedInputStream(new FileInputStream(filename)));
        o = decoder.readObject();
    } catch (Exception e) {
    } finally {
        try {
            decoder.close();
        } catch (Exception e) {
        }
    }
    return o;
}

From source file:org.ejbca.ui.web.admin.certprof.CertProfilesBean.java

private CertificateProfile getCertProfileFromByteArray(String profilename, byte[] profileBytes)
        throws AuthorizationDeniedException {
    ByteArrayInputStream is = new ByteArrayInputStream(profileBytes);
    CertificateProfile cprofile = new CertificateProfile();
    try {//from   w w  w .j a v  a  2s.c  o m
        XMLDecoder decoder = getXMLDecoder(is);
        // Add certificate profile
        Object data = null;
        try {
            data = decoder.readObject();
        } catch (IllegalArgumentException e) {
            if (log.isDebugEnabled()) {
                log.debug("IllegalArgumentException parsing certificate profile data: " + e.getMessage());
            }
            return null;
        }
        decoder.close();
        cprofile.loadData(data);

        // Make sure CAs in profile exist
        List<Integer> cas = cprofile.getAvailableCAs();
        ArrayList<Integer> casToRemove = new ArrayList<Integer>();
        for (Integer currentCA : cas) {
            // If the CA is not ANYCA and the CA does not exist, remove it from the profile before import
            if (currentCA != CertificateProfile.ANYCA) {
                try {
                    getEjbcaWebBean().getEjb().getCaSession().getCAInfo(getAdmin(), currentCA);
                } catch (CADoesntExistsException e) {
                    casToRemove.add(currentCA);
                }
            }
        }
        for (Integer toRemove : casToRemove) {
            log.warn("Warning: CA with id " + toRemove
                    + " was not found and will not be used in certificate profile '" + profilename + "'.");
            cas.remove(toRemove);
        }
        if (cas.size() == 0) {
            log.error("Error: No CAs left in certificate profile '" + profilename
                    + "' and no CA specified on command line. Using ANYCA.");
            cas.add(Integer.valueOf(CertificateProfile.ANYCA));

        }
        cprofile.setAvailableCAs(cas);
        // Remove and warn about unknown publishers
        List<Integer> publishers = cprofile.getPublisherList();
        ArrayList<Integer> allToRemove = new ArrayList<Integer>();
        for (Integer publisher : publishers) {
            BasePublisher pub = null;
            try {
                pub = getEjbcaWebBean().getEjb().getPublisherSession().getPublisher(getAdmin(), publisher);
            } catch (Exception e) {
                log.warn("Warning: There was an error loading publisher with id " + publisher
                        + ". Use debug logging to see stack trace: " + e.getMessage());
                log.debug("Full stack trace: ", e);
            }
            if (pub == null) {
                allToRemove.add(publisher);
            }
        }
        for (Integer toRemove : allToRemove) {
            log.warn("Warning: Publisher with id " + toRemove
                    + " was not found and will not be used in certificate profile '" + profilename + "'.");
            publishers.remove(toRemove);
        }
        cprofile.setPublisherList(publishers);

    } finally {
        try {
            is.close();
        } catch (IOException e) {
            throw new IllegalStateException("Unknown IOException was caught when closing stream", e);
        }
    }
    return cprofile;
}

From source file:de.willuhn.jameica.hbci.io.csv.ProfileUtil.java

/**
 * Laedt die vorhandenen Profile fuer das Format.
 * @param format das Format.//from w  w  w. j  a  va 2 s .  c  o m
 * @return die Liste der Profile.
 */
public static List<Profile> read(Format format) {
    List<Profile> result = new ArrayList<Profile>();

    if (format == null) {
        Logger.warn("no format given");
        Application.getMessagingFactory().sendMessage(
                new StatusBarMessage(i18n.tr("Kein Format ausgewhlt"), StatusBarMessage.TYPE_ERROR));
        return result;
    }

    final Profile dp = format.getDefaultProfile();
    result.add(dp); // System-Profil wird immer vorn einsortiert

    // 1. Mal schauen, ob wir gespeicherte Profil fuer das Format haben
    File dir = new File(Application.getPluginLoader().getPlugin(HBCI.class).getResources().getWorkPath(),
            "csv");
    if (!dir.exists())
        return result;

    File file = new File(dir, format.getClass().getName() + ".xml");
    if (!file.exists() || !file.canRead())
        return result;

    Logger.info("reading csv profile " + file);
    XMLDecoder decoder = null;
    try {
        decoder = new XMLDecoder(new BufferedInputStream(new FileInputStream(file)));
        decoder.setExceptionListener(new ExceptionListener() {
            public void exceptionThrown(Exception e) {
                throw new RuntimeException(e);
            }
        });

        // Es ist tatsaechlich so, dass "readObject()" nicht etwa NULL liefert, wenn keine Objekte mehr in der
        // Datei sind sondern eine ArrayIndexOutOfBoundsException wirft.
        try {
            for (int i = 0; i < 1000; ++i) {
                Profile p = (Profile) decoder.readObject();
                // Migration aus der Zeit vor dem Support mulitpler Profile:
                // Da konnte der User nur das eine existierende Profil aendern, es wurde automatisch gespeichert
                // Das hatte gar keinen Namen. Falls also ein Profil ohne Name existiert (inzwischen koennen keine
                // mehr ohne Name gespeichert werden), dann ist es das vom User geaenderte Profil. Das machen wir
                // automatisch zum ersten User-spezifischen Profil
                if (StringUtils.trimToNull(p.getName()) == null) {
                    p.setName(dp.getName() + " 2");
                    p.setSystem(false);
                }
                result.add(p);
            }
        } catch (ArrayIndexOutOfBoundsException e) {
            // EOF
        }

        Logger.info("read " + (result.size() - 1) + " profiles from " + file);
        Collections.sort(result);

        // Der User hat beim letzten Mal eventuell nicht alle Spalten zugeordnet.
        // Die wuerden jetzt hier in dem Objekt fehlen. Daher nehmen wir
        // noch die Spalten aus dem Default-Profil und haengen die fehlenden noch an.
    } catch (Exception e) {
        Logger.error("unable to read profile " + file, e);
        Application.getMessagingFactory().sendMessage(new StatusBarMessage(
                i18n.tr("Laden der Profile fehlgeschlagen: {0}", e.getMessage()), StatusBarMessage.TYPE_ERROR));
    } finally {
        if (decoder != null) {
            try {
                decoder.close();
            } catch (Exception e) {
                /* useless */}
        }
    }
    return result;
}