Example usage for org.dom4j XPath selectSingleNode

List of usage examples for org.dom4j XPath selectSingleNode

Introduction

In this page you can find the example usage for org.dom4j XPath selectSingleNode.

Prototype

Node selectSingleNode(Object context);

Source Link

Document

selectSingleNode evaluates this XPath expression on the given Node or List of Node s and returns the result as a single Node instance.

Usage

From source file:org.orbeon.oxf.xml.XPathUtils.java

License:Open Source License

/**
 * Apply the given XPath expression to the given node.
 *
 * @param prefixes  mapping of prefixes to namespace URIs for prefixes used in expr
 *///from  w ww  .jav a  2  s . co m
public static org.dom4j.Node selectSingleNode(org.dom4j.Node node, String expr, Map prefixes) {
    try {
        org.dom4j.XPath path = node.createXPath(expr);
        path.setNamespaceContext(new SimpleNamespaceContext(prefixes));
        return path.selectSingleNode(node);
    } catch (InvalidXPathException e) {
        throw new OXFException(e);
    }
}

From source file:org.orbeon.oxf.xml.XPathUtils.java

License:Open Source License

/**
 * Select a value as a String.//from w  ww  .  ja  va  2s. com
 *
 * If the XPath expressions select an empty node set, return null.
 */
public static String selectStringValue(Node node, String expr, Map prefixes) {
    try {
        XPath path = new DOMXPath(expr);
        path.setNamespaceContext(new SimpleNamespaceContext(prefixes));
        Object result = path.selectSingleNode(node);
        return (result == null || result instanceof String) ? (String) result
                : new DOMXPath(".").stringValueOf(result);
    } catch (JaxenException e) {
        throw new OXFException(e);
    }
}

From source file:org.pentaho.di.trans.steps.getxmldata.GetXMLData.java

License:Apache License

private Object[] processPutRow(Node node) throws KettleException {
    // Create new row...
    Object[] outputRowData = buildEmptyRow();

    // Create new row or clone
    if (meta.isInFields()) {
        System.arraycopy(data.readrow, 0, outputRowData, 0, data.nrReadRow);
    }/*from  w w w .j  ava 2 s.  co m*/
    try {
        data.nodenr++;

        // Read fields...
        for (int i = 0; i < data.nrInputFields; i++) {
            // Get field
            GetXMLDataField xmlDataField = meta.getInputFields()[i];
            // Get the Path to look for
            String XPathValue = xmlDataField.getResolvedXPath();

            if (meta.isuseToken()) {
                // See if user use Token inside path field
                // The syntax is : @_Fieldname-
                // PDI will search for Fieldname value and replace it
                // Fieldname must be defined before the current node
                XPathValue = substituteToken(XPathValue, outputRowData);
                if (isDetailed()) {
                    logDetailed(XPathValue);
                }
            }

            // Get node value
            String nodevalue;

            // Handle namespaces
            if (meta.isNamespaceAware()) {
                XPath xpathField = node.createXPath(addNSPrefix(XPathValue, data.PathValue));
                xpathField.setNamespaceURIs(data.NAMESPACE);
                if (xmlDataField.getResultType() == GetXMLDataField.RESULT_TYPE_VALUE_OF) {
                    nodevalue = xpathField.valueOf(node);
                } else {
                    // nodevalue=xpathField.selectSingleNode(node).asXML();
                    Node n = xpathField.selectSingleNode(node);
                    if (n != null) {
                        nodevalue = n.asXML();
                    } else {
                        nodevalue = "";
                    }
                }
            } else {
                if (xmlDataField.getResultType() == GetXMLDataField.RESULT_TYPE_VALUE_OF) {
                    nodevalue = node.valueOf(XPathValue);
                } else {
                    // nodevalue=node.selectSingleNode(XPathValue).asXML();
                    Node n = node.selectSingleNode(XPathValue);
                    if (n != null) {
                        nodevalue = n.asXML();
                    } else {
                        nodevalue = "";
                    }
                }
            }

            // Do trimming
            switch (xmlDataField.getTrimType()) {
            case GetXMLDataField.TYPE_TRIM_LEFT:
                nodevalue = Const.ltrim(nodevalue);
                break;
            case GetXMLDataField.TYPE_TRIM_RIGHT:
                nodevalue = Const.rtrim(nodevalue);
                break;
            case GetXMLDataField.TYPE_TRIM_BOTH:
                nodevalue = Const.trim(nodevalue);
                break;
            default:
                break;
            }

            // Do conversions
            //
            ValueMetaInterface targetValueMeta = data.outputRowMeta.getValueMeta(data.totalpreviousfields + i);
            ValueMetaInterface sourceValueMeta = data.convertRowMeta.getValueMeta(data.totalpreviousfields + i);
            outputRowData[data.totalpreviousfields + i] = targetValueMeta.convertData(sourceValueMeta,
                    nodevalue);

            // Do we need to repeat this field if it is null?
            if (meta.getInputFields()[i].isRepeated()) {
                if (data.previousRow != null && Utils.isEmpty(nodevalue)) {
                    outputRowData[data.totalpreviousfields + i] = data.previousRow[data.totalpreviousfields
                            + i];
                }
            }
        } // End of loop over fields...

        int rowIndex = data.totalpreviousfields + data.nrInputFields;

        // See if we need to add the filename to the row...
        if (meta.includeFilename() && !Utils.isEmpty(meta.getFilenameField())) {
            outputRowData[rowIndex++] = data.filename;
        }
        // See if we need to add the row number to the row...
        if (meta.includeRowNumber() && !Utils.isEmpty(meta.getRowNumberField())) {
            outputRowData[rowIndex++] = data.rownr;
        }
        // Possibly add short filename...
        if (meta.getShortFileNameField() != null && meta.getShortFileNameField().length() > 0) {
            outputRowData[rowIndex++] = data.shortFilename;
        }
        // Add Extension
        if (meta.getExtensionField() != null && meta.getExtensionField().length() > 0) {
            outputRowData[rowIndex++] = data.extension;
        }
        // add path
        if (meta.getPathField() != null && meta.getPathField().length() > 0) {
            outputRowData[rowIndex++] = data.path;
        }
        // Add Size
        if (meta.getSizeField() != null && meta.getSizeField().length() > 0) {
            outputRowData[rowIndex++] = data.size;
        }
        // add Hidden
        if (meta.isHiddenField() != null && meta.isHiddenField().length() > 0) {
            outputRowData[rowIndex++] = Boolean.valueOf(data.path);
        }
        // Add modification date
        if (meta.getLastModificationDateField() != null && meta.getLastModificationDateField().length() > 0) {
            outputRowData[rowIndex++] = data.lastModificationDateTime;
        }
        // Add Uri
        if (meta.getUriField() != null && meta.getUriField().length() > 0) {
            outputRowData[rowIndex++] = data.uriName;
        }
        // Add RootUri
        if (meta.getRootUriField() != null && meta.getRootUriField().length() > 0) {
            outputRowData[rowIndex] = data.rootUriName;
        }

        RowMetaInterface irow = getInputRowMeta();

        if (irow == null) {
            data.previousRow = outputRowData;
        } else {
            // clone to previously allocated array to make sure next step doesn't
            // change it in between...
            System.arraycopy(outputRowData, 0, this.prevRow, 0, outputRowData.length);
            // Pick up everything else that needs a real deep clone
            data.previousRow = irow.cloneRow(outputRowData, this.prevRow);
        }
    } catch (Exception e) {
        if (getStepMeta().isDoingErrorHandling()) {
            // Simply add this row to the error row
            putError(data.outputRowMeta, outputRowData, 1, e.toString(), null, "GetXMLData001");
            data.errorInRowButContinue = true;
            return null;
        } else {
            logError(e.toString());
            throw new KettleException(e.toString());
        }
    }
    return outputRowData;
}

From source file:org.soyatec.windowsazure.internal.util.xml.XPathQueryHelper.java

License:Apache License

/**
 * Select single node/*from w  w  w .  j a  va 2  s  .co  m*/
 * 
 * @param doc
 * @param path
 * @return a node object
 */
@SuppressWarnings("unchecked")
static Node selectSingleNode(final Node doc, String path) {
    Map xmlMap = new HashMap();
    xmlMap.put(XMLNS, ServiceManagementConstants.ServiceManagementNS);
    XPath x = doc.createXPath(path);
    x.setNamespaceURIs(xmlMap);
    Node selectSingleNode = x.selectSingleNode(doc);
    return selectSingleNode;
}

From source file:org.suren.autotest.web.framework.code.DefaultXmlDataSourceGenerator.java

License:Apache License

/**
 * @param document/*w  ww . j  av  a 2s.c  om*/
 */
private void parse(Document doc) {
    SimpleNamespaceContext simpleNamespaceContext = new SimpleNamespaceContext();
    simpleNamespaceContext.addNamespace("ns", "http://surenpi.com");

    XPath xpath = new DefaultXPath("/ns:autotest/ns:includePage");
    xpath.setNamespaceContext(simpleNamespaceContext);
    @SuppressWarnings("unchecked")
    List<Element> includePageList = xpath.selectNodes(doc);
    if (includePageList != null && includePageList.size() > 0) {
        for (Element includePage : includePageList) {
            String pageConfig = includePage.attributeValue("pageConfig");

            generate(pageConfig, outputDir);
        }
    }

    xpath = new DefaultXPath("/ns:autotest/ns:pages");
    xpath.setNamespaceContext(simpleNamespaceContext);
    Element pagesEle = (Element) xpath.selectSingleNode(doc);
    String pagePackage = pagesEle.attributeValue("pagePackage", "");
    if (StringUtils.isNotBlank(pagePackage)) {
        pagePackage = pagePackage.trim();
    }

    // pages parse progress
    xpath = new DefaultXPath("/ns:autotest/ns:pages/ns:page");
    xpath.setNamespaceContext(simpleNamespaceContext);
    @SuppressWarnings("unchecked")
    List<Element> pageNodes = xpath.selectNodes(doc);
    if (pageNodes != null) {
        for (Element ele : pageNodes) {
            String pageClsStr = ele.attributeValue("class");
            if (pageClsStr == null) {
                logger.warn("can not found class attribute.");
                continue;
            }

            String dataSrc = ele.attributeValue("dataSource");

            try {
                parse(doc, pagePackage, pageClsStr, dataSrc, ele);
            } catch (NoSuchBeanDefinitionException e) {
                logger.error("Page element [{}] parse error, in document [{}].", "pageClsStr", doc);
                throw e;
            } catch (Exception e) {
                logger.error("Page element parse error.", e);
            }
        }
    }
}

From source file:org.suren.autotest.web.framework.code.DefaultXmlDataSourceGenerator.java

License:Apache License

/**
 * ??Page/*from  w ww .j a v  a2s  . c o  m*/
 * 
 * @param pageClsStr
 * @param dataSrc
 * @param dataSrc2 
 * @param ele
 */
private void parse(Document doc, String pagePackage, final String pageClsStr, String dataSrc, Element ele)
        throws Exception {
    SimpleNamespaceContext simpleNamespaceContext = new SimpleNamespaceContext();
    simpleNamespaceContext.addNamespace("ns", "http://surenpi.com");

    XPath xpath = new DefaultXPath("/ns:autotest/ns:dataSources/ns:dataSource[@name='" + dataSrc + "']");
    xpath.setNamespaceContext(simpleNamespaceContext);
    Element dataSourceEle = (Element) xpath.selectSingleNode(doc);
    if (dataSourceEle == null) {
        logger.error("Can not found dataSource element by {}.", dataSrc);
        return;
    }

    String dsType = dataSourceEle.attributeValue("type");
    String dsResource = dataSourceEle.attributeValue("resource");

    logger.debug("DataSource type is {}, resource is {}.", dsType, dsResource);

    updateXmlDataSourceByEle(ele, dsResource, pagePackage, pageClsStr);
}

From source file:org.suren.autotest.web.framework.code.DefaultXmlDataSourceGenerator.java

License:Apache License

/**
 * @param ele/* w w  w  .  ja v a 2 s . com*/
 * @param pageClsStr2 
 */
private void updateXmlDataSourceByEle(Element ele, String dsResource, String pagePackage, String pageClsStr) {
    Document doc = docMap.get(dsResource);
    if (doc == null) {
        doc = prepareDoc(dsResource);
        docMap.put(dsResource, doc);
    }

    SimpleNamespaceContext simpleNamespaceContext = new SimpleNamespaceContext();
    simpleNamespaceContext.addNamespace("ns", "http://datasource.surenpi.com");

    XPath xpath = new DefaultXPath("/ns:dataSources");
    xpath.setNamespaceContext(simpleNamespaceContext);

    Element dataSourcesEle = doc.getRootElement();
    dataSourcesEle.addAttribute("pagePackage", pagePackage);

    //?
    if (StringUtils.isNotBlank(pagePackage)) {
        pagePackage = (pagePackage.trim());
        xpath = new DefaultXPath("/ns:dataSources[@pagePackage='" + pagePackage
                + "']/ns:dataSource[@pageClass='" + pageClsStr + "']");
        xpath.setNamespaceContext(simpleNamespaceContext);
    } else {
        xpath = new DefaultXPath("/ns:dataSources/ns:dataSource[@pageClass='" + pageClsStr + "']");
        xpath.setNamespaceContext(simpleNamespaceContext);
    }
    Element dataSourceEle = (Element) xpath.selectSingleNode(doc);
    if (dataSourceEle == null) {
        String prefix = dataSourcesEle.getNamespacePrefix();
        if (StringUtils.isBlank("")) {
            String parentName = dataSourcesEle.getName();
            if (parentName.contains(":")) {
                prefix = parentName.split(":")[0];
            }
        }

        if (StringUtils.isNotBlank(prefix)) {
            prefix = prefix + ":";
        }

        dataSourceEle = dataSourcesEle.addElement(prefix + "dataSource");

        dataSourceEle.addAttribute("pageClass", pageClsStr);
    }

    //??
    if (StringUtils.isNotBlank(pagePackage)) {
        pagePackage = (pagePackage.trim());
        xpath = new DefaultXPath("/ns:dataSources[@pagePackage='" + pagePackage
                + "']/ns:dataSource[@pageClass='" + pageClsStr + "']/ns:page[1]");
        xpath.setNamespaceContext(simpleNamespaceContext);
    } else {
        xpath = new DefaultXPath("/ns:dataSources/ns:dataSource[@pageClass='" + pageClsStr + "']/ns:page[1]");
        xpath.setNamespaceContext(simpleNamespaceContext);
    }
    Element pageEle = (Element) xpath.selectSingleNode(dataSourceEle);
    if (pageEle == null) {
        String prefix = dataSourceEle.getNamespacePrefix();
        if (StringUtils.isNotBlank(prefix)) {
            prefix = prefix + ":";
        }

        pageEle = dataSourceEle.addElement(prefix + "page");
    }

    ele.accept(new PageFieldVisitor(pageEle, pagePackage, pageClsStr));
}

From source file:org.suren.autotest.web.framework.code.DefaultXmlDataSourceGenerator.java

License:Apache License

/**
 * ?xmldocument/*from w w  w  .j  a  va  2  s  .  com*/
 * @param resPath
 * @return
 */
private Document prepareDoc(final String resPath) {
    ClassLoader clsLoader = this.getClass().getClassLoader();
    URL url = clsLoader.getResource(resPath);
    InputStream dsInput = null;
    try {
        if (url != null) {
            dsInput = url.openStream();
        }
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    Document doc = null;
    if (dsInput != null) {
        try {
            doc = new SAXReader().read(dsInput);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    } else {
        doc = DocumentHelper.createDocument();
    }

    SimpleDateFormat dateFormat = new SimpleDateFormat();
    doc.addComment("Auto created by AutoTest, " + dateFormat.format(new Date()));

    SimpleNamespaceContext simpleNamespaceContext = new SimpleNamespaceContext();
    simpleNamespaceContext.addNamespace("ns", "http://datasource.surenpi.com");

    XPath xpath = new DefaultXPath("/ns:dataSources");
    xpath.setNamespaceContext(simpleNamespaceContext);

    //?
    Element dataSourcesEle = (Element) xpath.selectSingleNode(doc);
    if (dataSourcesEle == null) {
        String prefix = "suren";
        dataSourcesEle = doc.addElement(prefix + ":dataSources");

        dataSourcesEle.addNamespace(prefix, "http://datasource.surenpi.com");
        dataSourcesEle.addAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
        dataSourcesEle.addAttribute("xsi:schemaLocation", "http://datasource.surenpi.com "
                + "http://surenpi.com/schema/datasource/autotest.web.framework.datasource.xsd ");
    }

    return doc;
}

From source file:org.suren.autotest.web.framework.code.DefaultXmlGenerator.java

License:Apache License

@Override
public void generate(String srcCoding, final String outputDir) {
    //???Page/*from  w w  w. j a va2 s . c  o m*/
    Generator generator = new DefaultXmlCodeGenerator() {

        private String springConfigPath = "applicationContext.xml";
        private Set<String> allPackage = new HashSet<String>();

        @Override
        protected void create(AutoPage autoPage) {
            super.create(autoPage);

            allPackage.add(autoPage.getPackageName());
        }

        @Override
        protected void done() {
            super.done();

            if (allPackage.size() == 0) {
                return;
            }

            Document springConfigDoc = null;

            try (InputStream inputStream = getClassLoader().getResourceAsStream(springConfigPath)) {
                if (inputStream != null) {
                    springConfigDoc = new SAXReader().read(inputStream);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (DocumentException e) {
                e.printStackTrace();
            }

            if (springConfigDoc == null) {
                springConfigDoc = DocumentHelper.createDocument();

                String prefix = "p";
                Element root = springConfigDoc.addElement(prefix + ":beans");

                root.addNamespace(prefix, "http://www.springframework.org/schema/beans");
                root.addNamespace("context", "http://www.springframework.org/schema/context");
                root.addAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
                root.addAttribute("xsi:schemaLocation",
                        "http://www.springframework.org/schema/beans "
                                + "http://www.springframework.org/schema/beans/spring-beans-3.0.xsd "
                                + "http://www.springframework.org/schema/context "
                                + "http://www.springframework.org/schema/context/spring-context-3.0.xsd  ");
            }

            SimpleNamespaceContext simpleNamespaceContext = new SimpleNamespaceContext();
            simpleNamespaceContext.addNamespace("p", "http://www.springframework.org/schema/beans");
            simpleNamespaceContext.addNamespace("context", "http://www.springframework.org/schema/context");

            XPath xpath = new DefaultXPath("/p:beans/context:component-scan");
            xpath.setNamespaceContext(simpleNamespaceContext);

            //?
            Element componentScanEle = (Element) xpath.selectSingleNode(springConfigDoc);
            if (componentScanEle == null) {
                componentScanEle = springConfigDoc.getRootElement().addElement("context:component-scan");
            }

            //pagepackage?
            String basePackage = componentScanEle.attributeValue("base-package", "");
            basePackage = basePackage.trim();
            if (!"".equals(basePackage) && !basePackage.endsWith(",")) {
                basePackage += ",";
            }

            basePackage.replaceAll(",\\s*", ",");
            for (String newPackage : allPackage) {
                if (!basePackage.contains(newPackage + ",")) {
                    basePackage += (newPackage + ",");
                }
            }

            componentScanEle.addAttribute("base-package", basePackage);

            //???
            File outputDirFile = new File(outputDir);
            if (!outputDirFile.isDirectory()) {
                outputDirFile.mkdirs();
            }

            try (OutputStream dsOutput = new FileOutputStream(new File(outputDirFile, springConfigPath))) {
                OutputFormat outputFormat = OutputFormat.createPrettyPrint();
                outputFormat.setIndentSize(4);
                XMLWriter xmlWriter = new XMLWriter(dsOutput, outputFormat);

                xmlWriter.write(springConfigDoc);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    };
    generator.generate(srcCoding, outputDir); //?

    generator = new DefaultXmlDataSourceGenerator();
    generator.generate(srcCoding, outputDir); //?

    generator = new DefaultXmlSuiteRunnerGenerator();
    generator.generate(srcCoding, outputDir); //?}
}

From source file:org.suren.autotest.web.framework.code.DefaultXmlSuiteRunnerGenerator.java

License:Apache License

/**
 * @param document//from   w  ww  . j  a  v  a 2  s .  c  o m
 */
private void parse(Document doc) {
    SimpleNamespaceContext simpleNamespaceContext = new SimpleNamespaceContext();
    simpleNamespaceContext.addNamespace("ns", "http://surenpi.com");

    XPath xpath = new DefaultXPath("/ns:autotest/ns:includePage");
    xpath.setNamespaceContext(simpleNamespaceContext);
    @SuppressWarnings("unchecked")
    List<Element> includePageList = xpath.selectNodes(doc);
    if (includePageList != null && includePageList.size() > 0) {
        for (Element includePage : includePageList) {
            String pageConfig = includePage.attributeValue("pageConfig");

            generate(pageConfig, outputDir);
        }
    }

    xpath = new DefaultXPath("/ns:autotest/ns:pages");
    xpath.setNamespaceContext(simpleNamespaceContext);
    Element pagesEle = (Element) xpath.selectSingleNode(doc);
    String pagePackage = pagesEle.attributeValue("pagePackage", "");
    if (StringUtils.isNotBlank(pagePackage)) {
        pagePackage = pagePackage.trim();
    }

    // pages parse progress
    xpath = new DefaultXPath("/ns:autotest/ns:pages/ns:page");
    xpath.setNamespaceContext(simpleNamespaceContext);
    @SuppressWarnings("unchecked")
    List<Element> pageNodes = xpath.selectNodes(doc);
    if (pageNodes != null) {
        for (Element ele : pageNodes) {
            String pageClsStr = ele.attributeValue("class");
            if (pageClsStr == null) {
                logger.warn("can not found class attribute.");
                continue;
            }

            try {
                parse(doc, pagePackage, pageClsStr, ele);
            } catch (NoSuchBeanDefinitionException e) {
                logger.error("Page element [{}] parse error, in document [{}].", "pageClsStr", doc);
                throw e;
            } catch (Exception e) {
                logger.error("Page element parse error.", e);
            }
        }
    }
}