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.automation.extensions.jmeter.JMeterTestManager.java

private JMeterResult resultValidator(String fileName) throws Exception {

    JMeterResult result = null;//from   w w w  .ja v a  2  s  .com
    XMLStreamReader parser = null;
    FileInputStream inputStream = null;
    File file = new File(fileName);
    List<String> assertionFailureList;
    List<String> errorList;

    if (file.exists()) {
        try {
            inputStream = new FileInputStream(file);
            parser = XMLInputFactory.newInstance().createXMLStreamReader(inputStream);

            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(file);
            doc.getDocumentElement().normalize();

            errorList = new ArrayList<String>();
            result = new JMeterResult();
            assertionFailureList = new ArrayList<String>();

            NodeList nodeList = doc.getElementsByTagName("httpSample");

            for (int temp = 0; temp < nodeList.getLength(); temp++) {

                String responseMessage;
                String label;
                String name = null;
                String error = null;
                String failure = null;
                String failureMessage = null;

                Node node = nodeList.item(temp);

                responseMessage = node.getAttributes().getNamedItem("s").getTextContent();
                label = node.getAttributes().getNamedItem("lb").getTextContent();

                if ("false".equalsIgnoreCase(responseMessage)) {
                    result.increaseErrorCount();
                    String errorMessage = label + " > " + responseMessage;
                    if (!errorList.contains(errorMessage)) {
                        errorList.add(errorMessage);
                    }
                }

                if (node.getNodeType() == Node.ELEMENT_NODE) {

                    Element element = (Element) node;

                    if (element.getElementsByTagName("name").getLength() != 0) {
                        name = element.getElementsByTagName("name").item(0).getTextContent();
                    }
                    if (element.getElementsByTagName("error").getLength() != 0) {
                        error = element.getElementsByTagName("error").item(0).getTextContent();
                    }
                    if (element.getElementsByTagName("failure").getLength() != 0) {
                        failure = element.getElementsByTagName("failure").item(0).getTextContent();
                    }
                    if (element.getElementsByTagName("failureMessage").getLength() != 0) {
                        failureMessage = element.getElementsByTagName("failureMessage").item(0)
                                .getTextContent();
                    }

                    if ("true".equalsIgnoreCase(failure) || "true".equalsIgnoreCase(error)) {
                        result.increaseFailureCount();
                        String assertionFailure = label + " : " + name + " > " + failureMessage;
                        if (!assertionFailureList.contains(assertionFailure)) {
                            assertionFailureList.add(assertionFailure);
                        }
                    }
                }
            }

            result.setErrorList(errorList);
            result.setAssertList(assertionFailureList);
        } finally {

            if (parser != null) {
                parser.close();
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    ///ignore
                }
            }
        }
    } else {
        throw new FileNotFoundException("Result File is not Created");
    }
    return result;
}

From source file:org.wso2.carbon.core.persistence.PersistenceUtils.java

public static OMElement getResourceDocumentElement(File resourceFile) throws XMLStreamException, IOException {
    OMElement resourceElement;//from   w  ww  .j ava2 s . c o m
    FileInputStream fis = null;
    XMLStreamReader reader = null;

    try {
        fis = FileUtils.openInputStream(resourceFile);
        reader = xif.createXMLStreamReader(fis);

        StAXOMBuilder builder = new StAXOMBuilder(reader);
        resourceElement = builder.getDocumentElement();
        resourceElement.detach();
    } catch (XMLStreamException e) {
        throw new XMLStreamException(e.getMessage(), e);
    } catch (IOException e) {
        throw new IOException(e.getMessage(), e);
    } finally {
        try {
            if (fis != null) {
                fis.close();
            }
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        try {
            if (reader != null) {
                reader.close();
            }
        } catch (XMLStreamException e) {
            log.error(e.getMessage(), e);
        }

    }
    return resourceElement;
}

From source file:org.wso2.carbon.core.transports.util.RequestProcessorUtil.java

/**
 * @param byteArrayOutStream//from   w ww  .  ja va 2  s .c  om
 * @param out
 * @param annotatedXsl
 * @param contextRoot
 * @param annotation         : If annotation is false PI would not be attached.
 */
public static void writeDocument(ByteArrayOutputStream byteArrayOutStream, OutputStream out,
        String annotatedXsl, String contextRoot, boolean annotation) {
    XMLStreamWriter writer;
    ByteArrayInputStream bais = null;
    XMLStreamReader reader = null;
    try {
        bais = new ByteArrayInputStream(byteArrayOutStream.toByteArray());
        reader = XMLInputFactory.newInstance().createXMLStreamReader(bais);
        StAXOMBuilder builder = new StAXOMBuilder(reader);
        OMElement docElem = builder.getDocumentElement();
        writer = XMLOutputFactory.newInstance().createXMLStreamWriter(out);
        if (annotatedXsl != null && annotation) {
            writer.writeProcessingInstruction("xml-stylesheet", "  type=\"text/xsl\" href=\""
                    + (contextRoot.equals("/") ? "" : contextRoot) + "/styles/" + annotatedXsl + "\"");
        }
        docElem.serialize(writer);
        writer.flush();
    } catch (XMLStreamException e) {
        log.error("Error occurred while trying to write processing instruction for attaching "
                + "annotated style sheet", e);
    } finally {
        try {
            if (bais != null) {
                bais.close();
            }
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        try {
            if (reader != null) {
                reader.close();
            }
        } catch (XMLStreamException e) {
            log.error(e.getMessage(), e);
        }

    }
}

From source file:org.wso2.carbon.ei.migration.service.dao.ServerProfileDAO.java

/**
 * Transform the password by new encryption algorithm
 *
 * @param filePath//from   w  w  w  .  j  a v  a 2s. c o  m
 * @throws MigrationClientException
 */
public void transformSPPassword(String filePath) throws MigrationClientException {
    XMLStreamReader parser = null;
    FileInputStream stream = null;
    try {
        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 (Boolean.parseBoolean(element.getAttributeValue(Constant.SECURE_PASSWORD_Q))) {
                String password = element.getAttributeValue(Constant.PASSWORD_Q);
                newEncryptedPassword = Utility.getNewEncryptedValue(password);
                if (StringUtils.isNotEmpty(newEncryptedPassword)) {
                    element.getAttribute(Constant.PASSWORD_Q).setAttributeValue(newEncryptedPassword);
                }
            }
        }
        if (newEncryptedPassword != null) {
            OutputStream outputStream = new FileOutputStream(new File(filePath));
            documentElement.serialize(outputStream);
            isModified = true;
        }
    } catch (XMLStreamException | FileNotFoundException e) {
        new MigrationClientException("Error while writing the file: " + e);
    } catch (CryptoException e) {
        new MigrationClientException("Error while encrypting the password: " + e);
    } finally {
        try {
            if (parser != null) {
                parser.close();
            }
            if (stream != null) {
                try {
                    if (stream != null) {
                        stream.close();
                    }
                } catch (IOException e) {
                    log.error("Error occurred while closing Input stream", e);
                }
            }
        } catch (XMLStreamException ex) {
            log.error("Error while closing XML stream", ex);
        }
    }
}

From source file:org.wso2.carbon.ei.migration.service.migrator.EntitlementMediatorMigrator.java

/**
 * Migrate the password in entitlement mediators
 *
 * @param filePath//from   w ww. j  av  a 2s .  co m
 * @throws MigrationClientException
 */
private void transformEMPassword(String filePath) throws MigrationClientException {
    isModified = false;
    XMLStreamReader parser = null;
    FileInputStream stream = null;
    try {
        log.info("Migrating password in: " + filePath);
        stream = new FileInputStream(filePath);
        parser = XMLInputFactory.newInstance().createXMLStreamReader(stream);
        StAXOMBuilder builder = new StAXOMBuilder(parser);
        OMElement documentElement = builder.getDocumentElement();
        loopAndEncrypt(documentElement.getChildElements());
        if (isModified) {
            OutputStream outputStream = new FileOutputStream(filePath);
            documentElement.serialize(outputStream);
        }
    } catch (XMLStreamException | FileNotFoundException e) {
        throw new MigrationClientException("Error while writing the file: " + e);
    } finally {
        try {
            if (parser != null) {
                parser.close();
            }
            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException e) {
                    log.error("Error occurred while closing Input stream", e);
                }
            }
        } catch (XMLStreamException ex) {
            log.error("Error while closing XML stream", ex);
        }
    }
}

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

/**
 * Encrypt by new algorithm and update the password in the provided file
 *
 * @param filePath/*from   w  w  w .  ja  v  a  2 s .co  m*/
 * @throws FileNotFoundException
 * @throws CryptoException
 */
private void updatePassword(String filePath) throws FileNotFoundException, CryptoException {
    XMLStreamReader parser = null;
    FileInputStream stream = null;
    try {
        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 (Constant.PASSWORD.equals(element.getAttributeValue(Constant.NAME_Q))
                    || Constant.CONNECTION_PASSWORD.equals(element.getAttributeValue(Constant.NAME_Q))) {
                String encryptedPassword = element.getText();
                newEncryptedPassword = Utility.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) {
                try {
                    stream.close();
                } catch (IOException e) {
                    log.error("Error occurred while closing Input stream", e);
                }
            }
        } catch (XMLStreamException ex) {
            log.error("Error while closing XML stream", ex);
        }
    }
}

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

/**
 * Encrypt the security policy password by new algorithm and update
 *
 * @param tenantId//  w ww  .j a v a2 s  .  c o m
 * @throws RegistryException
 * @throws CryptoException
 * @throws XMLStreamException
 */
private void updateSecurityPolicyPassword(int tenantId)
        throws RegistryException, CryptoException, XMLStreamException {
    InputStream resourceContent = null;
    XMLStreamReader parser = null;
    try {
        Registry registry = MigrationServiceDataHolder.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(Constant.CARBON_SEC_CONFIG));

                while (it != null && it.hasNext()) {
                    OMElement secConfig = (OMElement) it.next();
                    Iterator kerberosProperties = secConfig.getChildrenWithName(new QName(Constant.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 (Constant.SERVICE_PRINCIPAL_PASSWORD
                                    .equals(kbProperty.getAttributeValue(Constant.NAME_Q))) {
                                String encryptedPassword = kbProperty.getText();
                                newEncryptedPassword = Utility.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) {
                try {
                    resourceContent.close();
                } catch (IOException e) {
                    log.error("Error occurred while closing Input stream", e);
                }
            }
        } catch (XMLStreamException ex) {
            log.error("Error while closing XML stream", ex);
        }
    }

}

From source file:org.wso2.carbon.email.mgt.config.ConfigBuilder.java

private Config loadEmailConfigFile() {
    String confXml = CarbonUtils.getCarbonConfigDirPath() + File.separator
            + I18nMgtConstants.EMAIL_CONF_DIRECTORY + File.separator + I18nMgtConstants.EMAIL_ADMIN_CONF_FILE;

    Config emailConfig = new EmailNotificationConfig();

    File configfile = new File(confXml);
    if (!configfile.exists()) {
        log.warn("Email Configuration File is not present at: " + confXml);
    }//from   www. j  av a  2 s.c  o 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 configType1 = omElement.getAttributeValue(new QName("type"));
            String configType2 = omElement.getAttributeValue(new QName("display"));
            String configType3 = omElement.getAttributeValue(new QName("locale"));
            String configType4 = omElement.getAttributeValue(new QName("emailContentType"));
            String configFinal = configType1 + "|" + configType2 + "|" + configType3 + "|" + configType4;
            if (StringUtils.isNotBlank(configFinal)) {
                emailConfig.setProperty(configFinal, loadEmailConfig(omElement));
            }

        }
    } catch (XMLStreamException e) {
        log.warn("Error while loading email config. using default configuration", e);
    } catch (FileNotFoundException e) {
        log.warn("Error while loading email config. using default configuration", e);
    } finally {
        try {
            if (parser != null) {
                parser.close();
            }
            if (stream != null) {
                stream.close();
            }
        } catch (XMLStreamException e) {
            log.error("Error while closing XML stream", e);
        } catch (IOException e) {
            log.error("Error while closing input stream", e);
        }
    }
    return emailConfig;

}

From source file:org.wso2.carbon.email.mgt.util.I18nEmailUtil.java

/**
 * @return/*  w  ww  . j  a v  a  2  s .  com*/
 */
public static List<EmailTemplate> getDefaultEmailTemplates() {
    String configFilePath = CarbonUtils.getCarbonConfigDirPath() + File.separator
            + I18nMgtConstants.EMAIL_CONF_DIRECTORY + File.separator + I18nMgtConstants.EMAIL_ADMIN_CONF_FILE;

    List<EmailTemplate> defaultTemplates = new ArrayList<>();
    File configFile = new File(configFilePath);
    if (!configFile.exists()) {
        log.error("Email Configuration File is not present at: " + configFilePath);
    }

    XMLStreamReader xmlStreamReader = null;
    InputStream inputStream = null;
    try {
        inputStream = new FileInputStream(configFile);
        xmlStreamReader = XMLInputFactory.newInstance().createXMLStreamReader(inputStream);
        StAXOMBuilder builder = new StAXOMBuilder(xmlStreamReader);

        OMElement documentElement = builder.getDocumentElement();
        Iterator iterator = documentElement.getChildElements();
        while (iterator.hasNext()) {
            OMElement omElement = (OMElement) iterator.next();
            String type = omElement.getAttributeValue(new QName(I18nMgtConstants.TEMPLATE_TYPE));
            String displayName = omElement
                    .getAttributeValue(new QName(I18nMgtConstants.TEMPLATE_TYPE_DISPLAY_NAME));
            String locale = omElement.getAttributeValue(new QName(I18nMgtConstants.TEMPLATE_LOCALE));
            String contentType = omElement.getAttributeValue(new QName(I18nMgtConstants.TEMPLATE_CONTENT_TYPE));

            Map<String, String> emailContentMap = getEmailContent(omElement);
            String subject = emailContentMap.get(I18nMgtConstants.TEMPLATE_SUBJECT);
            String body = emailContentMap.get(I18nMgtConstants.TEMPLATE_BODY);
            String footer = emailContentMap.get(I18nMgtConstants.TEMPLATE_FOOTER);

            // create the DTO and add to list
            EmailTemplate emailTemplateDTO = new EmailTemplate();
            emailTemplateDTO.setTemplateType(type);
            emailTemplateDTO.setTemplateDisplayName(displayName);
            emailTemplateDTO.setLocale(locale);
            emailTemplateDTO.setEmailContentType(contentType);

            emailTemplateDTO.setSubject(subject);
            emailTemplateDTO.setBody(body);
            emailTemplateDTO.setFooter(footer);

            defaultTemplates.add(emailTemplateDTO);
        }
    } catch (XMLStreamException | FileNotFoundException e) {
        log.warn("Error while loading default templates to the registry.", e);
    } finally {
        try {
            if (xmlStreamReader != null) {
                xmlStreamReader.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
        } catch (XMLStreamException e) {
            log.error("Error while closing XML stream", e);
        } catch (IOException e) {
            log.error("Error while closing input stream", e);
        }
    }

    return defaultTemplates;
}

From source file:org.wso2.carbon.identity.mgt.config.ConfigBuilder.java

private Config loadEmailConfigFile() {

    String confXml = CarbonUtils.getCarbonConfigDirPath() + File.separator
            + IdentityMgtConstants.EMAIL_CONF_DIRECTORY + File.separator
            + IdentityMgtConstants.EMAIL_ADMIN_CONF_FILE;

    Config emailConfig = new EmailNotificationConfig();

    File configfile = new File(confXml);
    if (!configfile.exists()) {
        log.warn("Email Configuration File is not present at: " + confXml);
    }//from   w w w . j a  v  a 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("type"));
            if (configType != null && configType.trim().length() > 0) {
                emailConfig.setProperty(configType, loadEmailConfig(omElement));
            }

        }
    } catch (XMLStreamException | FileNotFoundException e) {
        log.warn("Error while loading email config. using default configuration", e);
    } finally {
        try {
            if (parser != null) {
                parser.close();
            }
        } catch (XMLStreamException e) {
            log.error("Error while closing XML stream", e);
        }
        try {
            if (stream != null) {
                stream.close();
            }
        } catch (IOException e) {
            log.error("Error while closing input stream", e);
        }
    }
    return emailConfig;

}