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: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  av  a2s  .c  om
 *
 * @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.kchine.r.server.RListener.java

public static String[] xmlGet(String url) {
    try {//from   ww  w  .  j  a  v a  2  s .c  o m

        RResponse rresponse = null;
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            XMLDecoder decoder = new XMLDecoder(connection.getInputStream());
            rresponse = (RResponse) decoder.readObject();
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (rresponse == null) {
            return new String[] { "NOK", convertToPrintCommand("Bad URL: " + url) };
        }

        long ref = DirectJNI.getInstance().putObject(rresponse.getValue());
        DirectJNI.getInstance().assignInPrivateEnv("xml.get.result", ref);

        return new String[] { "OK" };
    } catch (Exception e) {
        e.printStackTrace();
        return new String[] { "NOK", convertToPrintCommand(PoolUtils.getStackTraceAsString(e)) };
    }
}

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 {// w w w.j  a  v  a 2 s. 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:org.jtrfp.trcl.gui.ConfigWindow.java

private boolean readSettingsFromFile(File f) {
    try {/*ww  w . j a va 2s.  c o m*/
        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/*from w w w. j av a 2  s.  c o  m*/
 * @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:com.alvermont.terraj.stargen.ui.StargenFrame.java

private void loadMenuItemActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_loadMenuItemActionPerformed
{//GEN-HEADEREND:event_loadMenuItemActionPerformed
    final int choice = this.xmlChooser.showOpenDialog(this);

    if (choice == JFileChooser.APPROVE_OPTION) {
        try {/*  w ww . j a  va2s  .c o  m*/
            final File target = FileUtils.addExtension(this.xmlChooser.getSelectedFile(), ".xml");

            final XMLDecoder decoder = new XMLDecoder(new FileInputStream(target));

            final StargenParameters params = (StargenParameters) decoder.readObject();

            this.parameters = params;
            updateFromParameters(params);
        } catch (IOException ioe) {
            log.error("Error reading file", ioe);

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

From source file:com.alvermont.terraj.fracplanet.ui.AbstractTerrainViewerFrame.java

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

    final int choice = this.xmlChooser.showOpenDialog(this);

    if (choice == JFileChooser.APPROVE_OPTION) {
        try {//from ww  w .  j a v  a  2  s  .c om
            final File target = FileUtils.addExtension(this.xmlChooser.getSelectedFile(), ".xml");

            final XMLDecoder decoder = new XMLDecoder(new FileInputStream(target));

            final AllFracplanetParameters params = (AllFracplanetParameters) decoder.readObject();

            setParameters(params);

            display.setRenderParameters(params.getRenderParameters());
            display.setCameraPosition(params.getRenderParameters().getCameraPosition());
            this.cameraPosDialog.setPositions(params.getCameraPositionParameters().getPositions());

            regenerate();
        } catch (IOException ioe) {
            log.error("Error reading file", ioe);

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

From source file:com.alvermont.terraj.fracplanet.ui.AbstractTerrainViewerFrame.java

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

    final ImportXMLSettingsDialog dialog = new ImportXMLSettingsDialog(this, true);

    try {/* w w  w .j  ava2  s.c  om*/
        dialog.setVisible(true);

        if (dialog.isConfirmed()) {
            log.debug("Import confirmed");

            try {
                final File target = FileUtils.addExtension(dialog.getSelectedFile(), ".xml");

                final XMLDecoder decoder = new XMLDecoder(new FileInputStream(target));

                final AllFracplanetParameters newParams = (AllFracplanetParameters) decoder.readObject();

                final AllFracplanetParameters params = getParameters();

                // set the requested items in the parameters
                if (dialog.isImportTerrain()) {
                    params.setTerrainParameters(newParams.getTerrainParameters());
                }

                if (dialog.isImportRender()) {
                    params.setRenderParameters(newParams.getRenderParameters());
                }

                if (dialog.isImportExport()) {
                    params.setExportParameters(newParams.getExportParameters());
                }

                if (dialog.isImportCamera()) {
                    params.setCameraPositionParameters(newParams.getCameraPositionParameters());
                }

                // ok, update with any changes to the parameters
                setParameters(params);

                display.setRenderParameters(params.getRenderParameters());
                display.setCameraPosition(params.getRenderParameters().getCameraPosition());
                cameraPosDialog.setPositions(params.getCameraPositionParameters().getPositions());

                regenerate();
            } catch (IOException ioe) {
                log.error("Error reading file", ioe);

                JOptionPane.showMessageDialog(this,
                        "Error: " + ioe.getMessage() + "\nCheck log file for full details", "Error Loading",
                        JOptionPane.ERROR_MESSAGE);
            }
        }
    } finally {
        dialog.setVisible(false);
        dialog.dispose();
    }
}

From source file:org.ejbca.ui.web.admin.rainterface.RAInterfaceBean.java

private EndEntityProfile getEEProfileFromByteArray(String profilename, byte[] profileBytes)
        throws AuthorizationDeniedException {

    ByteArrayInputStream is = new ByteArrayInputStream(profileBytes);
    EndEntityProfile eprofile = new EndEntityProfile();
    try {//from  w w w .  j a v a2 s.c o  m
        XMLDecoder decoder = getXMLDecoder(is);

        // Add end entity 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();
        eprofile.loadData(data);

        // Translate cert profile ids that have changed after import
        String availableCertProfiles = "";
        String defaultCertProfile = eprofile.getValue(EndEntityProfile.DEFAULTCERTPROFILE, 0);
        for (String currentCertProfile : (Collection<String>) eprofile.getAvailableCertificateProfileIds()) {
            Integer currentCertProfileId = Integer.parseInt(currentCertProfile);

            if (certificateProfileSession.getCertificateProfile(currentCertProfileId) != null
                    || CertificateProfileConstants.isFixedCertificateProfile(currentCertProfileId)) {
                availableCertProfiles += (availableCertProfiles.equals("") ? "" : ";") + currentCertProfile;
            } else {
                log.warn("End Entity Profile '" + profilename + "' references certificate profile "
                        + currentCertProfile + " that does not exist.");
                if (currentCertProfile.equals(defaultCertProfile)) {
                    defaultCertProfile = "";
                }
            }
        }
        if (availableCertProfiles.equals("")) {
            log.warn(
                    "End Entity Profile only references certificate profile(s) that does not exist. Using ENDUSER profile.");
            availableCertProfiles = "1"; // At least make sure the default profile is available
        }
        if (defaultCertProfile.equals("")) {
            defaultCertProfile = availableCertProfiles.split(";")[0]; // Use first available profile from list as default if original default was missing
        }
        eprofile.setValue(EndEntityProfile.AVAILCERTPROFILES, 0, availableCertProfiles);
        eprofile.setValue(EndEntityProfile.DEFAULTCERTPROFILE, 0, defaultCertProfile);
        // Remove any unknown CA and break if none is left
        String defaultCA = eprofile.getValue(EndEntityProfile.DEFAULTCA, 0);
        String availableCAs = eprofile.getValue(EndEntityProfile.AVAILCAS, 0);
        List<String> cas = Arrays.asList(availableCAs.split(";"));
        availableCAs = "";
        for (String currentCA : cas) {
            Integer currentCAInt = Integer.parseInt(currentCA);
            // The constant ALLCAS will not be searched for among available CAs
            try {
                if (currentCAInt.intValue() != SecConst.ALLCAS) {
                    caSession.getCAInfo(administrator, currentCAInt);
                }
                availableCAs += (availableCAs.equals("") ? "" : ";") + currentCA; // No Exception means CA exists
            } catch (CADoesntExistsException e) {
                log.warn("CA with id " + currentCA
                        + " was not found and will not be used in end entity profile '" + profilename + "'.");
                if (defaultCA.equals(currentCA)) {
                    defaultCA = "";
                }
            }
        }
        if (availableCAs.equals("")) {
            log.error("No CAs left in end entity profile '" + profilename + "'. Using ALLCAs.");
            availableCAs = Integer.toString(SecConst.ALLCAS);
        }
        if (defaultCA.equals("")) {
            defaultCA = availableCAs.split(";")[0]; // Use first available
            log.warn("Changing default CA in end entity profile '" + profilename + "' to " + defaultCA + ".");
        }
        eprofile.setValue(EndEntityProfile.AVAILCAS, 0, availableCAs);
        eprofile.setValue(EndEntityProfile.DEFAULTCA, 0, defaultCA);
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            throw new IllegalStateException("Unknown IOException was caught when closing stream", e);
        }
    }
    return eprofile;
}

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

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

    final int choice = xmlChooser.showOpenDialog(this);

    if (choice == JFileChooser.APPROVE_OPTION) {
        try {/* w w w .java 2 s.  c om*/
            final InputStream target = xmlChooser.getFileContents().getInputStream();

            final XMLDecoder decoder = new XMLDecoder(target);

            final AllPlanetParameters newParams = (AllPlanetParameters) decoder.readObject();

            this.params = newParams;

            updateAllFromParameters();
        } catch (IOException ioe) {
            log.error("Error reading file", ioe);

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