Example usage for org.xml.sax InputSource setCharacterStream

List of usage examples for org.xml.sax InputSource setCharacterStream

Introduction

In this page you can find the example usage for org.xml.sax InputSource setCharacterStream.

Prototype

public void setCharacterStream(Reader characterStream) 

Source Link

Document

Set the character stream for this input source.

Usage

From source file:org.slc.sli.sandbox.idp.saml.SamlResponseComposer.java

private byte[] signResponse(String template) {
    try {//w  ww .jav a 2 s .c  o m
        InputSource stringSource = new InputSource();
        stringSource.setCharacterStream(new StringReader(template));

        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        docFactory.setNamespaceAware(true);
        Document unsignedDoc = docFactory.newDocumentBuilder().parse(stringSource);
        Document signedDoc = signer.signSamlAssertion(unsignedDoc);

        // any transforms (indentation, etc) will break the XML Signatures. No touch!
        Transformer trans = TransformerFactory.newInstance().newTransformer();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        trans.transform(new DOMSource(signedDoc), new StreamResult(bos));
        return bos.toByteArray();

    } catch (SAXException e) {
        // holy checked exception list, Batman!
        throw new SamlProcessException(e);
    } catch (IOException e) {
        throw new SamlProcessException(e);
    } catch (ParserConfigurationException e) {
        throw new SamlProcessException(e);
    } catch (GeneralSecurityException e) {
        throw new SamlProcessException(e);
    } catch (TransformerException e) {
        throw new SamlProcessException(e);
    } catch (MarshalException e) {
        throw new SamlProcessException(e);
    } catch (XMLSignatureException e) {
        throw new SamlProcessException(e);
    }
}

From source file:org.sonar.plugins.gosu.sqale.RemediationEffortExtractor.java

private static Document parseXml(File f) throws Exception {
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder;
    documentBuilder = documentBuilderFactory.newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new FileReader(f));
    return documentBuilder.parse(is);
}

From source file:org.webtestingexplorer.state.CustomizedPropertiesElementsState.java

private Map<WebElementIdentifier, Map<String, String>> parseXML(String xmlString) {
    Map<WebElementIdentifier, Map<String, String>> elementProperties = new HashMap<WebElementIdentifier, Map<String, String>>();
    XpathWebElementIdentifier identifier;
    Map<String, String> attributeMap;

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    Document doc = null;/*from   ww w.  j a  va  2  s.  c  o  m*/

    try {
        DocumentBuilder db = dbf.newDocumentBuilder();
        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(xmlString));

        doc = db.parse(is);
    } catch (ParserConfigurationException pce) {
        pce.printStackTrace();
    } catch (SAXException se) {
        se.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }

    if (doc == null) {
        return elementProperties;
    }

    NodeList nl = doc.getElementsByTagName("element");
    if (nl != null && nl.getLength() > 0) {
        // Loop through all elements
        for (int i = 0; i < nl.getLength(); ++i) {
            identifier = null;
            attributeMap = null;
            Element el = (Element) nl.item(i);

            // Get xpath
            NodeList xpaths = el.getElementsByTagName("xpath");
            Element xpathElement = (Element) xpaths.item(0);
            String xpath = getCharacterDataFromElement(xpathElement);
            identifier = new XpathWebElementIdentifier(xpath);

            NodeList attributes = el.getElementsByTagName("attribute");
            if (attributes != null && attributes.getLength() > 0) {
                // Loop through all attributes
                attributeMap = new HashMap<String, String>();
                for (int j = 0; j < attributes.getLength(); ++j) {
                    Element attributeElement = (Element) attributes.item(j);
                    NamedNodeMap attributeNodeMap = attributeElement.getAttributes();
                    for (int m = 0; m < attributeNodeMap.getLength(); ++m) {
                        Node attributeNode = attributeNodeMap.item(m);
                        attributeMap.put(attributeNode.getNodeName(), attributeNode.getNodeValue());
                    }
                } // for
            }

            if (identifier != null && attributeMap != null) {
                elementProperties.put(identifier, attributeMap);
            }
        } // for
    }
    return elementProperties;
}

From source file:org.wso2.carbon.appmgt.impl.utils.SelfSignUpUtil.java

/**
 * load configuration from the registry//from   w ww.  java  2s . c  o  m
 *
 * @param tenantId tenant id
 * @return
 * @throws org.wso2.carbon.appmgt.api.AppManagementException
 */
private static UserRegistrationConfigDTO getSignupConfigurationFromRegistry(int tenantId)
        throws AppManagementException {

    UserRegistrationConfigDTO config = null;
    try {

        Registry registry = ServiceReferenceHolder.getInstance().getRegistryService()
                .getGovernanceSystemRegistry(tenantId);
        if (registry.resourceExists(AppMConstants.SELF_SIGN_UP_CONFIG_LOCATION)) {

            Resource resource = registry.get(AppMConstants.SELF_SIGN_UP_CONFIG_LOCATION);
            // build config from registry resource
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
            DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();

            String configXml = new String((byte[]) resource.getContent());
            InputSource configInputSource = new InputSource();
            configInputSource.setCharacterStream(new StringReader(configXml.trim()));
            Document doc = builder.parse(configInputSource);
            NodeList nodes = doc.getElementsByTagName(AppMConstants.SELF_SIGN_UP_REG_ROOT);
            if (nodes.getLength() > 0) {
                config = new UserRegistrationConfigDTO();
                config.setSignUpDomain(((Element) nodes.item(0))
                        .getElementsByTagName(AppMConstants.SELF_SIGN_UP_REG_DOMAIN_ELEM).item(0)
                        .getTextContent());
                // set tenant admin credentials
                config.setAdminUserName(
                        ((Element) nodes.item(0)).getElementsByTagName(AppMConstants.SELF_SIGN_UP_REG_USERNAME)
                                .item(0).getTextContent());
                config.setAdminPassword(
                        ((Element) nodes.item(0)).getElementsByTagName(AppMConstants.SELF_SIGN_UP_REG_PASSWORD)
                                .item(0).getTextContent());

                config.setSignUpEnabled(Boolean.parseBoolean(
                        ((Element) nodes.item(0)).getElementsByTagName(AppMConstants.SELF_SIGN_UP_REG_ENABLED)
                                .item(0).getTextContent()));

                // iterate through sign-up role list
                Element roleListParent = (Element) ((Element) nodes.item(0))
                        .getElementsByTagName(AppMConstants.SELF_SIGN_UP_REG_ROLES_ELEM).item(0);

                NodeList rolesEl = roleListParent
                        .getElementsByTagName(AppMConstants.SELF_SIGN_UP_REG_ROLE_ELEM);
                for (int i = 0; i < rolesEl.getLength(); i++) {
                    Element tmpEl = (Element) rolesEl.item(i);
                    String tmpRole = tmpEl
                            .getElementsByTagName(AppMConstants.SELF_SIGN_UP_REG_ROLE_NAME_ELEMENT).item(0)
                            .getTextContent();
                    boolean tmpIsExternal = Boolean.parseBoolean(
                            tmpEl.getElementsByTagName(AppMConstants.SELF_SIGN_UP_REG_ROLE_IS_EXTERNAL).item(0)
                                    .getTextContent());
                    String permissions = null;
                    NodeList permissionsNodeList = tmpEl.getElementsByTagName("Permissions");
                    if (permissionsNodeList.item(0) != null) {
                        permissions = permissionsNodeList.item(0).getTextContent();
                    }
                    String[] permissionList = null;
                    permissionList = permissions != null ? permissions.split(",")
                            : new String[] { "/permission/admin/login",
                                    "/permission/admin/manage/webapp/subscribe" };
                    SignUpRole signUpRole = new SignUpRole();
                    signUpRole.setRoleName(tmpRole);
                    signUpRole.setExternalRole(tmpIsExternal);
                    signUpRole.setPermissionsList(permissionList);
                    config.getSignUpRoles().add(signUpRole);
                }
            }
        }
    } catch (RegistryException e) {
        throw new AppManagementException(
                "Error while reading sign-up configuration file in registry location : "
                        + AppMConstants.SELF_SIGN_UP_CONFIG_LOCATION,
                e);
    } catch (ParserConfigurationException e) {
        throw new AppManagementException("Error while building sign-up configuration file in : "
                + AppMConstants.SELF_SIGN_UP_CONFIG_LOCATION, e);
    } catch (SAXException e) {
        throw new AppManagementException(
                "Error while parsing sign-up configuration in : " + AppMConstants.SELF_SIGN_UP_CONFIG_LOCATION,
                e);
    } catch (IOException e) {
        throw new AppManagementException(
                "Error while parsing sign-up configuration in : " + AppMConstants.SELF_SIGN_UP_CONFIG_LOCATION,
                e);
    }
    return config;
}

From source file:org.wso2.carbon.appmgt.migration.client.MigrationClientImpl.java

private String modifySignUpConfiguration(String configXml) throws APPMMigrationException {

    Writer stringWriter = new StringWriter();
    try {// w  w  w  .  ja  v  a  2 s  .  co m
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        InputSource configInputSource = new InputSource();
        configInputSource.setCharacterStream(new StringReader(configXml.trim()));
        Document doc = builder.parse(configInputSource);
        NodeList nodes = doc.getElementsByTagName(AppMConstants.SELF_SIGN_UP_REG_ROOT);
        if (nodes.getLength() > 0) {
            // iterate through sign-up role list
            Element roleListParent = (Element) ((Element) nodes.item(0))
                    .getElementsByTagName(AppMConstants.SELF_SIGN_UP_REG_ROLES_ELEM).item(0);

            NodeList rolesEl = roleListParent.getElementsByTagName(AppMConstants.SELF_SIGN_UP_REG_ROLE_ELEM);
            for (int i = 0; i < rolesEl.getLength(); i++) {
                Element tmpEl = (Element) rolesEl.item(i);
                Element permissionElement = (Element) tmpEl
                        .getElementsByTagName(AppMConstants.SELF_SIGN_UP_REG_ROLE_PERMISSIONS).item(0);
                if (permissionElement == null) {
                    Element externalRole = (Element) tmpEl
                            .getElementsByTagName(AppMConstants.SELF_SIGN_UP_REG_ROLE_IS_EXTERNAL).item(0);
                    Element newElement = doc.createElement(AppMConstants.SELF_SIGN_UP_REG_ROLE_PERMISSIONS);
                    //Set default permissions into config
                    newElement.setTextContent(
                            "/permission/admin/login,/permission/admin/manage/webapp/subscribe");
                    tmpEl.insertBefore(newElement, externalRole);
                }
            }
        }
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.transform(new DOMSource(doc), new StreamResult(stringWriter));

    } catch (SAXException e) {
        handleException("Error occurred while parsing signup configuration.", e);
    } catch (IOException e) {
        handleException("Error occurred while reading the sign up configuration document. "
                + "Please check the existence of signup configuration file in registry.", e);
    } catch (ParserConfigurationException e) {
        handleException("Error occurred while trying to build the signup configuration xml document", e);
    } catch (TransformerException e) {
        handleException("Error occurred while saving modified signup configuration xml document", e);
    }

    return stringWriter.toString();
}

From source file:org.wso2.carbon.core.persistence.metadata.ArtifactMetadataManager.java

public Element loadXMLParameter(String artifactName, ArtifactType artifactType, String propertyName)
        throws ArtifactMetadataException {
    try {//from ww  w. jav a2  s  .  c  o  m
        String param = loadParameter(artifactName, artifactType, propertyName);
        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(param));

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document d = db.parse(is);
        return d.getDocumentElement();
    } catch (Exception e) {
        String message = "Error while loading parameter as XML. artifact - " + artifactName + ", property - "
                + propertyName;
        handleException(message, e);
    }
    return null;
}

From source file:org.wso2.carbon.es.migration.client.ProviderMigrationClient.java

private Document stringToDocument(String strXml)
        throws ParserConfigurationException, SAXException, IOException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(strXml));
    return builder.parse(is);
}

From source file:org.wso2.carbon.identity.application.mgt.defaultsequence.DefaultAuthSeqMgtServiceImpl.java

private void checkUnsupportedXMLElements(String seqConfigXml, String tenantDomain, String errorMsg)
        throws DefaultAuthSeqMgtException {

    List<String> validationMsg = new ArrayList<>();

    if (seqConfigXml != null) {
        try {/*w  w  w.j a  va2  s  .  co m*/
            DocumentBuilder builder = IdentityUtil.getSecuredDocumentBuilderFactory().newDocumentBuilder();
            InputSource src = new InputSource();
            src.setCharacterStream(new StringReader(seqConfigXml));
            Document doc = builder.parse(src);
            if (!doc.getDocumentElement().getNodeName()
                    .equalsIgnoreCase(LocalAndOutboundAuthenticationConfig.class.getSimpleName())) {
                validationMsg.add("Invalid XML element: " + doc.getDocumentElement().getNodeName() + " in the "
                        + "sequence configuration.");
            } else {
                NodeList nodeList = doc.getDocumentElement().getChildNodes();
                for (int i = 0; i < nodeList.getLength(); i++) {
                    Node currentNode = nodeList.item(i);
                    if (currentNode.getNodeType() == Node.ELEMENT_NODE
                            && !currentNode.getNodeName().equals("AuthenticationSteps")
                            && !currentNode.getNodeName().equals("AuthenticationScript")) {
                        validationMsg.add("Invalid XML element: " + currentNode.getNodeName() + " in the "
                                + "sequence configuration.");
                    }
                }
            }
        } catch (ParserConfigurationException | SAXException | IOException e) {
            throw new DefaultAuthSeqMgtServerException(errorMsg, e);
        }
    }

    if (!validationMsg.isEmpty()) {
        log.error(errorMsg + tenantDomain);
        for (String msg : validationMsg) {
            log.error(msg);
        }
        throw new DefaultAuthSeqMgtException(validationMsg.toArray(new String[0]));
    }
}

From source file:org.wso2.carbon.identity.application.mgt.defaultsequence.DefaultAuthSeqMgtServiceImpl.java

private String removeUnsupportedXMLElements(String seqConfigXml) throws DefaultAuthSeqMgtException {

    String updatedSeqConfigXml = null;
    if (seqConfigXml != null) {
        try {/*from  w w  w .  ja  v  a  2 s. co  m*/
            DocumentBuilder builder = IdentityUtil.getSecuredDocumentBuilderFactory().newDocumentBuilder();
            InputSource src = new InputSource();
            src.setCharacterStream(new StringReader(seqConfigXml));
            Document doc = builder.parse(src);
            NodeList nodeList = doc.getDocumentElement().getChildNodes();
            for (int i = 0; i < nodeList.getLength(); i++) {
                Node currentNode = nodeList.item(i);
                if (currentNode.getNodeType() == Node.ELEMENT_NODE
                        && !currentNode.getNodeName().equals("AuthenticationSteps")
                        && !currentNode.getNodeName().equals("AuthenticationScript")) {
                    doc.getDocumentElement().removeChild(currentNode);
                }
            }

            StringWriter stringWriter = new StringWriter();
            Transformer transformer = IdentityUtil.getSecuredTransformerFactory().newTransformer();
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "true");
            transformer.transform(new DOMSource(doc), new StreamResult(stringWriter));
            updatedSeqConfigXml = stringWriter.toString().replaceAll("(?m)^[ \t]*\r?\n", "");
        } catch (ParserConfigurationException | SAXException | IOException | TransformerException e) {
            throw new DefaultAuthSeqMgtServerException("Error when retrieving default authentication sequence",
                    e);
        }
    }
    return updatedSeqConfigXml;
}

From source file:org.wso2.carbon.identity.provisioning.rules.XACMLBasedRuleHandler.java

private boolean evaluateXACMLResponse(String xacmlResponse) throws IdentityProvisioningException {

    try {//from   w  w  w  .ja v  a2s  .  com
        DocumentBuilderFactory documentBuilderFactory = IdentityUtil.getSecuredDocumentBuilderFactory();
        DocumentBuilder db = documentBuilderFactory.newDocumentBuilder();
        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(xacmlResponse));
        Document doc = db.parse(is);

        String decision = "";
        NodeList decisionNode = doc.getDocumentElement()
                .getElementsByTagName(ProvisioningRuleConstanats.XACML_RESPONSE_DECISION_NODE);
        if (decisionNode != null && decisionNode.item(0) != null) {
            decision = decisionNode.item(0).getTextContent();
        }
        if (decision.equalsIgnoreCase(EntitlementPolicyConstants.RULE_EFFECT_PERMIT)
                || decision.equalsIgnoreCase(EntitlementPolicyConstants.RULE_EFFECT_NOT_APPLICABLE)) {
            return true;
        }
    } catch (ParserConfigurationException | SAXException | IOException e) {
        throw new IdentityProvisioningException("Exception occurred while xacmlResponse processing", e);
    }
    return false;
}