Search in sources :

Example 66 with XPath

use of javax.xml.xpath.XPath in project uPortal by Jasig.

the class PositionManager method isNotReparentable.

/**
 * Return true if the passed in node or any downstream (higher index) siblings <strong>relative
 * to its destination location</strong> have moveAllowed="false".
 */
private static boolean isNotReparentable(NodeInfo ni, Element compViewParent, Element positionSet) {
    // This one is easy -- can't re-parent a node with dlm:moveAllowed=false
    if (ni.getNode().getAttribute(Constants.ATT_MOVE_ALLOWED).equals("false")) {
        return true;
    }
    try {
        /*
             *  Annoying to do in Java, but we need to find our own placeholder
             *  element in the positionSet
             */
        final XPathFactory xpathFactory = XPathFactory.newInstance();
        final XPath xpath = xpathFactory.newXPath();
        final String findPlaceholderXpath = ".//*[local-name()='position' and @name='" + ni.getId() + "']";
        final XPathExpression findPlaceholder = xpath.compile(findPlaceholderXpath);
        final NodeList findPlaceholderList = (NodeList) findPlaceholder.evaluate(positionSet, XPathConstants.NODESET);
        switch(findPlaceholderList.getLength()) {
            case 0:
                LOG.warn("Node not found for XPathExpression=\"" + findPlaceholderXpath + "\" in positionSet=" + XmlUtilitiesImpl.toString(positionSet));
                return true;
            case 1:
                // This is healthy
                break;
            default:
                LOG.warn("More than one node found for XPathExpression=\"" + findPlaceholderXpath + "\" in positionSet=" + XmlUtilitiesImpl.toString(positionSet));
                return true;
        }
        // At last
        final Element placeholder = (Element) findPlaceholderList.item(0);
        for (Element nextPlaceholder = (Element) placeholder.getNextSibling(); // As long as we have a placeholder to look at
        nextPlaceholder != null; nextPlaceholder = (Element) nextPlaceholder.getNextSibling()) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Considering whether node ''" + ni.getId() + "' is Reparentable;  subsequent sibling is:  " + nextPlaceholder.getAttribute("name"));
            }
            /*
                 * Next task:  we have to find the non-placeholder representation of
                 * the nextSiblingPlaceholder within the compViewParent
                 */
            final String unmaskPlaceholderXpath = ".//*[@ID='" + nextPlaceholder.getAttribute("name") + "']";
            final XPathExpression unmaskPlaceholder = xpath.compile(unmaskPlaceholderXpath);
            final NodeList unmaskPlaceholderList = (NodeList) unmaskPlaceholder.evaluate(compViewParent, XPathConstants.NODESET);
            switch(unmaskPlaceholderList.getLength()) {
                case 0:
                    // to a node that has been moved to this context (afaik)
                    continue;
                case 1:
                    final Element nextSibling = (Element) unmaskPlaceholderList.item(0);
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Considering whether node ''" + ni.getId() + "' is Reparentable;  subsequent sibling '" + nextSibling.getAttribute("ID") + "' has dlm:moveAllowed=" + !nextSibling.getAttribute(Constants.ATT_MOVE_ALLOWED).equals("false"));
                    }
                    // Need to perform some checks...
                    if (nextSibling.getAttribute(Constants.ATT_MOVE_ALLOWED).equals("false")) {
                        /*
                             *  The following check is a bit strange;  it seems to verify
                             *  that the current NodeInfo and the nextSibling come from the
                             *  same fragment.  If they don't, the re-parenting is allowable.
                             *  I believe this check could only be unsatisfied in the case
                             *  of tabs.
                             */
                        Precedence p = Precedence.newInstance(nextSibling.getAttribute(Constants.ATT_FRAGMENT));
                        if (ni.getPrecedence().isEqualTo(p)) {
                            return true;
                        }
                    }
                    break;
                default:
                    LOG.warn("More than one node found for XPathExpression=\"" + unmaskPlaceholderXpath + "\" in compViewParent");
                    return true;
            }
        }
    } catch (XPathExpressionException xpe) {
        throw new RuntimeException("Failed to evaluate XPATH", xpe);
    }
    // Re-parenting is "not disallowed" (double-negative less readable)
    return false;
}
Also used : XPath(javax.xml.xpath.XPath) XPathExpression(javax.xml.xpath.XPathExpression) XPathFactory(javax.xml.xpath.XPathFactory) XPathExpressionException(javax.xml.xpath.XPathExpressionException) NodeList(org.w3c.dom.NodeList) Element(org.w3c.dom.Element)

Example 67 with XPath

use of javax.xml.xpath.XPath in project openremote by openremote.

the class DOMParser method createXPath.

public XPath createXPath(XPathFactory factory, NamespaceContext nsContext) {
    XPath xpath = factory.newXPath();
    xpath.setNamespaceContext(nsContext);
    return xpath;
}
Also used : XPath(javax.xml.xpath.XPath)

Example 68 with XPath

use of javax.xml.xpath.XPath in project hale by halestudio.

the class INSPIRECodeListReader method parse.

private boolean parse(Document doc, URI location, IOReporter reporter) throws Exception {
    XPath xpath = XPathFactory.newInstance().newXPath();
    boolean directlyReferenced = location != null && location.toString().toLowerCase().endsWith(".xml");
    String description = null;
    String namespace = null;
    namespace = (String) xpath.evaluate("codelist/@id", doc, XPathConstants.STRING);
    if (namespace == null) {
        reporter.error(new IOMessageImpl("No id attribute present in INSPIRE codelist.", null));
        return false;
    }
    // use the last part of the id as name
    String name = namespace;
    int idxSlash = name.indexOf('/');
    if (idxSlash >= 0 && idxSlash + 1 < name.length()) {
        name = name.substring(idxSlash);
    }
    if (directlyReferenced) {
        // if directly referenced use the label as name
        // (for backwards compatibility)
        NodeList labels = (NodeList) xpath.evaluate("codelist/label", doc, XPathConstants.NODESET);
        if (labels.getLength() > 0) {
            name = labels.item(0).getTextContent();
        }
    }
    NodeList definitions = (NodeList) xpath.evaluate("codelist/definition", doc, XPathConstants.NODESET);
    if (definitions.getLength() > 0)
        description = definitions.item(0).getTextContent();
    // XXX ignore descriptions for now
    // also ignore status, extensibility, register, applicationschema and
    // theme
    // don't use the name as identifier, as it is language dependent!
    INSPIRECodeList codelist = new INSPIRECodeList(namespace, name, description, location);
    NodeList entries = (NodeList) xpath.evaluate("codelist/containeditems/value", doc, XPathConstants.NODESET);
    for (int i = 0; i < entries.getLength(); i++) addEntry(entries.item(i), codelist, xpath, reporter);
    this.codelist = codelist;
    return true;
}
Also used : XPath(javax.xml.xpath.XPath) NodeList(org.w3c.dom.NodeList) IOMessageImpl(eu.esdihumboldt.hale.common.core.io.report.impl.IOMessageImpl)

Example 69 with XPath

use of javax.xml.xpath.XPath in project pentaho-kettle by pentaho.

the class XMLJoin method processRow.

@Override
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException {
    meta = (XMLJoinMeta) smi;
    data = (XMLJoinData) sdi;
    XPath xpath = XPathFactory.newInstance().newXPath();
    // if first row we do some initializing and process the first row of the target XML Step
    if (first) {
        first = false;
        int target_field_id = -1;
        XMLJoinMeta meta = (XMLJoinMeta) smi;
        // Get the two input row sets
        data.TargetRowSet = findInputRowSet(meta.getTargetXMLstep());
        data.SourceRowSet = findInputRowSet(meta.getSourceXMLstep());
        // get the first line from the target row set
        Object[] rTarget = getRowFrom(data.TargetRowSet);
        if (rTarget == null) {
            // nothing to do
            logBasic(BaseMessages.getString(PKG, "XMLJoin.NoRowsFoundInTarget"));
            setOutputDone();
            return false;
        }
        // get target xml
        String[] target_field_names = data.TargetRowSet.getRowMeta().getFieldNames();
        for (int i = 0; i < target_field_names.length; i++) {
            if (meta.getTargetXMLfield().equals(target_field_names[i])) {
                target_field_id = i;
            }
        }
        // Throw exception if target field has not been found
        if (target_field_id == -1) {
            throw new KettleException(BaseMessages.getString(PKG, "XMLJoin.Exception.FieldNotFound", meta.getTargetXMLfield()));
        }
        data.outputRowMeta = data.TargetRowSet.getRowMeta().clone();
        meta.getFields(data.outputRowMeta, getStepname(), new RowMetaInterface[] { data.TargetRowSet.getRowMeta() }, null, getTransMeta(), repository, metaStore);
        data.outputRowData = rTarget.clone();
        // get the target xml structure and create a DOM
        String strTarget = (String) rTarget[target_field_id];
        // parse the XML as a W3C Document
        InputSource inputSource = new InputSource(new StringReader(strTarget));
        data.XPathStatement = meta.getTargetXPath();
        try {
            DocumentBuilder builder = XMLParserFactoryProducer.createSecureDocBuilderFactory().newDocumentBuilder();
            data.targetDOM = builder.parse(inputSource);
            if (!meta.isComplexJoin()) {
                data.targetNode = (Node) xpath.evaluate(data.XPathStatement, data.targetDOM, XPathConstants.NODE);
                if (data.targetNode == null) {
                    throw new KettleXMLException("XPath statement returned no result [" + data.XPathStatement + "]");
                }
            }
        } catch (Exception e) {
            throw new KettleXMLException(e);
        }
    }
    // This also waits for a row to be finished.
    Object[] rJoinSource = getRowFrom(data.SourceRowSet);
    if (rJoinSource == null) {
        // no more input to be expected... create the output row
        try {
            if (meta.isOmitNullValues()) {
                removeEmptyNodes(data.targetDOM.getChildNodes());
            }
            // create string from xml tree
            StringWriter sw = new StringWriter();
            StreamResult resultXML = new StreamResult(sw);
            DOMSource source = new DOMSource(data.targetDOM);
            getTransformer().transform(source, resultXML);
            int outputIndex = data.outputRowMeta.size() - 1;
            // send the row to the next steps...
            putRow(data.outputRowMeta, RowDataUtil.addValueData(data.outputRowData, outputIndex, sw.toString()));
            // finishing up
            setOutputDone();
            return false;
        } catch (Exception e) {
            throw new KettleException(e);
        }
    } else {
        if (data.iSourceXMLField == -1) {
            // assume failure
            // get the column of the join xml set
            // get target xml
            String[] source_field_names = data.SourceRowSet.getRowMeta().getFieldNames();
            for (int i = 0; i < source_field_names.length; i++) {
                if (meta.getSourceXMLfield().equals(source_field_names[i])) {
                    data.iSourceXMLField = i;
                }
            }
            // Throw exception if source xml field has not been found
            if (data.iSourceXMLField == -1) {
                throw new KettleException(BaseMessages.getString(PKG, "XMLJoin.Exception.FieldNotFound", meta.getSourceXMLfield()));
            }
        }
        if (meta.isComplexJoin() && data.iCompareFieldID == -1) {
            // get the column of the compare value
            String[] source_field_names = data.SourceRowSet.getRowMeta().getFieldNames();
            for (int i = 0; i < source_field_names.length; i++) {
                if (meta.getJoinCompareField().equals(source_field_names[i])) {
                    data.iCompareFieldID = i;
                }
            }
            // Throw exception if source xml field has not been found
            if (data.iCompareFieldID == -1) {
                throw new KettleException(BaseMessages.getString(PKG, "XMLJoin.Exception.FieldNotFound", meta.getJoinCompareField()));
            }
        }
        // get XML tags to join
        String strJoinXML = (String) rJoinSource[data.iSourceXMLField];
        try {
            DocumentBuilder builder = XMLParserFactoryProducer.createSecureDocBuilderFactory().newDocumentBuilder();
            Document joinDocument = builder.parse(new InputSource(new StringReader(strJoinXML)));
            Node node = data.targetDOM.importNode(joinDocument.getDocumentElement(), true);
            if (meta.isComplexJoin()) {
                String strCompareValue = rJoinSource[data.iCompareFieldID].toString();
                String strXPathStatement = data.XPathStatement.replace("?", strCompareValue);
                data.targetNode = (Node) xpath.evaluate(strXPathStatement, data.targetDOM, XPathConstants.NODE);
                if (data.targetNode == null) {
                    throw new KettleXMLException("XPath statement returned no result [" + strXPathStatement + "]");
                }
            }
            data.targetNode.appendChild(node);
        } catch (Exception e) {
            throw new KettleException(e);
        }
    }
    return true;
}
Also used : XPath(javax.xml.xpath.XPath) KettleException(org.pentaho.di.core.exception.KettleException) InputSource(org.xml.sax.InputSource) DOMSource(javax.xml.transform.dom.DOMSource) StreamResult(javax.xml.transform.stream.StreamResult) Node(org.w3c.dom.Node) Document(org.w3c.dom.Document) KettleException(org.pentaho.di.core.exception.KettleException) KettleXMLException(org.pentaho.di.core.exception.KettleXMLException) StringWriter(java.io.StringWriter) DocumentBuilder(javax.xml.parsers.DocumentBuilder) StringReader(java.io.StringReader) KettleXMLException(org.pentaho.di.core.exception.KettleXMLException)

Example 70 with XPath

use of javax.xml.xpath.XPath in project coprhd-controller by CoprHD.

the class RemoteRepository method parseCatalog.

/**
 * Parse the EMC software update string representation
 *
 * @param input the EMC software catalog string representation
 * @return a map of software version to remote file URLs
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 * @throws XPathExpressionException
 * @throws InvalidSoftwareVersionException
 * @throws MalformedURLException
 * @throws RemoteRepositoryException
 */
private Map<SoftwareVersion, URL> parseCatalog(String input) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException, InvalidSoftwareVersionException, MalformedURLException, RemoteRepositoryException {
    Map<SoftwareVersion, URL> versions = new HashMap<SoftwareVersion, URL>();
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(new InputSource(new StringReader(input)));
    XPath xPath = XPathFactory.newInstance().newXPath();
    NodeList fileList = (NodeList) xPath.compile("//File").evaluate(doc, XPathConstants.NODESET);
    for (int fileItr = 0; fileItr < fileList.getLength(); fileItr++) {
        Node fileNode = fileList.item(fileItr);
        Element element = (Element) fileNode;
        Node nameNode = element.getAttributeNode("Name");
        if (null != nameNode) {
            String fileName = nameNode.getNodeValue();
            if (fileName.endsWith(SOFTWARE_IMAGE_SUFFIX)) {
                String fileVersion = fileName.replace(SOFTWARE_IMAGE_SUFFIX, "");
                Node urlNode = element.getAttributeNode("URL");
                String fileUrl = urlNode.getNodeValue();
                versions.put(new SoftwareVersion(fileVersion), new URL(fileUrl));
            }
        }
    }
    if (versions.isEmpty()) {
        throw SyssvcException.syssvcExceptions.remoteRepoError("Empty remote repository: " + _repo);
    }
    return versions;
}
Also used : XPath(javax.xml.xpath.XPath) InputSource(org.xml.sax.InputSource) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) SoftwareVersion(com.emc.storageos.coordinator.client.model.SoftwareVersion) DocumentBuilder(javax.xml.parsers.DocumentBuilder)

Aggregations

XPath (javax.xml.xpath.XPath)526 Document (org.w3c.dom.Document)254 NodeList (org.w3c.dom.NodeList)230 XPathFactory (javax.xml.xpath.XPathFactory)215 Node (org.w3c.dom.Node)171 XPathExpressionException (javax.xml.xpath.XPathExpressionException)159 XPathExpression (javax.xml.xpath.XPathExpression)142 DocumentBuilder (javax.xml.parsers.DocumentBuilder)125 Element (org.w3c.dom.Element)118 DocumentBuilderFactory (javax.xml.parsers.DocumentBuilderFactory)97 IOException (java.io.IOException)89 Test (org.junit.Test)80 InputSource (org.xml.sax.InputSource)59 File (java.io.File)57 SAXException (org.xml.sax.SAXException)57 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)51 ByteArrayInputStream (java.io.ByteArrayInputStream)44 ArrayList (java.util.ArrayList)44 InputStream (java.io.InputStream)39 DSNamespaceContext (org.apache.xml.security.test.dom.DSNamespaceContext)37