Example usage for org.dom4j Node selectSingleNode

List of usage examples for org.dom4j Node selectSingleNode

Introduction

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

Prototype

Node selectSingleNode(String xpathExpression);

Source Link

Document

selectSingleNode evaluates an XPath expression and returns the result as a single Node instance.

Usage

From source file:org.pentaho.aggdes.model.ssas.ConversionUtil.java

License:Open Source License

public static String getXPathNodeText(Node parent, String xpath) throws AggDesignerException {
    Element element = (Element) parent.selectSingleNode(xpath);
    if (element == null) {
        throw new AggDesignerException("no element found for xpath '" + xpath + "'");
    }/*  w  w  w.j a va  2 s .c om*/
    return ((Element) parent.selectSingleNode(xpath)).getTextTrim();
}

From source file:org.pentaho.commons.connection.memory.MemoryResultSet.java

License:Open Source License

public static String getNodeText(String xpath, Node rootNode, String defaultValue) {
    if (rootNode == null) {
        return (defaultValue);
    }/*from ww  w.  j  av  a2  s  . co  m*/
    Node node = rootNode.selectSingleNode(xpath);
    if (node == null) {
        return defaultValue;
    }
    return node.getText();
}

From source file:org.pentaho.di.baserver.utils.inspector.WadlParser.java

License:Open Source License

protected Endpoint parseMethod(Node methodNode, final String path) {
    Endpoint endpoint = new Endpoint();
    endpoint.setId(methodNode.valueOf("@id"));
    endpoint.setHttpMethod(HttpMethod.valueOf(methodNode.valueOf("@name")));
    endpoint.setPath(shortPath(path));/*  w  w  w  .j a va 2s. c  o m*/

    Node requestNode = methodNode.selectSingleNode("*[local-name() = 'request']");
    if (requestNode != null) {
        for (Object queryParamNode : requestNode.selectNodes("*[local-name() = 'param']")) {
            endpoint.getQueryParams().add(parseQueryParam((Node) queryParamNode));
        }
    }

    Node nodeDoc = methodNode.selectSingleNode("*[local-name() = 'doc']");
    if (nodeDoc != null) {
        endpoint.setDeprecated(isDeprecated(nodeDoc.getText()));
        endpoint.setDocumentation(extractComment(nodeDoc.getText()));
        endpoint.setSupported(isSupported(nodeDoc.getText()));
    }
    return endpoint;
}

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);
    }/* w  w  w . ja v  a  2 s  . com*/
    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.pentaho.jpivot.AnalysisSaver.java

License:Open Source License

/**
 * @param componentDefinition//w w  w.j  a  v a2 s  .c  o m
 * @param props
 */
private static void updateComponent(final Element componentDefinition, final HashMap props) {
    Iterator iter = props.keySet().iterator();

    while (iter.hasNext()) {
        Object key = iter.next();
        Node node = componentDefinition.selectSingleNode(key.toString());
        if (node == null) {
            node = componentDefinition.addElement(key.toString());
        }
        if (PivotViewComponent.OPTIONS.equals(node.getName())) {
            List optionsList = (List) props.get(key);
            Iterator optsIter = optionsList.iterator();
            while (optsIter.hasNext()) {
                String anOption = optsIter.next().toString();
                Node anOptionNode = node.selectSingleNode(anOption);
                if (anOptionNode == null) {
                    ((Element) node).addElement(anOption);
                }
            }
        } else {
            Object value = props.get(key);
            if (value != null) {
                // remove existing text
                node.setText(""); //$NON-NLS-1$
                ((Element) node).addCDATA(value.toString());
            }
        }
    }
    // the property "mdx" is no longer being put in the hashmap. So,
    // query will be passed properly now.
}

From source file:org.pentaho.pac.server.config.WebXml.java

License:Open Source License

public String getContextParamValue(String name) {
    String xPath = MessageFormat.format(CONTEXT_PARAM_NAME_TEMPLATE_XPATH, name);
    Node node = document.selectSingleNode(xPath);
    String value = null;//from   w  ww . ja va2s  .c  om
    if (node != null) {
        node = node.selectSingleNode("../param-value"); //$NON-NLS-1$
    }
    if (node != null) {
        value = node.getText();
    }
    return value;
}

From source file:org.pentaho.pac.server.config.WebXml.java

License:Open Source License

public boolean setServletMapping(String name, String value) {
    String xPath = MessageFormat.format(SERVLET_NAME_TEMPLATE_XPATH, name);
    Node node = document.selectSingleNode(xPath);
    if (node != null) {
        node = node.selectSingleNode("../jsp-file"); //$NON-NLS-1$
    }/*from  w  ww  .j  a v a2s  .  com*/
    if (node != null) {
        node.setText(value);
        return true;
    }
    return false;
}

From source file:org.pentaho.pac.server.config.WebXml.java

License:Open Source License

public String getServletMapping(String name) {
    String xPath = MessageFormat.format(SERVLET_NAME_TEMPLATE_XPATH, name);
    Node node = document.selectSingleNode(xPath);
    String value = null;/*w ww .  j av  a  2  s.com*/
    if (node != null) {
        node = node.selectSingleNode("../jsp-file"); //$NON-NLS-1$
    }
    if (node != null) {
        value = node.getText();
    }
    return value;
}

From source file:org.pentaho.platform.engine.core.system.PentahoSystem.java

License:Open Source License

/**
 * Using data in the systemSettings (this data typically originates in the pentaho.xml file), initialize 3 System
 * properties to explicitly identify the Transformer, SAX, and DOM factory implementations. (i.e. Crimson, Xerces,
 * Xalan, Saxon, etc.)/*from  www.  j  a v a 2s .  co  m*/
 * <p/>
 * For background on the purpose of this method, take a look at the notes/URLs below:
 * <p/>
 * Java[tm] API for XML Processing (JAXP):Frequently Asked Questions http://java.sun
 * .com/webservices/jaxp/reference/faqs/index.html
 * <p/>
 * Plugging in a Transformer and XML parser http://xml.apache.org/xalan-j/usagepatterns.html#plug
 * <p/>
 * http://marc2.theaimsgroup.com/?l=xml-apache-general&m=101344910514822&w=2 Q. How do I use a different JAXP
 * compatible implementation?
 * <p/>
 * The JAXP 1.1 API allows applications to plug in different JAXP compatible implementations of parsers or XSLT
 * processors. For example, when an application wants to create a new JAXP DocumentBuilderFactory instance, it calls
 * the staic method DocumentBuilderFactory.newInstance(). This causes a search for the name of a concrete subclass of
 * DocumentBuilderFactory using the following order: - The value of a system property like
 * javax.xml.parsers.DocumentBuilderFactory if it exists and is accessible. - The contents of the file
 * $JAVA_HOME/jre/lib/jaxp.properties if it exists. - The Jar Service Provider mechanism specified in the Jar File
 * Specification. A jar file can have a resource (i.e. an embedded file) such as
 * META-INF/javax/xml/parsers/DocumentBuilderFactory containing the name of the concrete class to instantiate. - The
 * fallback platform default implementation.
 * <p/>
 * Of the above ways to specify an implementation, perhaps the most useful is the jar service provider mechanism. To
 * use this mechanism, place the implementation jar file on your classpath. For example, to use Xerces 1.4.4 instead
 * of the version of Crimson which is bundled with JDK 1.4 (Java Development Kit version 1.4), place xerces.jar in
 * your classpath. This mechanism also works with older versions of the JDK which do not bundle JAXP. If you are using
 * JDK 1.4 and above, see the following question for potential problems. see http://java.sun.com/j2se/1
 * .3/docs/guide/jar/jar.html#Service%20Provider
 */
private static void initXMLFactories() {
    // assert systemSettings != null : "systemSettings property must be set
    // before calling initXMLFactories.";

    if (PentahoSystem.systemSettingsService != null) {
        String xpathToXMLFactoryNodes = "xml-factories/factory-impl"; //$NON-NLS-1$
        List nds = PentahoSystem.systemSettingsService.getSystemSettings(xpathToXMLFactoryNodes);
        if (null != nds && !nds.isEmpty()) {
            Logger.warn(PentahoSystem.class.getName(), Messages.getInstance().getErrorString(
                    "PentahoSystem.WARN_XML_FACTORIES_LOCATION_CHANGED", JAVA_SYSTEM_PROPERTIES)); //$NON-NLS-1$
            for (Iterator it = nds.iterator(); it.hasNext();) {
                Node nd = (Node) it.next();
                Node nameAttr = nd.selectSingleNode("@name"); //$NON-NLS-1$
                Node implAttr = nd.selectSingleNode("@implementation"); //$NON-NLS-1$
                if ((null != nameAttr) && (null != implAttr)) {
                    String name = nameAttr.getText();
                    String impl = implAttr.getText();
                    System.setProperty(name, impl);
                } else {
                    Logger.error(PentahoSystem.class.getName(),
                            Messages.getInstance().getErrorString(
                                    "PentahoSystem.ERROR_0025_LOAD_XML_FACTORY_PROPERTIES_FAILED", //$NON-NLS-1$
                                    xpathToXMLFactoryNodes));
                }
            }
        }
    }
}

From source file:org.pentaho.platform.engine.services.actionsequence.ActionDefinition.java

License:Open Source License

public ActionDefinition(final Node actionRootNode, final ILogger logger) {

    this.actionRootNode = actionRootNode;

    errorCode = ISequenceDefinition.ACTION_SEQUENCE_DEFINITION_OK;
    // this.sequenceData = sequenceData;

    // get the input parameter definitions
    actionInputDefinitions = new ListOrderedMap();
    actionInputMapping = new ListOrderedMap();
    errorCode = SequenceDefinition.parseParameters(actionRootNode, logger, "action-inputs/*", //$NON-NLS-1$
            actionInputDefinitions, actionInputMapping, true);

    // get the ouput definitions
    actionOutputDefinitions = new ListOrderedMap();
    actionOutputMapping = new ListOrderedMap();
    errorCode = SequenceDefinition.parseParameters(actionRootNode, logger, "action-outputs/*", //$NON-NLS-1$
            actionOutputDefinitions, actionOutputMapping, false);

    // get the resource definitions
    actionResourceMapping = new ListOrderedMap();
    if (actionRootNode.selectNodes("action-resources/*").size() > 0) { //$NON-NLS-1$
        hasActionResources = true;/*from  ww  w  .j av a 2 s . c  o m*/
        errorCode = SequenceDefinition.parseActionResourceDefinitions(actionRootNode, logger,
                "action-resources/*", actionResourceMapping); //$NON-NLS-1$
    }

    componentName = XmlDom4JHelper.getNodeText("component-name", actionRootNode); //$NON-NLS-1$
    String loggingLevelString = XmlDom4JHelper.getNodeText("logging-level", actionRootNode); //$NON-NLS-1$
    loggingLevel = Logger.getLogLevel(loggingLevelString);

    // get the component payload
    componentNode = actionRootNode.selectSingleNode("component-definition"); //$NON-NLS-1$
    if (componentNode == null) {
        componentNode = ((Element) actionRootNode).addElement("component-definition"); //$NON-NLS-1$
    }

    // TODO populate preExecuteAuditList and postExecuteAuditList
}