Example usage for javax.xml.stream XMLStreamReader close

List of usage examples for javax.xml.stream XMLStreamReader close

Introduction

In this page you can find the example usage for javax.xml.stream XMLStreamReader close.

Prototype

public void close() throws XMLStreamException;

Source Link

Document

Frees any resources associated with this Reader.

Usage

From source file:org.wso2.carbon.identity.oauth2.util.OAuth2Util.java

private static Map<String, String> loadScopeConfigFile() {
    Map<String, String> scopes = new HashMap<>();
    String configDirPath = CarbonUtils.getCarbonConfigDirPath();
    String confXml = Paths.get(configDirPath, "identity", OAuthConstants.OIDC_SCOPE_CONFIG_PATH).toString();
    File configfile = new File(confXml);
    if (!configfile.exists()) {
        log.warn("OIDC scope-claim Configuration File is not present at: " + confXml);
    }//from   w  w w .j  ava  2 s  .  co m

    XMLStreamReader parser = null;
    InputStream stream = null;

    try {
        stream = new FileInputStream(configfile);
        parser = XMLInputFactory.newInstance().createXMLStreamReader(stream);
        StAXOMBuilder builder = new StAXOMBuilder(parser);
        OMElement documentElement = builder.getDocumentElement();
        Iterator iterator = documentElement.getChildElements();
        while (iterator.hasNext()) {
            OMElement omElement = (OMElement) iterator.next();
            String configType = omElement.getAttributeValue(new QName("id"));
            scopes.put(configType, loadClaimConfig(omElement));
        }
    } catch (XMLStreamException e) {
        log.warn("Error while loading scope config.", e);
    } catch (FileNotFoundException e) {
        log.warn("Error while loading email config.", e);
    } finally {
        try {
            if (parser != null) {
                parser.close();
            }
            if (stream != null) {
                IdentityIOStreamUtils.closeInputStream(stream);
            }
        } catch (XMLStreamException e) {
            log.error("Error while closing XML stream", e);
        }
    }
    return scopes;
}

From source file:org.wso2.carbon.is.migration.service.v530.migrator.UserStorePasswordMigrator.java

private void updatePassword(String filePath) throws FileNotFoundException, CryptoException {

    XMLStreamReader parser = null;
    FileInputStream stream = null;
    try {/*from w ww .  ja v a 2  s .c  o  m*/
        log.info("Migrating password in: " + filePath);
        stream = new FileInputStream(filePath);
        parser = XMLInputFactory.newInstance().createXMLStreamReader(stream);
        StAXOMBuilder builder = new StAXOMBuilder(parser);
        OMElement documentElement = builder.getDocumentElement();
        Iterator it = documentElement.getChildElements();
        String newEncryptedPassword = null;
        while (it.hasNext()) {
            OMElement element = (OMElement) it.next();
            if ("true".equals(element.getAttributeValue(new QName("encrypted")))
                    && ("password".equals(element.getAttributeValue(new QName("name")))
                            || "ConnectionPassword".equals(element.getAttributeValue(new QName("name"))))) {
                String encryptedPassword = element.getText();
                newEncryptedPassword = EncryptionUtil.getNewEncryptedUserstorePassword(encryptedPassword);
                if (StringUtils.isNotEmpty(newEncryptedPassword)) {
                    element.setText(newEncryptedPassword);
                }
            }
        }

        if (newEncryptedPassword != null) {
            OutputStream outputStream = new FileOutputStream(filePath);
            documentElement.serialize(outputStream);
        }
    } catch (XMLStreamException ex) {
        log.error("Error while updating password for: " + filePath, ex);
    } finally {
        try {
            if (parser != null) {
                parser.close();
            }
            if (stream != null) {
                IdentityIOStreamUtils.closeInputStream(stream);
            }
        } catch (XMLStreamException ex) {
            log.error("Error while closing XML stream", ex);
        }

    }
}

From source file:org.wso2.carbon.is.migration.service.v530.RegistryDataManager.java

private static Map<String, String> loadScopeConfigFile() throws FileNotFoundException, IdentityException {

    Map<String, String> scopes = new HashMap<>();
    String carbonHome = System.getProperty("carbon.home");
    String confXml = Paths
            .get(carbonHome, new String[] { "repository", "conf", "identity", "oidc-scope-config.xml" })
            .toString();/* w  w  w.  j av  a  2  s  .c o m*/
    File configfile = new File(confXml);
    if (!configfile.exists()) {
        String errMsg = "OIDC scope-claim Configuration File is not present at: " + confXml;
        throw new FileNotFoundException(errMsg);
    }

    XMLStreamReader parser = null;
    FileInputStream stream = null;
    try {
        stream = new FileInputStream(configfile);
        parser = XMLInputFactory.newInstance().createXMLStreamReader(stream);
        StAXOMBuilder builder = new StAXOMBuilder(parser);
        OMElement documentElement = builder.getDocumentElement();
        Iterator iterator = documentElement.getChildElements();

        while (iterator.hasNext()) {
            OMElement omElement = (OMElement) iterator.next();
            String configType = omElement.getAttributeValue(new QName("id"));
            scopes.put(configType, loadClaimConfig(omElement));
        }
    } catch (XMLStreamException ex) {
        throw IdentityException.error("Error while loading scope config.", ex);
    } finally {
        try {
            if (parser != null) {
                parser.close();
            }

            if (stream != null) {
                IdentityIOStreamUtils.closeInputStream(stream);
            }
        } catch (XMLStreamException ex) {
            log.error("Error while closing XML stream", ex);
        }

    }

    return scopes;
}

From source file:org.wso2.carbon.is.migration.service.v550.migrator.UserStorePasswordMigrator.java

private void updatePassword(String filePath) throws FileNotFoundException, CryptoException {

    XMLStreamReader parser = null;
    FileInputStream stream = null;
    try {//from   ww  w . j  ava 2s  . c o m
        log.info("Migrating password in: " + filePath);
        stream = new FileInputStream(filePath);
        parser = XMLInputFactory.newInstance().createXMLStreamReader(stream);
        StAXOMBuilder builder = new StAXOMBuilder(parser);
        OMElement documentElement = builder.getDocumentElement();
        Iterator it = documentElement.getChildElements();
        String newEncryptedPassword = null;
        while (it.hasNext()) {
            OMElement element = (OMElement) it.next();
            if ("password".equals(element.getAttributeValue(new QName("name")))
                    || "ConnectionPassword".equals(element.getAttributeValue(new QName("name")))) {
                String encryptedPassword = element.getText();
                newEncryptedPassword = EncryptionUtil.getNewEncryptedValue(encryptedPassword);
                if (StringUtils.isNotEmpty(newEncryptedPassword)) {
                    element.setText(newEncryptedPassword);
                }
            }
        }

        if (newEncryptedPassword != null) {
            OutputStream outputStream = new FileOutputStream(filePath);
            documentElement.serialize(outputStream);
        }
    } catch (XMLStreamException ex) {
        log.error("Error while updating password for: " + filePath);
    } finally {
        try {
            if (parser != null) {
                parser.close();
            }
            if (stream != null) {
                IdentityIOStreamUtils.closeInputStream(stream);
            }
        } catch (XMLStreamException ex) {
            log.error("Error while closing XML stream", ex);
        }

    }
}

From source file:org.wso2.carbon.is.migration.service.v550.RegistryDataManager.java

private void updateSecurityPolicyPassword(int tenantId)
        throws RegistryException, CryptoException, XMLStreamException {

    InputStream resourceContent = null;
    XMLStreamReader parser = null;

    try {/*from   w  w w  .j  a v a2 s.  co m*/
        Registry registry = IdentityTenantUtil.getRegistryService().getConfigSystemRegistry(tenantId);
        List<String> policyPaths = getSTSPolicyPaths(registry);
        String newEncryptedPassword = null;
        for (String resourcePath : policyPaths) {
            if (registry.resourceExists(resourcePath)) {
                Resource resource = registry.get(resourcePath);
                resourceContent = resource.getContentStream();
                parser = XMLInputFactory.newInstance().createXMLStreamReader(resourceContent);
                StAXOMBuilder builder = new StAXOMBuilder(parser);
                OMElement documentElement = builder.getDocumentElement();
                Iterator it = documentElement.getChildrenWithName(new QName(CARBON_SEC_CONFIG));

                while (it != null && it.hasNext()) {
                    OMElement secConfig = (OMElement) it.next();
                    Iterator kerberosProperties = secConfig.getChildrenWithName(new QName(KERBEROS));
                    Iterator propertySet = null;
                    if ((kerberosProperties != null && kerberosProperties.hasNext())) {
                        propertySet = ((OMElement) kerberosProperties.next()).getChildElements();
                    }
                    if (propertySet != null) {
                        while (propertySet.hasNext()) {
                            OMElement kbProperty = (OMElement) propertySet.next();
                            if (SERVICE_PRINCIPAL_PASSWORD
                                    .equals(kbProperty.getAttributeValue(new QName(NAME)))) {
                                String encryptedPassword = kbProperty.getText();
                                newEncryptedPassword = EncryptionUtil.getNewEncryptedValue(encryptedPassword);
                                if (StringUtils.isNotEmpty(newEncryptedPassword)) {
                                    kbProperty.setText(newEncryptedPassword);
                                }
                            }
                        }
                    }
                }
                if (StringUtils.isNotEmpty(newEncryptedPassword)) {
                    resource.setContent(RegistryUtils.encodeString(documentElement.toString()));
                    registry.beginTransaction();
                    registry.put(resourcePath, resource);
                    registry.commitTransaction();
                }
            }
        }
    } finally {
        try {
            if (parser != null) {
                parser.close();
            }
            if (resourceContent != null) {
                IdentityIOStreamUtils.closeInputStream(resourceContent);
            }
        } catch (XMLStreamException ex) {
            log.error("Error while closing XML stream", ex);
        }
    }

}

From source file:org.wso2.carbon.is.migration.service.v570.migrator.OIDCScopeDataMigrator.java

private Map<String, String> loadScopeConfigFile(File configfile) {

    Map<String, String> scopes = new HashMap<>();
    XMLStreamReader parser = null;
    InputStream stream = null;/* w  w w.  j a  va 2  s  .com*/

    try {
        stream = new FileInputStream(configfile);
        parser = XMLInputFactory.newInstance().createXMLStreamReader(stream);
        StAXOMBuilder builder = new StAXOMBuilder(parser);
        OMElement documentElement = builder.getDocumentElement();
        Iterator iterator = documentElement.getChildElements();
        while (iterator.hasNext()) {
            OMElement omElement = (OMElement) iterator.next();
            String configType = omElement.getAttributeValue(new QName(ID));
            scopes.put(configType, loadClaimConfig(omElement));
        }
    } catch (XMLStreamException e) {
        log.warn(Constant.MIGRATION_LOG + "Error while loading scope config.", e);
    } catch (FileNotFoundException e) {
        log.warn(Constant.MIGRATION_LOG + "Error while loading email config.", e);
    } finally {
        try {
            if (parser != null) {
                parser.close();
            }
            if (stream != null) {
                IdentityIOStreamUtils.closeInputStream(stream);
            }
        } catch (XMLStreamException e) {
            log.error(Constant.MIGRATION_LOG + "Error while closing XML stream", e);
        }
    }
    return scopes;
}

From source file:org.wso2.carbon.registry.synchronization.operation.CheckOutCommand.java

private void dumpToFileSystem(Registry registry, UserInputCallback callback) throws SynchronizationException {
    addedCount = 0;//  ww  w. j  a  v  a2 s .  co  m

    // first try getting the path and confirmed it is a collection
    Resource r;
    try {
        r = registry.get(checkOutPath);
    } catch (Exception e) {
        throw new SynchronizationException(MessageCode.ERROR_IN_DUMPING_NO_RESOURCE_OR_NO_PERMISSION,
                new String[] { "path: " + checkOutPath, "username: " + username });
    }
    if (!(r instanceof Collection)) {
        throw new SynchronizationException(MessageCode.DUMPING_NON_COLLECTION,
                new String[] { "path: " + checkOutPath, "username: " + username });
    }

    // we are doing the checkout through a temp file. (so assumed enough spaces are there)
    File tempFile = null;
    boolean deleteTempFileFailed = false;
    FileWriter writer = null;
    try {
        try {
            tempFile = File.createTempFile(SynchronizationConstants.DUMP_META_FILE_NAME,
                    SynchronizationConstants.META_FILE_EXTENSION);
            try {
                writer = new FileWriter(tempFile);
                // doing the dump
                log.debug("Starting to do registry 'dumpToFileSystem' for : " + checkOutPath + " with : "
                        + tempFile.getName());
                if (dumpLite) {
                    registry.dumpLite(checkOutPath, writer);
                } else {
                    registry.dump(checkOutPath, writer);
                }
                log.debug("Registry 'dumpToFileSystem' completed for : " + checkOutPath + " in : "
                        + tempFile.getName());

            } finally {
                if (writer != null) {
                    writer.close();
                }
            }
        } catch (RegistryException e) {
            throw new SynchronizationException(MessageCode.ERROR_IN_DUMPING_NO_RESOURCE_OR_NO_PERMISSION,
                    new String[] { "path: " + checkOutPath, "username: " + username });
        } catch (IOException e) {
            throw new SynchronizationException(MessageCode.ERROR_IN_CREATING_TEMP_FILE_FOR_DUMP, e);
        }
        // now read the xml stream from the file
        XMLStreamReader xmlReader = null;
        Reader reader = null;
        try {
            try {
                reader = new FileReader(tempFile);
                xmlReader = XMLInputFactory.newInstance().createXMLStreamReader(reader);
                log.debug("Starting registry 'checkOutRecursively' for repository : " + checkOutPath
                        + " with : " + tempFile.getName());
                checkOutRecursively(xmlReader, workingDir, checkOutPath, callback);
                log.debug("Checkout recursively completed for repository : " + checkOutPath + " with : "
                        + tempFile.getName());
            } finally {
                try {
                    if (xmlReader != null) {
                        xmlReader.close();
                    }
                } finally {
                    if (reader != null) {
                        reader.close();
                    }
                }
            }
        } catch (IOException e) {
            throw new SynchronizationException(MessageCode.ERROR_IN_READING_TEMP_FILE_OF_DUMP, e);
        } catch (XMLStreamException e) {
            throw new SynchronizationException(MessageCode.ERROR_IN_READING_STREAM_OF_TEMP_FILE_OF_DUMP, e);
        }
    } finally {
        if (tempFile != null) {
            // Our intention here is to delete the temporary file. We are not bothered whether
            // this operation fails.
            deleteTempFileFailed = !FileUtils.deleteQuietly(tempFile);
        }
    }
    if (deleteTempFileFailed) {
        throw new SynchronizationException(MessageCode.ERROR_IN_CLEANING_UP,
                new String[] { "file path: " + tempFile.getAbsolutePath() });
    }

    if (cleanRegistry && registryUrl == null) {
        Utils.cleanEmbeddedRegistry();
    }
}

From source file:org.wso2.carbon.registry.synchronization.operation.UpdateCommand.java

/**
 * This method will execute the update command utilizing the various parameters passed when
 * creating the instance of the command. This method accepts the users preference to whether a
 * file or directory should be deleted on the filesystem.
 *
 * @param registry the registry instance to be used.
 * @param callback the instance of a callback that can be used to determine the user's
 *                 preference before deleting an existing file or directory during operation. If
 *                 this parameter is null, the default behaviour of deleting the existing file
 *                 will be used./*w  ww .j a  v a2 s. c om*/
 * @return whether file system updated
 *
 * @throws SynchronizationException if the operation failed.
 */
public boolean execute(Registry registry, UserInputCallback callback) throws SynchronizationException {
    if (outputFile != null) {
        throw new SynchronizationException(MessageCode.OUTPUT_FILE_NOT_SUPPORTED);
    }

    // we are doing the update through a temp file. (so assumed enough spaces are there)
    File tempFile = null;
    boolean deleteTempFileFailed = false;
    FileWriter writer = null;
    try {
        try {
            tempFile = File.createTempFile(SynchronizationConstants.DUMP_META_FILE_NAME,
                    SynchronizationConstants.META_FILE_EXTENSION);
            try {
                writer = new FileWriter(tempFile);
                // doing the dump
                log.debug(
                        "Starting to do registry dump for : " + checkOutPath + " with : " + tempFile.getName());
                if (dumpLite) {
                    registry.dumpLite(checkOutPath, writer);
                } else {
                    registry.dump(checkOutPath, writer);
                }
                log.debug("Registry dump completed for : " + checkOutPath + " in : " + tempFile.getName());
            } finally {
                if (writer != null) {
                    writer.close();
                }
            }
        } catch (RegistryException e) {
            throw new SynchronizationException(MessageCode.ERROR_IN_DUMPING_NO_RESOURCE_OR_NO_PERMISSION, e,
                    new String[] { "path: " + checkOutPath, "username: " + username,
                            "registry url: " + registryUrl });
        } catch (IOException e) {
            throw new SynchronizationException(MessageCode.ERROR_IN_CREATING_TEMP_FILE_FOR_DUMP);
        }
        // now read the xml stream from the file
        XMLStreamReader xmlReader = null;
        Reader reader = null;
        try {
            try {
                reader = new FileReader(tempFile);
                xmlReader = XMLInputFactory.newInstance().createXMLStreamReader(reader);
                log.debug("Starting registry 'updateRecursively' for repository : " + checkOutPath + " with : "
                        + tempFile.getName());
                updateRecursively(xmlReader, workingLocation, checkOutPath, callback);
                log.debug("Update recursively completed for repository : " + checkOutPath + " with : "
                        + tempFile.getName());
            } finally {
                try {
                    if (xmlReader != null) {
                        xmlReader.close();
                    }
                } finally {
                    if (reader != null) {
                        reader.close();
                    }
                }
            }
        } catch (IOException e) {
            throw new SynchronizationException(MessageCode.ERROR_IN_READING_TEMP_FILE_OF_DUMP);
        } catch (XMLStreamException e) {
            throw new SynchronizationException(MessageCode.ERROR_IN_READING_STREAM_OF_TEMP_FILE_OF_DUMP);
        }
    } finally {
        if (tempFile != null) {
            // Our intention here is to delete the temporary file. We are not bothered whether
            // this operation fails.
            deleteTempFileFailed = !FileUtils.deleteQuietly(tempFile);
        }
    }
    if (deleteTempFileFailed) {
        throw new SynchronizationException(MessageCode.ERROR_IN_CLEANING_UP,
                new String[] { "file path: " + tempFile.getAbsolutePath() });
    }

    if (cleanRegistry && registryUrl == null) {
        Utils.cleanEmbeddedRegistry();
    }

    return updated;
}

From source file:org.wso2.carbon.reporting.core.utils.CommonUtil.java

/**
 * @param componentName  name of the report requesting component
 * @param reportTemplate name of the template
 * @param registry       Registry//from   w w w  .jav  a  2  s . c o  m
 * @return report template as string
 * @throws ReportingException if failed to get report template
 */
public static String getReportResources(String componentName, String reportTemplate, Registry registry)
        throws ReportingException, XMLStreamException {

    String jrXmlPath;
    if (reportTemplate != null && !"".equals(reportTemplate)) {
        jrXmlPath = ReportConstants.JRXML_PATH + RegistryConstants.PATH_SEPARATOR + reportTemplate + ".jrxml";
    } else {
        throw new ReportingException("Can't generate report without template ");
    }

    Resource resource;
    InputStream reportDefinitionOmStream;

    StAXOMBuilder stAXOMBuilder;
    OMElement reportJrXmlOmElement;
    try {

        resource = registry.get(RegistryUtils.getRelativePathToOriginal(jrXmlPath,
                RegistryConstants.CONFIG_REGISTRY_BASE_PATH));
        reportDefinitionOmStream = resource.getContentStream();

    } catch (RegistryException e) {
        throw new ReportingException(reportTemplate + " getting  failed from " + componentName, e);
    }
    XMLInputFactory xmlInputFactory;
    XMLStreamReader xmlStreamReader = null;
    xmlInputFactory = XMLInputFactory.newInstance();
    try {
        xmlStreamReader = xmlInputFactory.createXMLStreamReader(reportDefinitionOmStream);
        stAXOMBuilder = new StAXOMBuilder(xmlStreamReader);
        reportJrXmlOmElement = stAXOMBuilder.getDocumentElement();
        return reportJrXmlOmElement.toString();
    } catch (XMLStreamException e) {
        throw new ReportingException(reportTemplate + " getting  failed from " + componentName, e);
    } finally {
        if (xmlStreamReader != null) {
            xmlStreamReader.close();
        }
    }

}

From source file:org.wso2.cep.integration.common.utils.CEPIntegrationTest.java

public OMElement loadClasspathResourceXML(String path) throws FileNotFoundException, XMLStreamException {
    OMElement documentElement = null;//from   ww w .j a va 2s  .  c o m
    FileInputStream inputStream = null;
    XMLStreamReader parser = null;
    StAXOMBuilder builder = null;
    File file = new File(path);
    if (file.exists()) {
        try {
            inputStream = new FileInputStream(file);
            parser = XMLInputFactory.newInstance().createXMLStreamReader(inputStream);
            //create the builder
            builder = new StAXOMBuilder(parser);
            //get the root element (in this case the envelope)
            documentElement = builder.getDocumentElement().cloneOMElement();
        } finally {
            if (builder != null) {
                builder.close();
            }
            if (parser != null) {
                try {
                    parser.close();
                } catch (XMLStreamException e) {
                    //ignore
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    //ignore
                }
            }
        }
    } else {
        throw new FileNotFoundException("File does not exist at " + path);
    }
    return documentElement;
}