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.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 {/*  w w  w .j av  a  2  s  .  c  om*/
        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.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.// www  .  j  a  v  a  2s  .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:de.huxhorn.lilith.swing.ApplicationPreferences.java

private void initRecentFiles() {
    File appPath = getStartupApplicationPath();
    File file = new File(appPath, RECENT_FILES_XML_FILENAME);

    if (file.isFile() && this.recentFiles == null) {
        XMLDecoder d = null;
        try {/* ww w.ja  v  a 2 s. co m*/
            d = new XMLDecoder(new BufferedInputStream(new FileInputStream(file)));

            this.recentFiles = transformToList(String.class, d.readObject());
        } catch (Throwable ex) {
            if (logger.isWarnEnabled())
                logger.warn("Exception while loading recentFiles from file '" + file.getAbsolutePath() + "'!",
                        ex);
            IOUtilities.interruptIfNecessary(ex);
        } finally {
            if (d != null) {
                d.close();
            }
        }
    }

    if (this.recentFiles == null) {
        this.recentFiles = new ArrayList<>();
    }
}

From source file:de.huxhorn.lilith.swing.ApplicationPreferences.java

private void initPreviousSearchStrings() {
    File appPath = getStartupApplicationPath();
    File file = new File(appPath, PREVIOUS_SEARCH_STRINGS_XML_FILENAME);

    if (file.isFile() && this.previousSearchStrings == null) {
        XMLDecoder d = null;
        try {// w  w w .j av  a2 s  .  c om
            d = new XMLDecoder(new BufferedInputStream(new FileInputStream(file)));

            this.previousSearchStrings = transformToList(String.class, d.readObject());
        } catch (Throwable ex) {
            if (logger.isWarnEnabled())
                logger.warn("Exception while loading previous search strings from file '"
                        + file.getAbsolutePath() + "'!", ex);
            IOUtilities.interruptIfNecessary(ex);
        } finally {
            if (d != null) {
                d.close();
            }
        }
    }

    if (this.previousSearchStrings == null) {
        this.previousSearchStrings = new ArrayList<>();
    }
}

From source file:de.huxhorn.lilith.swing.ApplicationPreferences.java

private List<PersistentTableColumnModel.TableColumnLayoutInfo> readColumnLayout(File file) {
    XMLDecoder d = null;
    List<PersistentTableColumnModel.TableColumnLayoutInfo> result;
    try {/* w  w  w . j  a  v  a2  s .c  om*/
        d = new XMLDecoder(new BufferedInputStream(new FileInputStream(file)));

        result = transformToList(PersistentTableColumnModel.TableColumnLayoutInfo.class, d.readObject());
    } catch (Throwable ex) {
        if (logger.isInfoEnabled())
            logger.info("Exception while loading layouts from file '{}'':", file.getAbsolutePath(),
                    ex.getMessage());
        result = null;
        IOUtilities.interruptIfNecessary(ex);
    } finally {
        if (d != null) {
            d.close();
        }
    }
    return result;
}

From source file:de.huxhorn.lilith.swing.ApplicationPreferences.java

private void initLevelColors() {
    if (levelColors == null) {
        File appPath = getStartupApplicationPath();
        File levelColorsFile = new File(appPath, LEVEL_COLORS_XML_FILENAME);

        if (levelColorsFile.isFile()) {
            XMLDecoder d = null;
            try {
                d = new XMLDecoder(new BufferedInputStream(new FileInputStream(levelColorsFile)));

                levelColors = transformToMap(LoggingEvent.Level.class, ColorScheme.class, d.readObject());
            } catch (Throwable ex) {
                if (logger.isWarnEnabled())
                    logger.warn("Exception while loading Level-ColorSchemes from file '"
                            + levelColorsFile.getAbsolutePath() + "'!", ex);
                levelColors = null;//from ww w. j a va  2s  .c  o  m
                IOUtilities.interruptIfNecessary(ex);
            } finally {
                if (d != null) {
                    d.close();
                }
            }
        }
    }

    if (levelColors != null && levelColors.size() != DEFAULT_LEVEL_COLOR_SCHEMES.size()) {
        if (logger.isWarnEnabled())
            logger.warn("Reverting Level-ColorSchemes to defaults.");
        levelColors = null;
    }

    if (levelColors == null) {
        levelColors = cloneLevelColors(DEFAULT_LEVEL_COLOR_SCHEMES);
    }
}

From source file:de.huxhorn.lilith.swing.ApplicationPreferences.java

private void initStatusColors() {
    if (statusColors == null) {
        File appPath = getStartupApplicationPath();
        File statusColorsFile = new File(appPath, STATUS_COLORS_XML_FILENAME);

        if (statusColorsFile.isFile()) {
            XMLDecoder d = null;
            try {
                d = new XMLDecoder(new BufferedInputStream(new FileInputStream(statusColorsFile)));

                statusColors = transformToMap(HttpStatus.Type.class, ColorScheme.class, d.readObject());
            } catch (Throwable ex) {
                if (logger.isWarnEnabled())
                    logger.warn("Exception while loading status Status-ColorSchemes from file '"
                            + statusColorsFile.getAbsolutePath() + "'!", ex);
                statusColors = null;/*from   www  .  j a  v a  2  s  .c  o  m*/
                IOUtilities.interruptIfNecessary(ex);
            } finally {
                if (d != null) {
                    d.close();
                }
            }
        }
    }

    if (statusColors != null && statusColors.size() != DEFAULT_STATUS_COLOR_SCHEMES.size()) {
        if (logger.isWarnEnabled())
            logger.warn("Reverting Status-ColorSchemes to defaults.");
        statusColors = null;
    }

    if (statusColors == null) {
        statusColors = cloneStatusColors(DEFAULT_STATUS_COLOR_SCHEMES);
    }
}

From source file:de.huxhorn.lilith.swing.ApplicationPreferences.java

private void initConditions() {
    File appPath = getStartupApplicationPath();
    File conditionsFile = new File(appPath, CONDITIONS_XML_FILENAME);

    if (conditionsFile.isFile()) {
        long lastModified = conditionsFile.lastModified();
        if (conditions != null && lastConditionsModified >= lastModified) {
            if (logger.isDebugEnabled())
                logger.debug("Won't reload conditions.");
            return;
        }/*from  w w w  .ja va 2  s. c o  m*/
        XMLDecoder d = null;
        try {
            d = new XMLDecoder(new BufferedInputStream(new FileInputStream(conditionsFile)));

            conditions = transformToList(SavedCondition.class, d.readObject());
            lastConditionsModified = lastModified;
            if (logger.isDebugEnabled())
                logger.debug("Loaded conditions {}.", conditions);
        } catch (Throwable ex) {
            if (logger.isWarnEnabled())
                logger.warn("Exception while loading conditions from file '" + conditionsFile.getAbsolutePath()
                        + "'!", ex);
            IOUtilities.interruptIfNecessary(ex);
        } finally {
            if (d != null) {
                d.close();
            }
        }
    }

    if (conditions == null) {
        conditions = new ArrayList<>();
    }
}

From source file:org.ejbca.core.protocol.ws.CommonEjbcaWS.java

protected void getCertificateProfileFromID() throws Exception {

    String profilename = "TESTPROFILEFORGETPROFILECOMMAND";

    if (endEntityProfileSession.getEndEntityProfile(profilename) != null) {
        endEntityProfileSession.removeEndEntityProfile(intAdmin, profilename);
    }// w ww . j  a va 2s .c o  m
    if (certificateProfileSession.getCertificateProfile(profilename) != null) {
        certificateProfileSession.removeCertificateProfile(intAdmin, profilename);
    }
    CertificateProfile profile = new CertificateProfile();
    profile.setAllowValidityOverride(true);
    profile.setAllowExtensionOverride(true);
    certificateProfileSession.addCertificateProfile(intAdmin, profilename, profile);
    int profileid = certificateProfileSession.getCertificateProfileId(profilename);

    try {

        try {
            ejbcaraws.getProfile(profileid, "eep");
        } catch (EjbcaException_Exception e) {
            String expectedmsg = "Could not find end entity profile with ID '" + profileid
                    + "' in the database.";
            assertEquals(expectedmsg, e.getMessage());
        }

        byte[] profilebytes = ejbcaraws.getProfile(profileid, "cp");
        java.beans.XMLDecoder decoder = new java.beans.XMLDecoder(
                new java.io.ByteArrayInputStream(profilebytes));
        final Map<?, ?> h = (Map<?, ?>) decoder.readObject();
        decoder.close();

        // Check that the default data are different from the data in the profile we want to retrieve
        profile = new CertificateProfile();
        assertFalse(profile.getAllowValidityOverride());
        assertFalse(profile.getAllowExtensionOverride());

        // Load the data from the retrieved profile and verify that the data is correct
        profile.loadData(h);
        assertTrue(profile.getAllowValidityOverride());
        assertTrue(profile.getAllowExtensionOverride());

    } finally {
        certificateProfileSession.removeCertificateProfile(intAdmin, profilename);
    }

}

From source file:org.ejbca.core.protocol.ws.CommonEjbcaWS.java

protected void getEndEntityProfileFromID() throws Exception {

    String profilename = "TESTPROFILEFORGETPROFILECOMMAND";

    if (endEntityProfileSession.getEndEntityProfile(profilename) != null) {
        endEntityProfileSession.removeEndEntityProfile(intAdmin, profilename);
    }//from   w  w  w  .ja  v a 2s  .  com
    if (certificateProfileSession.getCertificateProfile(profilename) != null) {
        certificateProfileSession.removeCertificateProfile(intAdmin, profilename);
    }
    EndEntityProfile profile = new EndEntityProfile();
    profile.setPrinterName("TestPrinter");
    profile.addField(DnComponents.COMMONNAME);
    profile.setUse(EndEntityProfile.KEYRECOVERABLE, 0, true);
    profile.setValue(EndEntityProfile.KEYRECOVERABLE, 0, EndEntityProfile.TRUE);
    endEntityProfileSession.addEndEntityProfile(intAdmin, profilename, profile);
    int profileid = endEntityProfileSession.getEndEntityProfileId(profilename);

    try {
        try {
            ejbcaraws.getProfile(profileid, "ccp");
        } catch (UnknownProfileTypeException_Exception e) {
            String expectedmsg = "Unknown profile type 'ccp'. Recognized types are 'eep' for End Entity Profiles and 'cp' for Certificate Profiles";
            assertEquals(expectedmsg, e.getMessage());
        }

        try {
            ejbcaraws.getProfile(profileid, "cp");
        } catch (EjbcaException_Exception e) {
            String expectedmsg = "Could not find certificate profile with ID '" + profileid
                    + "' in the database.";
            assertEquals(expectedmsg, e.getMessage());
        }

        byte[] profilebytes = ejbcaraws.getProfile(profileid, "eep");
        java.beans.XMLDecoder decoder = new java.beans.XMLDecoder(
                new java.io.ByteArrayInputStream(profilebytes));
        final Map<?, ?> h = (Map<?, ?>) decoder.readObject();
        decoder.close();

        // Check that the default data are different from the data in the profile we want to retrieve
        profile = new EndEntityProfile();
        assertFalse(StringUtils.equals("TestPrinter", profile.getPrinterName()));
        assertFalse(profile.getUse(EndEntityProfile.KEYRECOVERABLE, 0));

        // Load the data from the retrieved profile and verify that the data is correct
        profile.loadData(h);
        assertEquals("TestPrinter", profile.getPrinterName());
        assertTrue(profile.getUse(EndEntityProfile.KEYRECOVERABLE, 0));

    } finally {
        endEntityProfileSession.removeEndEntityProfile(intAdmin, profilename);
    }

}