Example usage for javax.xml.xpath XPathConstants STRING

List of usage examples for javax.xml.xpath XPathConstants STRING

Introduction

In this page you can find the example usage for javax.xml.xpath XPathConstants STRING.

Prototype

QName STRING

To view the source code for javax.xml.xpath XPathConstants STRING.

Click Source Link

Document

The XPath 1.0 string data type.

Maps to Java String .

Usage

From source file:org.kuali.rice.krad.service.impl.MaintainableXMLConversionServiceImpl.java

private void transformNode(Document document, Node node, Class<?> currentClass,
        Map<String, String> propertyMappings) throws ClassNotFoundException, XPathExpressionException,
        IllegalAccessException, InvocationTargetException, NoSuchMethodException, InstantiationException {
    for (Node childNode = node.getFirstChild(); childNode != null;) {
        Node nextChild = childNode.getNextSibling();
        String propertyName = childNode.getNodeName();
        if (childNode.hasAttributes()) {
            XPath xpath = XPathFactory.newInstance().newXPath();
            Node serializationAttribute = childNode.getAttributes().getNamedItem(SERIALIZATION_ATTRIBUTE);
            if (serializationAttribute != null
                    && StringUtils.equals(serializationAttribute.getNodeValue(), "custom")) {
                Node classAttribute = childNode.getAttributes().getNamedItem(CLASS_ATTRIBUTE);
                if (classAttribute != null && StringUtils.equals(classAttribute.getNodeValue(),
                        "org.kuali.rice.kns.util.TypedArrayList")) {
                    ((Element) childNode).removeAttribute(SERIALIZATION_ATTRIBUTE);
                    ((Element) childNode).removeAttribute(CLASS_ATTRIBUTE);
                    XPathExpression listSizeExpression = xpath.compile("//" + propertyName
                            + "/org.apache.ojb.broker.core.proxy.ListProxyDefaultImpl/default/size/text()");
                    String size = (String) listSizeExpression.evaluate(childNode, XPathConstants.STRING);
                    List<Node> nodesToAdd = new ArrayList<Node>();
                    if (StringUtils.isNotBlank(size) && Integer.valueOf(size) > 0) {
                        XPathExpression listTypeExpression = xpath.compile("//" + propertyName
                                + "/org.kuali.rice.kns.util.TypedArrayList/default/listObjectType/text()");
                        String listType = (String) listTypeExpression.evaluate(childNode,
                                XPathConstants.STRING);
                        XPathExpression listContentsExpression = xpath.compile("//" + propertyName
                                + "/org.apache.ojb.broker.core.proxy.ListProxyDefaultImpl/" + listType);
                        NodeList listContents = (NodeList) listContentsExpression.evaluate(childNode,
                                XPathConstants.NODESET);
                        for (int i = 0; i < listContents.getLength(); i++) {
                            Node tempNode = listContents.item(i);
                            transformClassNode(document, tempNode);
                            nodesToAdd.add(tempNode);
                        }/*w ww.j  a v  a  2 s.  c o m*/
                    }
                    for (Node removeNode = childNode.getFirstChild(); removeNode != null;) {
                        Node nextRemoveNode = removeNode.getNextSibling();
                        childNode.removeChild(removeNode);
                        removeNode = nextRemoveNode;
                    }
                    for (Node nodeToAdd : nodesToAdd) {
                        childNode.appendChild(nodeToAdd);
                    }
                } else {
                    ((Element) childNode).removeAttribute(SERIALIZATION_ATTRIBUTE);

                    XPathExpression mapContentsExpression = xpath.compile("//" + propertyName + "/map/string");
                    NodeList mapContents = (NodeList) mapContentsExpression.evaluate(childNode,
                            XPathConstants.NODESET);
                    List<Node> nodesToAdd = new ArrayList<Node>();
                    if (mapContents.getLength() > 0 && mapContents.getLength() % 2 == 0) {
                        for (int i = 0; i < mapContents.getLength(); i++) {
                            Node keyNode = mapContents.item(i);
                            Node valueNode = mapContents.item(++i);
                            Node entryNode = document.createElement("entry");
                            entryNode.appendChild(keyNode);
                            entryNode.appendChild(valueNode);
                            nodesToAdd.add(entryNode);
                        }
                    }
                    for (Node removeNode = childNode.getFirstChild(); removeNode != null;) {
                        Node nextRemoveNode = removeNode.getNextSibling();
                        childNode.removeChild(removeNode);
                        removeNode = nextRemoveNode;
                    }
                    for (Node nodeToAdd : nodesToAdd) {
                        childNode.appendChild(nodeToAdd);
                    }
                }
            }
        }
        if (propertyMappings != null && propertyMappings.containsKey(propertyName)) {
            String newPropertyName = propertyMappings.get(propertyName);
            if (StringUtils.isNotBlank(newPropertyName)) {
                document.renameNode(childNode, null, newPropertyName);
                propertyName = newPropertyName;
            } else {
                // If there is no replacement name then the element needs
                // to be removed and skip all other processing
                node.removeChild(childNode);
                childNode = nextChild;
                continue;
            }
        }
        if (childNode.hasChildNodes() && !(Collection.class.isAssignableFrom(currentClass)
                || Map.class.isAssignableFrom(currentClass))) {
            if (propertyName.equals("principalId") && (node.getNodeName().equals("dataManagerUser")
                    || node.getNodeName().equals("dataStewardUser"))) {
                currentClass = new org.kuali.rice.kim.impl.identity.PersonImpl().getClass();
            }
            Class<?> propertyClass = PropertyUtils.getPropertyType(currentClass.newInstance(), propertyName);
            if (propertyClass != null && classPropertyRuleMap.containsKey(propertyClass.getName())) {
                transformNode(document, childNode, propertyClass,
                        this.classPropertyRuleMap.get(propertyClass.getName()));
            }
            transformNode(document, childNode, propertyClass, classPropertyRuleMap.get("*"));
        }
        childNode = nextChild;
    }
}

From source file:org.kuali.rice.krad.workflow.KualiXMLAttributeImplTest.java

/**
 * This method compares the label from the test to the expected, or not expected, value for all of the rule attributes in the
 * file. The inputSource file should be as close to the production version as possible, as described by the class comments. It
 * accepts the string to test against as a parameter.
 * // ww  w  . j  ava 2 s.c o  m
 * @param testString
 */
private boolean confirmLabels(String testString, String attributeXml, String configNodeName) {
    boolean testFailed = false;
    String theTitle = "";
    String theName = "";
    String attributeName = "";
    try {
        NodeList tempList = (NodeList) myXPath.evaluate("//ruleAttribute",
                new InputSource(new StringReader(attributeXml)), XPathConstants.NODESET);
        for (int i = 0; i < tempList.getLength(); i++) { // loop over ruleattributes
            Node originalNode = tempList.item(i);
            Set ruleAttributeFieldDefNames = new HashSet();
            Set ruleAttributeFieldDefTitles = new HashSet();
            attributeName = (String) myXPath.evaluate(WorkflowUtils.XSTREAM_MATCH_RELATIVE_PREFIX + "name",
                    originalNode, XPathConstants.STRING);
            Node classNameNode = (Node) myXPath.evaluate(
                    WorkflowUtils.XSTREAM_MATCH_RELATIVE_PREFIX + "className", originalNode,
                    XPathConstants.NODE);
            if ((classNameNode != null) && (classNameNode.getFirstChild() != null)) {
                if (LOG.isInfoEnabled()) {
                    LOG.info("Checking attribute with name '" + attributeName + "'");
                }
                KualiXmlAttribute myAttribute = (KualiXmlAttribute) GlobalResourceLoader
                        .getObject(new ObjectDefinition(classNameNode.getFirstChild().getNodeValue()));
                Node xmlNode = configureRuleAttribute(originalNode, myAttribute);
                NamedNodeMap fieldDefAttributes = null;
                String potentialFailMessage = "";

                try {
                    NodeList xmlNodeList = (NodeList) myXPath.evaluate("//fieldDef", xmlNode,
                            XPathConstants.NODESET);

                    for (int j = 0; j < xmlNodeList.getLength(); j++) {
                        Node fieldDefXmlNode = xmlNodeList.item(j);
                        fieldDefAttributes = fieldDefXmlNode.getAttributes();

                        theTitle = fieldDefAttributes.getNamedItem("title").getNodeValue();// Making sure they are clean
                        theName = fieldDefAttributes.getNamedItem("name").getNodeValue();
                        if (LOG.isDebugEnabled()) {
                            LOG.debug(attributeName);
                            LOG.debug("name=" + theName + "   title=" + theTitle);
                        }
                        if (ruleAttributeFieldDefNames.contains(theName)) {
                            // names of fieldDefs inside a single attribute must be unique
                            potentialFailMessage = "Each fieldDef name on a single attribute must be unique and the fieldDef name '"
                                    + theName + "' already exists on the attribute '" + attributeName + "'";
                            fail(potentialFailMessage);
                        } else {
                            ruleAttributeFieldDefNames.add(theName);
                        }
                        if (testString.equals(KualiXmlAttributeHelper.notFound)) {
                            potentialFailMessage = "Each fieldDef title should be a valid value and currently the title for attribute '"
                                    + attributeName + "' is '" + theTitle + "'";
                            assertFalse(potentialFailMessage, theTitle.equals(testString));
                            if (ruleAttributeFieldDefTitles.contains(theTitle)) {
                                /*
                                 * Titles of fieldDefs inside a single attribute should be unique in the normal case. Having two
                                 * fields with the same label would certainly confuse the user. However, due to the way the
                                 * confirmSource test works, all the titles/labels must be the same. So only run this check when
                                 * not in the confirmSource test.
                                 */
                                potentialFailMessage = "Each fieldDef title on a single attribute must be unique and the fieldDef title '"
                                        + theTitle + "' already exists on the attribute '" + attributeName
                                        + "'";
                                fail(potentialFailMessage);
                            } else {
                                ruleAttributeFieldDefTitles.add(theTitle);
                            }
                        } else {
                            potentialFailMessage = "For attribute '" + attributeName
                                    + "' the title should have been '" + testString + "' but was actually '"
                                    + theTitle + "'";
                            assertEquals(potentialFailMessage, testString, theTitle);
                        }
                    }
                } catch (AssertionError afe) {
                    LOG.warn("Assertion Failed for attribute '" + attributeName + "' with error "
                            + potentialFailMessage, afe);
                    testFailed = true;
                } finally {
                    attributeName = "";
                }
            } else {
                throw new RuntimeException("Could not find class for attribute named '" + attributeName + "'");
            }
        }
    } catch (Exception e) {
        LOG.error("General Exception thrown for attribute '" + attributeName + "'", e);
        testFailed = true;
    }
    return testFailed;
}

From source file:org.linguafranca.pwdb.kdbx.dom.DomSerializableDatabase.java

private void prepareProtection(Document doc, String protect) throws XPathExpressionException {
    // does this require encryption
    String query = String.format(protectQuery, protect);
    if (!((String) DomHelper.xpath.evaluate(query, doc, XPathConstants.STRING)).toLowerCase().equals("true")) {
        return;//from   ww  w .java2 s  .  com
    }
    // mark the field as Protected but don't actually encrypt yet, that comes later
    String path = String.format(pattern, protect);
    NodeList nodelist = (NodeList) DomHelper.xpath.evaluate(path, doc, XPathConstants.NODESET);
    for (int i = 0; i < nodelist.getLength(); i++) {
        Element element = (Element) nodelist.item(i);
        element.setAttribute("Protected", "True");
    }
}

From source file:org.linguafranca.pwdb.kdbx.dom.DomSerializableDatabase.java

@Override
public byte[] getHeaderHash() {
    try {/*from   ww  w .j  a v a2  s.c om*/
        String base64 = (String) DomHelper.xpath.evaluate("//HeaderHash", doc, XPathConstants.STRING);
        // Android compatibility
        return Base64.decodeBase64(base64.getBytes());
    } catch (XPathExpressionException e) {
        throw new IllegalStateException("Can't get header hash", e);
    }
}

From source file:org.linguafranca.pwdb.kdbx.KdbxKeyFile.java

/**
 * Load a key from an InputStream with a KDBX XML key file.
 * @param inputStream the input stream holding the key
 * @return they key or null if there was a problem
 *///from  w w w .  j av  a  2 s  . c o  m
public static byte[] load(InputStream inputStream) {
    String base64;
    try {
        DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = documentBuilder.parse(inputStream);
        base64 = (String) xpath.evaluate("//KeyFile/Key/Data/text()", doc, XPathConstants.STRING);
        if (base64 == null) {
            return null;
        }
    } catch (Exception e) {
        return null;
    }
    // android compatibility
    return Base64.decodeBase64(base64.getBytes());
}

From source file:org.lockss.plugin.clockss.XPathXmlMetadataParser.java

private ArticleMetadata extractDataFromNode(Object startNode, XPathInfo[] xPathList)
        throws XPathExpressionException {

    ArticleMetadata returnAM = makeNewArticleMetadata();
    NumberFormat format = NumberFormat.getInstance();

    for (int i = 0; i < xPathList.length; i++) {
        log.debug3("evaluate xpath: " + xPathList[i].xKey.toString());
        QName definedType = xPathList[i].xVal.getType();
        Object itemResult = xPathList[i].xExpr.evaluate(startNode, XPathConstants.NODESET);
        NodeList resultNodeList = (NodeList) itemResult;
        log.debug3(resultNodeList.getLength() + " results for this xKey");
        for (int p = 0; p < resultNodeList.getLength(); p++) {
            Node resultNode = resultNodeList.item(p);
            if (resultNode == null) {
                continue;
            }/*from w  w w . j  av a  2 s. c om*/
            String value = null;
            if (definedType == XPathConstants.NODE) {
                // filter node
                value = xPathList[i].xVal.getValue(resultNode);
            } else if (definedType == XPathConstants.STRING) {
                // filter node text content
                String text = resultNode.getTextContent();
                if (!StringUtil.isNullString(text)) {
                    value = xPathList[i].xVal.getValue(text);
                }
            } else if (definedType == XPathConstants.BOOLEAN) {
                // filter boolean value of node text content
                String text = resultNode.getTextContent();
                if (!StringUtil.isNullString(text)) {
                    value = xPathList[i].xVal.getValue(Boolean.parseBoolean(text));
                }
            } else if (definedType == XPathConstants.NUMBER) {
                // filter number value of node text content
                try {
                    String text = resultNode.getTextContent();
                    if (!StringUtil.isNullString(text)) {
                        value = xPathList[i].xVal.getValue(format.parse(text));
                    }
                } catch (ParseException ex) {
                    // ignore invalid number
                    log.debug3("ignore invalid number", ex);
                }
            } else {
                log.debug("Unknown nodeValue type: " + definedType.toString());
            }

            if (!StringUtil.isNullString(value)) {
                log.debug3("  returning (" + xPathList[i].xKey + ", " + value);
                returnAM.putRaw(xPathList[i].xKey, value);
            }
        }
    }
    return returnAM;
}

From source file:org.mashupmedia.util.XmlHelper.java

public static String getTextFromElement(Document document, String expression) throws XPathExpressionException {
    XPath xPath = getxPathFactory().newXPath();
    XPathExpression xPathExpression = xPath.compile(expression);
    String value = (String) xPathExpression.evaluate(document, XPathConstants.STRING);
    value = StringUtils.trimToEmpty(value);
    return value;
}

From source file:org.mule.GoogleMapsModule.java

private String getXPath(InputStream inputStream, String xpath) throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);//from   w  w w  .j a  va  2  s.  c o  m
    Document doc = dbf.newDocumentBuilder().parse(inputStream);
    XPathFactory factory = XPathFactory.newInstance();
    XPathExpression expr = factory.newXPath().compile(xpath);
    return (String) expr.evaluate(doc, XPathConstants.STRING);
}

From source file:org.mule.ibeans.IBeansSupport.java

/**
 * Select a single XML String value using an Xpath
 * @param xpath the XPath expression to evaluate
 * @param node the node (or document) to exaluate on
 * @return the result of the evaluation.  Note that if an error occurs, the error is logged and null is returned
 *//*  w  w w  .java2  s  .  c  o m*/
public static String selectValue(String xpath, Node node) {
    try {
        XPath xp = createXPath(node);
        return (String) xp.evaluate(xpath, node, XPathConstants.STRING);
    } catch (XPathExpressionException e) {
        logger.error(e.getMessage());
        return null;
    }
}

From source file:org.mule.module.dxpath.DxTransformer.java

/**
 * Result type from this transformer.//w  w w . j av  a 2  s .c  o m
 * 
 * @param resultType
 *            Result type from this transformer.
 */
public void setResultType(ResultType resultTypeType) {
    QName resultType;
    switch (resultTypeType) {
    case BOOLEAN:
        resultType = XPathConstants.BOOLEAN;
        break;
    case NODE:
        resultType = XPathConstants.NODE;
        break;
    case NODESET:
        resultType = XPathConstants.NODESET;
        break;
    case NUMBER:
        resultType = XPathConstants.NUMBER;
        break;
    default:
        resultType = XPathConstants.STRING;
        break;
    }
    this.resultType = resultType;
}