Example usage for javax.xml.xpath XPathFactory newXPath

List of usage examples for javax.xml.xpath XPathFactory newXPath

Introduction

In this page you can find the example usage for javax.xml.xpath XPathFactory newXPath.

Prototype

public abstract XPath newXPath();

Source Link

Document

Return a new XPath using the underlying object model determined when the XPathFactory was instantiated.

Usage

From source file:org.wso2.carbon.identity.application.authentication.endpoint.util.TenantDataManager.java

/**
 * Retrieve latest active tenant domains list
 */// ww  w.  j  a  v  a  2s .com
private static void refreshActiveTenantDomainsList() {

    try {
        String xmlString = getServiceResponse(serviceURL);

        if (StringUtils.isNotEmpty(xmlString)) {

            XPathFactory xpf = XPathFactory.newInstance();
            XPath xpath = xpf.newXPath();

            InputSource inputSource = new InputSource(new StringReader(xmlString));
            String xPathExpression = "/*[local-name() = '" + RETRIEVE_TENANTS_RESPONSE + "']/*[local-name() = '"
                    + RETURN + "']";
            NodeList nodeList = null;
            nodeList = (NodeList) xpath.evaluate(xPathExpression, inputSource, XPathConstants.NODESET);

            // Reset existing tenant domains list
            tenantDomainList.clear();

            // For each loop is not supported for NodeList
            for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);
                if (node != null && node.getNodeType() == Node.ELEMENT_NODE) {
                    Element element = (Element) node;
                    NodeList tenantData = element.getChildNodes();
                    boolean activeChecked = false;
                    boolean domainChecked = false;
                    boolean isActive = false;
                    String tenantDomain = null;

                    // For each loop is not supported for NodeList
                    for (int j = 0; j < tenantData.getLength(); j++) {
                        Node dataItem = tenantData.item(j);
                        String localName = dataItem.getLocalName();

                        if (ACTIVE.equals(localName)) {
                            // Current element has domain status active or inactive
                            activeChecked = true;
                            if (Boolean.parseBoolean(dataItem.getTextContent())) {
                                isActive = true;
                            }
                        }

                        if (TENANT_DOMAIN.equals(localName)) {
                            // Current element has domain name of the tenant
                            domainChecked = true;
                            tenantDomain = dataItem.getTextContent();
                        }

                        if (activeChecked && domainChecked) {
                            if (isActive) {
                                tenantDomainList.add(tenantDomain);

                                if (log.isDebugEnabled()) {
                                    log.debug(tenantDomain + " is active and added to the dropdown list");
                                }
                            } else {
                                if (log.isDebugEnabled()) {
                                    log.debug(tenantDomain + " is inactive and not added to the dropdown list");
                                }
                            }
                            break;
                        }
                    }
                }
            }
            // Sort the list of tenant domains alphabetically
            Collections.sort(tenantDomainList);
        }
    } catch (Exception e) {
        // Catching the general exception as if no tenants are available it should stop processing
        log.error("Retrieving list of active tenant domains failed. Ignore this if there are no tenants : ", e);
    }
}

From source file:org.wso2.carbon.identity.workflow.mgt.WorkflowManagementServiceImpl.java

@Override
public void addAssociation(String associationName, String workflowId, String eventId, String condition)
        throws WorkflowException {

    if (StringUtils.isBlank(workflowId)) {
        log.error("Null or empty string given as workflow id to be associated to event.");
        throw new InternalWorkflowException("Service alias cannot be null");
    }/*from   ww w .  j av a2s  .  c  o m*/
    if (StringUtils.isBlank(eventId)) {
        log.error("Null or empty string given as 'event' to be associated with the service.");
        throw new InternalWorkflowException("Event type cannot be null");
    }

    if (StringUtils.isBlank(condition)) {
        log.error("Null or empty string given as condition expression when associating " + workflowId
                + " to event " + eventId);
        throw new InternalWorkflowException("Condition cannot be null");
    }

    //check for xpath syntax errors
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    try {
        xpath.compile(condition);
        workflowDAO.addAssociation(associationName, workflowId, eventId, condition);
    } catch (XPathExpressionException e) {
        log.error("The condition:" + condition + " is not an valid xpath expression.", e);
        throw new WorkflowRuntimeException("The condition is not a valid xpath expression.");
    }
}

From source file:org.wso2.carbon.identity.workflow.mgt.WorkflowService.java

public void addAssociation(String associationName, String workflowId, String eventId, String condition)
        throws WorkflowException {

    if (StringUtils.isBlank(workflowId)) {
        log.error("Null or empty string given as workflow id to be associated to event.");
        throw new InternalWorkflowException("Service alias cannot be null");
    }//from  w  ww  .j  a  v  a2s .  c o  m
    if (StringUtils.isBlank(eventId)) {
        log.error("Null or empty string given as 'event' to be associated with the service.");
        throw new InternalWorkflowException("Event type cannot be null");
    }

    if (StringUtils.isBlank(condition)) {
        log.error("Null or empty string given as condition expression when associating " + workflowId
                + " to event " + eventId);
        throw new InternalWorkflowException("Condition cannot be null");
    }

    //check for xpath syntax errors
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    try {
        xpath.compile(condition);
        workflowDAO.addAssociation(associationName, workflowId, eventId, condition);
    } catch (XPathExpressionException e) {
        log.error("The condition:" + condition + " is not an valid xpath expression.", e);
        throw new RuntimeWorkflowException("The condition is not a valid xpath expression.");
    }
}

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

private void migrateData(File folder) throws MigrationClientException {
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    DocumentBuilder builder;/*from  w w  w.  j  a v  a 2  s.co  m*/
    Document doc;
    try {
        for (File fileEntry : Objects.requireNonNull(folder.listFiles())) {
            builder = documentBuilderFactory.newDocumentBuilder();
            doc = builder.parse(fileEntry);
            XPathFactory xpathFactory = XPathFactory.newInstance();
            XPath xpath = xpathFactory.newXPath();
            NodeList data = getEncryptedPayload(doc, xpath);
            if (data.getLength() > 0) {
                for (int i = 0; i < data.getLength(); i++) {
                    String newEncryptedPassword = EncryptionUtil
                            .getNewEncryptedValue(data.item(i).getNodeValue());
                    if (StringUtils.isNotEmpty(newEncryptedPassword)) {
                        data.item(i).setNodeValue(newEncryptedPassword);
                    }
                }
                Transformer xformer = TransformerFactory.newInstance().newTransformer();
                xformer.transform(new DOMSource(doc),
                        new StreamResult(new File(fileEntry.getAbsolutePath()).getPath()));
            }
        }

    } catch (Exception e) {
        throw new MigrationClientException(
                "Error occurred while migrating data in folder : " + folder.getAbsolutePath() + " . ", e);
    }

}

From source file:org.wso2.carbon.registry.indexing.utils.RxtUnboundedDataLoadUtils.java

/**
 * This method is used to get unbounded field values in a rxt.
 *
 * @param rxtContent rxt configuration/*from w w  w.  j a  v  a  2s.  c  o m*/
 * @return list of unbounded filed values.
 * @throws RegistryException
 */
public static RxtUnboundedEntryBean getRxtUnboundedEntries(String rxtContent) throws RegistryException {
    RxtUnboundedEntryBean rxtUnboundedEntryBean = new RxtUnboundedEntryBean();
    String mediaType;
    List<String> fields = new ArrayList<>();

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder;
    Document doc;
    try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(rxtContent.getBytes())) {
        builder = factory.newDocumentBuilder();
        if (builder != null) {
            doc = builder.parse(byteArrayInputStream);
            XPathFactory xPathfactory = XPathFactory.newInstance();
            XPath xpath = xPathfactory.newXPath();
            //Get media Type
            XPathExpression expToGetMediaType = xpath.compile(SolrConstants.RXT_ROOT_XPATH);
            Node rxtRootNode = (Node) expToGetMediaType.evaluate(doc, XPathConstants.NODE);
            mediaType = rxtRootNode.getAttributes().getNamedItem(SolrConstants.WORD_TYPE).getTextContent();
            rxtUnboundedEntryBean.setMediaType(mediaType);

            if (StringUtils.isNotEmpty(mediaType)) {
                XPathExpression expr1 = xpath.compile(SolrConstants.UNBOUNDED_TABLE_XPATH);
                NodeList n1 = (NodeList) expr1.evaluate(doc, XPathConstants.NODESET);
                XPathExpression expr2 = xpath.compile(SolrConstants.UNBOUNDED_FIELD_XPATH);
                NodeList n2 = (NodeList) expr2.evaluate(doc, XPathConstants.NODESET);

                // Stop the iteration if no unbounded table entries were found in rxt configuration.
                if (n1.getLength() != 0 || n2.getLength() != 0) {
                    // Add unbounded table values
                    for (int i = 0; i < n1.getLength(); i++) {
                        Node n = n1.item(i);
                        String tableName = n.getAttributes().getNamedItem(SolrConstants.WORD_NAME)
                                .getTextContent();
                        String expr2Text = SolrConstants.UNBOUNDED_TABLE_XPATH_PREFIX + tableName
                                + SolrConstants.UNBOUNDED_TABLE_XPATH_SUFFIX;
                        XPathExpression expr3 = xpath.compile(expr2Text);
                        NodeList n3 = (NodeList) expr3.evaluate(doc, XPathConstants.NODESET);

                        if (n3.getLength() > 0) {
                            for (int j = 0; j < n3.getLength(); j++) {
                                Node node = n3.item(j);
                                fields.add(toCamelCase(tableName) + SolrConstants.UNDERSCORE
                                        + node.getTextContent());
                            }
                        }
                    }
                    // Add unbounded option test field values.
                    for (int k = 0; k < n2.getLength(); k++) {
                        Node node = n2.item(k);
                        String tableName = node.getParentNode().getAttributes()
                                .getNamedItem(SolrConstants.WORD_NAME).getTextContent();
                        if (tableName != null) {
                            fields.add(toCamelCase(tableName) + SolrConstants.UNDERSCORE_ENTRY);
                        }
                    }
                }
            }
        }
        rxtUnboundedEntryBean.setFields(fields);
    } catch (ParserConfigurationException | SAXException | XPathExpressionException | IOException e) {
        throw new RegistryException("Failed to read rxt configuration and filter the unbounded fields", e);
    }
    return rxtUnboundedEntryBean;
}

From source file:org.wso2.developerstudio.eclipse.artifact.bpel.ui.wizard.BPELSecurityWizard.java

/**
 * Removing empty text nodes//w  w  w .ja  v a2s .  c  o  m
 * 
 * @param doc
 * @throws XPathExpressionException
 */
private void removingEmptyTextNodes(Document doc) throws XPathExpressionException {
    XPathFactory xpathFactory = XPathFactory.newInstance();
    // XPath to find empty text nodes.
    XPathExpression xpathExp = xpathFactory.newXPath().compile("//text()[normalize-space(.) = '']");
    NodeList emptyTextNodes = (NodeList) xpathExp.evaluate(doc, XPathConstants.NODESET);

    // Remove each empty text node from document.
    for (int i = 0; i < emptyTextNodes.getLength(); i++) {
        Node emptyTextNode = emptyTextNodes.item(i);
        emptyTextNode.getParentNode().removeChild(emptyTextNode);
    }
}

From source file:org.wso2.ppaas.configurator.tests.ConfiguratorTestManager.java

public String readXML(String resourcePath, String xpathExpression) {

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = null;
    try {/* w w  w .  j  a va2s . c om*/
        String targetFile = ConfiguratorTestManager.class.getResource(PATH_SEP).getPath() + ".." + PATH_SEP
                + CONFIGURATOR_DIR_NAME + PATH_SEP + resourcePath;
        builder = factory.newDocumentBuilder();
        Document doc = builder.parse(targetFile);
        XPathFactory xPathfactory = XPathFactory.newInstance();
        XPath xpath = xPathfactory.newXPath();
        XPathExpression expr = xpath.compile(xpathExpression);
        String value = expr.evaluate(doc, XPathConstants.STRING).toString();
        log.info("Parsed value" + value);
        return value;

    } catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException e) {
        log.error("Error in parsing xml " + e.getMessage());
    }
    return null;
}

From source file:org.wso2.pwprovider.DefaultPasswordProvider.java

private String getDataFromConfigFile(File fileName, String xpath) {

    String nodeValue = null;/*  w w  w .j  a v a  2s  .  c o m*/
    try {
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(fileName);

        XPathFactory xpf = XPathFactory.newInstance();
        XPath xp = xpf.newXPath();
        XPathExpression xpathEx = xp.compile(xpath);

        Node text = (Node) xpathEx.evaluate(doc.getDocumentElement(), XPathConstants.NODE);
        nodeValue = text.getTextContent();
    } catch (Exception e) {
        handleException("Error reading key store data from key-password.xml file ", e);
    }
    return nodeValue;
}

From source file:org.wso2.pwprovider.DefaultPasswordProvider.java

private String getPrimaryKeyData(String xpath) {

    String carbonConfigFile = carbonHome + File.separator + "repository" + File.separator + "conf"
            + File.separator + "carbon.xml";
    String nodeValue = null;// w w w .ja  v a2s. c  om
    try {
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(carbonConfigFile);

        XPathFactory xpf = XPathFactory.newInstance();
        XPath xp = xpf.newXPath();
        XPathExpression xpathEx = xp.compile(xpath);

        Node text = (Node) xpathEx.evaluate(doc.getDocumentElement(), XPathConstants.NODE);
        nodeValue = text.getTextContent();
    } catch (Exception e) {
        handleException("Error reading primary key store data from carbon.xml file ", e);
    }
    return nodeValue;
}

From source file:org.yawlfoundation.yawl.util.DOMUtil.java

public static Node selectSingleNode(Node node, String expression) throws XPathExpressionException {
    XPathFactory factory = XPathFactory.newInstance();
    XPath path = factory.newXPath();
    Object result = path.evaluate(expression, node, XPathConstants.NODE);
    return (Node) result;
}