Example usage for javax.xml.parsers DocumentBuilderFactory setFeature

List of usage examples for javax.xml.parsers DocumentBuilderFactory setFeature

Introduction

In this page you can find the example usage for javax.xml.parsers DocumentBuilderFactory setFeature.

Prototype

public abstract void setFeature(String name, boolean value) throws ParserConfigurationException;

Source Link

Document

Set a feature for this DocumentBuilderFactory and DocumentBuilder s created by this factory.

Usage

From source file:org.wso2.carbon.pc.core.assets.common.AssetResource.java

protected Document getXMLDocument(byte[] documentoXml)
        throws IOException, SAXException, ParserConfigurationException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);//from w w w .j  av a  2s  .co m
    factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    return builder.parse(new ByteArrayInputStream(documentoXml));
}

From source file:org.wso2.carbon.pc.core.assets.Process.java

public Document getBpmnResource() throws ProcessCenterException {
    Document BPMNDocument = null;
    DocumentBuilderFactory factory;
    DocumentBuilder builder;//from  w w w .  j av a 2s.com
    String processRegistryPath = ProcessCenterConstants.PROCESS_ASSET_ROOT + processName + "/" + processVersion;
    try {
        RegistryService registryService = ProcessCenterServerHolder.getInstance().getRegistryService();
        if (registryService != null) {
            UserRegistry userRegistry = registryService.getGovernanceUserRegistry(username);
            // Getting process and bpmn resource association
            Association[] processAssociations = userRegistry.getAssociations(processRegistryPath,
                    ProcessCenterConstants.PACKAGE_PROCESS_ASSOCIATION);
            if (processAssociations != null && processAssociations.length > 0) {
                Resource bpmnRegistryResource = userRegistry.get(processAssociations[0].getSourcePath());
                byte[] bpmnContent = (byte[]) bpmnRegistryResource.getContent();
                InputStreamProvider inputStreamProvider = new PCInputStreamProvider(bpmnContent);
                factory = DocumentBuilderFactory.newInstance();
                factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
                builder = factory.newDocumentBuilder();
                BPMNDocument = builder.parse(new InputSource(inputStreamProvider.getInputStream()));
            }
        }
    } catch (RegistryException | ParserConfigurationException | SAXException | IOException e) {
        String errMsg = "Error occurred while getting bpmn resources for process : " + processName + " version "
                + processVersion;
        log.error(errMsg, e);
        throw new ProcessCenterException(errMsg, e);
    }

    return BPMNDocument;
}

From source file:org.wso2.carbon.pc.core.services.ProcessContentSearchService.java

private Document stringToXML(String xmlString) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document document = builder.parse(new InputSource(new StringReader(xmlString)));
    return document;
}

From source file:org.wso2.carbon.pc.core.transfer.ProcessImport.java

/**
 * Add the BPMN file of the imported process into the registry
 *
 * @param processName process name/*w ww .  j a v  a2s . c  o  m*/
 * @param processVersion process version
 * @param processDirPath process directory path
 * @param processAssetPath process path
 * @throws IOException
 * @throws SAXException
 * @throws ParserConfigurationException
 * @throws TransformerException
 * @throws RegistryException
 */
private void setBPMN(String processName, String processVersion, String processDirPath, String processAssetPath)
        throws IOException, SAXException, ParserConfigurationException, TransformerException,
        RegistryException {

    String bpmnFilePathStr = processDirPath + "/" + ProcessCenterConstants.EXPORTED_BPMN_CONTENT_FILE;
    Path bpmnFilePath = Paths.get(bpmnFilePathStr);
    String bpmnMetaDataFilePathStr = processDirPath + "/" + ProcessCenterConstants.EXPORTED_BPMN_META_FILE;
    Path bpmnMetaDataFilePath = Paths.get(bpmnMetaDataFilePathStr);

    if (Files.exists(bpmnFilePath) && Files.exists(bpmnMetaDataFilePath)) {
        //set bpmn content file
        File bpmnXMLFile = new File(bpmnFilePathStr);
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        DocumentBuilder dBuilder = factory.newDocumentBuilder();
        Document doc = dBuilder.parse(bpmnXMLFile);
        String bpmnFileContent = ProcessStore.xmlToString(doc);
        String bpmnContentResourcePath = ProcessCenterConstants.BPMN_CONTENT_PATH + processName + "/"
                + processVersion;
        if (bpmnFileContent != null && bpmnFileContent.length() > 0) {
            Resource bpmnFileResource = reg.newResource();
            bpmnFileResource.setContent(bpmnFileContent);
            bpmnFileResource.setMediaType(MediaType.APPLICATION_XML);
            reg.put(bpmnContentResourcePath, bpmnFileResource);
            reg.addAssociation(bpmnContentResourcePath, processAssetPath,
                    ProcessCenterConstants.ASSOCIATION_TYPE);
        }

        //set bpmn meta data file (contains path of the target bpmn file)
        File bpmnMetaDataXMLFile = new File(bpmnMetaDataFilePathStr);
        Document bpmnMetaDataDoc = dBuilder.parse(bpmnMetaDataXMLFile);
        String bpmnMetaDataContent = ProcessStore.xmlToString(bpmnMetaDataDoc);
        Resource bpmnMetaDataResource = reg.newResource();
        bpmnMetaDataResource.setContent(bpmnMetaDataContent);
        bpmnMetaDataResource.setMediaType(ProcessCenterConstants.WSO2_BPMN_ASSET_MEDIA_TYPE);
        String bpmnMetaDataResPath = ProcessCenterConstants.BPMN_META_DATA_FILE_PATH + processName + "/"
                + processVersion;
        reg.put(bpmnMetaDataResPath, bpmnMetaDataResource);
    }
}

From source file:org.wso2.carbon.policy.mgt.core.util.PolicyManagerUtil.java

public static Document convertToDocument(File file) throws PolicyManagementException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);/*from   w w w.  j av a  2 s  .  c  om*/
    try {
        factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
        factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        DocumentBuilder docBuilder = factory.newDocumentBuilder();
        return docBuilder.parse(file);
    } catch (Exception e) {
        throw new PolicyManagementException("Error occurred while parsing file, while converting "
                + "to a org.w3c.dom.Document : " + e.getMessage(), e);
    }
}

From source file:org.wso2.carbon.policyeditor.PolicyEditorService.java

/**
 * Formats a given unformatted XML string
 *
 * @param xml//from w w w .  ja  v  a2 s . com
 * @return A CDATA wrapped, formatted XML String
 */
public String formatXML(String xml) {

    try {
        // create the factory
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        docFactory.setIgnoringComments(true);
        docFactory.setNamespaceAware(true);
        docFactory.setExpandEntityReferences(false);
        SecurityManager securityManager = new SecurityManager();
        securityManager.setEntityExpansionLimit(ENTITY_EXPANSION_LIMIT);
        docFactory.setAttribute(SECURITY_MANAGER_PROPERTY, securityManager);
        DocumentBuilder docBuilder;
        Document xmlDoc;

        // now use the factory to create the document builder
        docFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        docBuilder = docFactory.newDocumentBuilder();
        docBuilder.setEntityResolver(new CarbonEntityResolver());
        xmlDoc = docBuilder.parse(new ByteArrayInputStream(xml.getBytes(Charsets.UTF_8)));

        OutputFormat format = new OutputFormat(xmlDoc);
        format.setLineWidth(0);
        format.setIndenting(true);
        format.setIndent(2);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        XMLSerializer serializer = new XMLSerializer(baos, format);
        serializer.serialize(xmlDoc);

        xml = baos.toString("UTF-8");

    } catch (ParserConfigurationException pce) {
        throw new IllegalArgumentException("Failed to setup repository: ");
    } catch (Exception e) {
        log.error(e);
    }

    return "<![CDATA[" + xml + "]]>";
}

From source file:org.wso2.carbon.task.ui.internal.TaskManagementHelper.java

/**
 * This method provides a secured document builder which will secure XXE attacks.
 *
 * @param setIgnoreComments whether to set setIgnoringComments in DocumentBuilderFactory.
 * @return DocumentBuilder//from   w ww  . j  a v  a2s .  c o m
 * @throws javax.xml.parsers.ParserConfigurationException
 */
public static DocumentBuilder getSecuredDocumentBuilder(boolean setIgnoreComments)
        throws ParserConfigurationException {
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setIgnoringComments(setIgnoreComments);
    documentBuilderFactory.setNamespaceAware(true);
    documentBuilderFactory.setExpandEntityReferences(false);
    documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    documentBuilderFactory.setXIncludeAware(false);
    org.apache.xerces.util.SecurityManager securityManager = new SecurityManager();
    securityManager.setEntityExpansionLimit(0);
    documentBuilderFactory.setAttribute(Constants.XERCES_PROPERTY_PREFIX + Constants.SECURITY_MANAGER_PROPERTY,
            securityManager);
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    documentBuilder.setEntityResolver(new EntityResolver() {
        @Override
        public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
            throw new SAXException("Possible XML External Entity (XXE) attack. Skipping entity resolving");
        }
    });
    return documentBuilder;
}

From source file:org.wso2.carbon.tools.wsdlvalidator.WsdlValidator.java

/**
 * Securely parse XML document.//from   w w w. ja  v  a  2  s .c  o m
 *
 * @param payload String XML
 * @return XML Document
 * @throws WSDLValidatorException on SAX, IO or parsing error
 */
private Document secureParseXML(String payload) throws WSDLValidatorException {

    Document document;
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    try {
        dbf.setValidating(true);
        dbf.setNamespaceAware(true);

        // Perform namespace processing
        dbf.setFeature("http://xml.org/sax/features/namespaces", true);

        // Validate the document and report validity errors.
        dbf.setFeature("http://xml.org/sax/features/validation", true);

        // Build the grammar but do not use the default attributes and attribute types information it contains.
        dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);

        // Ignore the external DTD completely.
        dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

        DocumentBuilder db = dbf.newDocumentBuilder();
        InputSource inputSource = new InputSource();
        inputSource.setCharacterStream(new StringReader(payload));
        document = db.parse(inputSource);
    } catch (ParserConfigurationException e) {
        throw new WSDLValidatorException("Error parsing XML document", e);
    } catch (SAXException e) {
        throw new WSDLValidatorException("SAX error in processing XML document", e);
    } catch (IOException e) {
        throw new WSDLValidatorException("IO error in processing XML document", e);
    }
    return document;
}

From source file:org.wso2.carbon.utils.CarbonUtils.java

/**
 *
 * @param xmlConfiguration InputStream that carries xml configuration
 * @return returns a InputStream that has evaluated system variables in input
 * @throws CarbonException//from  w  w w .  jav  a 2s.c o m
 */
public static InputStream replaceSystemVariablesInXml(InputStream xmlConfiguration) throws CarbonException {
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder;
    Document doc;
    try {
        documentBuilderFactory.setNamespaceAware(true);
        documentBuilderFactory.setExpandEntityReferences(false);
        documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        SecurityManager securityManager = new SecurityManager();
        securityManager.setEntityExpansionLimit(CarbonConstants.ENTITY_EXPANSION_LIMIT_0);
        documentBuilderFactory.setAttribute(CarbonConstants.SECURITY_MANAGER_PROPERTY, securityManager);
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
        documentBuilder.setEntityResolver(new CarbonEntityResolver());
        doc = documentBuilder.parse(xmlConfiguration);
    } catch (Exception e) {
        throw new CarbonException("Error in building Document", e);
    }
    NodeList nodeList = null;
    if (doc != null) {
        nodeList = doc.getElementsByTagName("*");
    }
    if (nodeList != null) {
        for (int i = 0; i < nodeList.getLength(); i++) {
            resolveLeafNodeValue(nodeList.item(i));
        }
    }
    return toInputStream(doc);
}

From source file:org.wso2.carbon.webapp.authenticator.framework.AuthenticationFrameworkUtil.java

public static Document convertToDocument(File file) throws AuthenticatorFrameworkException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);//from w w w . ja  v a  2 s  . co  m
    try {
        factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
        factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        DocumentBuilder docBuilder = factory.newDocumentBuilder();
        return docBuilder.parse(file);
    } catch (Exception e) {
        throw new AuthenticatorFrameworkException(
                "Error occurred while parsing file, while converting " + "to a org.w3c.dom.Document", e);
    }
}