Example usage for org.w3c.dom Node setUserData

List of usage examples for org.w3c.dom Node setUserData

Introduction

In this page you can find the example usage for org.w3c.dom Node setUserData.

Prototype

public Object setUserData(String key, Object data, UserDataHandler handler);

Source Link

Document

Associate an object to a key on this node.

Usage

From source file:Main.java

/**
 * Sets the index of the Node instance's "current" child as user data on
 * the Node instance./*from  w ww. j a  v a2  s .  co m*/
 * 
 * @param node Node instance on which to set index.
 * @param index Index of node's "current" child.
 * @return true if index has changed, else false.
 */
public static boolean setCurrentChildIndex(Node node, int index) {
    boolean indexChanged = false;
    if (node != null) {
        int currentIndex = getCurrentChildIndex(node);
        if (currentIndex != index) {
            node.setUserData(KEY_CURRENT_CHILD_INDEX, new Integer(index), null);
            indexChanged = true;
        }
    }
    return indexChanged;
}

From source file:Main.java

/**
 * Reverse Engineers an XPath Expression of a given Node in the DOM.
 * /*from ww w  .ja v  a2 s .  c  om*/
 * @param node
 *            the given node.
 * @return string xpath expression (e.g., "/html[1]/body[1]/div[3]").
 */
public static String getXPathExpression(Node node) {
    Object xpathCache = node.getUserData(FULL_XPATH_CACHE);
    if (xpathCache != null) {
        return xpathCache.toString();
    }
    Node parent = node.getParentNode();

    if ((parent == null) || parent.getNodeName().contains("#document")) {
        String xPath = "/" + node.getNodeName() + "[1]";
        node.setUserData(FULL_XPATH_CACHE, xPath, null);
        return xPath;
    }

    StringBuffer buffer = new StringBuffer();

    if (parent != node) {
        buffer.append(getXPathExpression(parent));
        buffer.append("/");
    }

    buffer.append(node.getNodeName());

    List<Node> mySiblings = getSiblings(parent, node);

    for (int i = 0; i < mySiblings.size(); i++) {
        Node el = mySiblings.get(i);

        if (el.equals(node)) {
            buffer.append('[').append(Integer.toString(i + 1)).append(']');
            // Found so break;
            break;
        }
    }
    String xPath = buffer.toString();
    node.setUserData(FULL_XPATH_CACHE, xPath, null);
    return xPath;
}

From source file:de.betterform.xml.xforms.model.Instance.java

public static ModelItem createModelItem(Node node) {
    String id = Model.generateModelItemId();
    ModelItem modelItem;//from ww  w  .  j  av  a2 s . co m
    if (node.getNodeType() == Node.ELEMENT_NODE) {
        modelItem = new XercesElementImpl(id);
    } else {
        modelItem = new XercesNodeImpl(id);
    }
    modelItem.setNode(node);

    Node parentNode;
    if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
        parentNode = ((Attr) node).getOwnerElement();
    } else {
        parentNode = node.getParentNode();
    }
    if (parentNode != null) {
        ModelItem parentItem = (ModelItem) parentNode.getUserData("");
        if (parentItem == null) {
            parentItem = createModelItem(parentNode);
        }

        modelItem.setParent(parentItem);
    }

    node.setUserData("", modelItem, null);
    return modelItem;
}

From source file:com.twinsoft.convertigo.beans.core.Sequence.java

private static Node cloneNodeWithUserData(Node node, boolean recurse) {
    if (node != null) {
        Object node_output = node.getUserData(Step.NODE_USERDATA_OUTPUT);

        Node clonedNode = node.cloneNode(false);
        clonedNode.setUserData(Step.NODE_USERDATA_OUTPUT, node_output, null);

        if (node.getNodeType() == Node.ELEMENT_NODE) {
            // attributes
            NamedNodeMap attributeMap = clonedNode.getAttributes();
            for (int i = 0; i < attributeMap.getLength(); i++) {
                Node clonedAttribute = attributeMap.item(i);
                String attr_name = clonedAttribute.getNodeName();
                Object attr_output = ((Element) node).getAttributeNode(attr_name)
                        .getUserData(Step.NODE_USERDATA_OUTPUT);
                clonedAttribute.setUserData(Step.NODE_USERDATA_OUTPUT, attr_output, null);
            }/*from  w w  w.  ja v  a 2 s.  c  o  m*/

            // recurse on element child nodes only
            if (recurse && node.hasChildNodes()) {
                NodeList list = node.getChildNodes();
                for (int i = 0; i < list.getLength(); i++) {
                    Node clonedChild = cloneNodeWithUserData(list.item(i), recurse);
                    if (clonedChild != null) {
                        clonedNode.appendChild(clonedChild);
                    }
                }
            }
        }

        return clonedNode;
    }
    return null;
}

From source file:com.twinsoft.convertigo.beans.core.Sequence.java

private static Node setOutputUserData(Node node, Object value, boolean recurse) {
    if (node != null) {
        // set output mode as userdata (element or attribute)
        node.setUserData(Step.NODE_USERDATA_OUTPUT, value, null);

        // recurse on element child nodes only
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            if (recurse && node.hasChildNodes()) {
                NodeList list = node.getChildNodes();
                for (int i = 0; i < list.getLength(); i++) {
                    setOutputUserData(list.item(i), value, recurse);
                }// w  ww.  j a  va 2 s.  co  m
            }
        }
    }
    return node;
}

From source file:com.bstek.dorado.view.config.XmlDocumentPreprocessor.java

@SuppressWarnings("unchecked")
private void postProcessNodeReplacement(Element element) {
    Document ownerDocument = element.getOwnerDocument();
    Node child = element.getFirstChild();
    while (child != null) {
        Node nextChild = child.getNextSibling();
        if (child instanceof Element) {
            if (child.getUserData("dorado.delete") != null) {
                List<Element> replaceContent = (List<Element>) child.getUserData("dorado.replace");
                if (replaceContent != null) {
                    for (Element el : replaceContent) {
                        Element clonedElement = (Element) ownerDocument.importNode(el, true);
                        element.insertBefore(clonedElement, child);
                    }//from w  ww  .  ja v  a 2 s.c  o m
                    child.setUserData("dorado.replace", null, null);
                }
                element.removeChild(child);
                child.setUserData("dorado.delete", null, null);
            }
        }
        child = nextChild;
    }
}

From source file:net.sourceforge.pmd.lang.xml.ast.DOMLineNumbers.java

private void setBeginLocation(Node n, int index) {
    if (n != null) {
        n.setUserData(XmlNode.BEGIN_LINE, toLine(index), null);
        n.setUserData(XmlNode.BEGIN_COLUMN, toColumn(index), null);
    }//from   ww  w .  java  2  s.  c o  m
}

From source file:net.sourceforge.pmd.lang.xml.ast.DOMLineNumbers.java

private void setEndLocation(Node n, int index) {
    if (n != null) {
        n.setUserData(XmlNode.END_LINE, toLine(index), null);
        n.setUserData(XmlNode.END_COLUMN, toColumn(index), null);
    }/*from www  .j  a  v  a 2s .co  m*/
}

From source file:org.apache.ode.bpel.compiler.v2.xquery10.compiler.XQuery10ExpressionCompilerImpl.java

private void doJaxpCompile(OXQuery10ExpressionBPEL20 out, Expression source) throws CompilationException {
    String xqueryStr;/*from  w  w w  . j  av  a 2 s . c om*/
    Node node = source.getExpression();
    if (node == null) {
        throw new IllegalStateException("XQuery string and xpath node are both null");
    }
    if (node.getNodeType() != Node.TEXT_NODE && node.getNodeType() != Node.ELEMENT_NODE
            && node.getNodeType() != Node.CDATA_SECTION_NODE) {
        throw new CompilationException(__msgs.errUnexpectedNodeTypeForXPath(DOMUtils.domToString(node)));
    }
    xqueryStr = DOMUtils.domToString(node);
    xqueryStr = xqueryStr.trim();
    if (xqueryStr.length() == 0) {
        throw new CompilationException(__msgs.warnXPath20Syntax(DOMUtils.domToString(node), "empty string"));
    }

    try {
        XQDataSource xqds = new SaxonXQDataSource();
        XQConnection xqconn = xqds.getConnection();

        __log.debug("Compiling expression " + xqueryStr);
        Configuration configuration = ((SaxonXQConnection) xqconn).getConfiguration();
        configuration.setAllNodesUntyped(true);
        configuration.setHostLanguage(Configuration.XQUERY);

        XQStaticContext staticContext = xqconn.getStaticContext();
        JaxpFunctionResolver funcResolver = new JaxpFunctionResolver(_compilerContext, out,
                source.getNamespaceContext(), _bpelNS);
        JaxpVariableResolver variableResolver = new JaxpVariableResolver(_compilerContext, out);

        XQueryDeclarations declarations = new XQueryDeclarations();
        NSContext nsContext = source.getNamespaceContext();
        Set<String> prefixes = nsContext.getPrefixes();
        if (!nsContext.getUriSet().contains(Namespaces.ODE_EXTENSION_NS)) {
            nsContext.register("ode", Namespaces.ODE_EXTENSION_NS);
        }
        for (String prefix : prefixes) {
            String uri = nsContext.getNamespaceURI(prefix);
            staticContext.declareNamespace(prefix, uri);
            if ("".equals(prefix)) {
                declarations.declareDefaultElementNamespace(uri);
            } else if ("bpws".equals(prefix)) {
                declarations.declareNamespace("bpws", "java:" + Constants.XQUERY_FUNCTION_HANDLER_COMPILER);
            } else {
                declarations.declareNamespace(prefix, uri);
            }
        }
        declarations.declareVariable(getQName(nsContext, Namespaces.ODE_EXTENSION_NS, "pid"),
                getQName(nsContext, Namespaces.XML_SCHEMA, "integer"));
        Map<URI, Source> schemaDocuments = _compilerContext.getSchemaSources();
        for (URI schemaUri : schemaDocuments.keySet()) {
            Source schemaSource = schemaDocuments.get(schemaUri);
            // Don't add schema sources, since our Saxon library is not schema-aware. 
            // configuration.addSchemaSource(schemaSource);
        }
        configuration.setSchemaValidationMode(Validation.SKIP);
        List<OScope.Variable> variables = _compilerContext.getAccessibleVariables();
        Map<QName, QName> variableTypes = new HashMap<QName, QName>();
        for (String variableName : getVariableNames(xqueryStr)) {
            OScope.Variable variable = getVariable(variables, variableName);
            if (variable == null) {
                continue;
            }
            OVarType type = variable.type;
            QName nameQName = getNameQName(variableName);
            QName typeQName = getTypeQName(variableName, type);
            variableTypes.put(nameQName, typeQName);
            String prefix = typeQName.getPrefix();
            if (prefix == null || "".equals(prefix.trim())) {
                prefix = getPrefixForUri(nsContext, typeQName.getNamespaceURI());
            }
            // don't declare typed variables, as our engine is not schema-aware
            // declarations.declareVariable(variable.name, typeQName);
            declarations.declareVariable(variableName);
        }

        // Add implicit declarations as prolog to the user-defined XQuery
        out.xquery = declarations.toString() + xqueryStr;

        // Check the XQuery for compilation errors 
        xqconn.setStaticContext(staticContext);
        XQPreparedExpression exp = xqconn.prepareExpression(out.xquery);

        // Pre-evaluate variables and functions by executing query  
        node.setUserData(XQuery10BpelFunctions.USER_DATA_KEY_FUNCTION_RESOLVER, funcResolver, null);
        exp.bindItem(XQConstants.CONTEXT_ITEM, xqconn.createItemFromNode(node, xqconn.createNodeType()));
        // Bind external variables to dummy runtime values
        for (QName variable : exp.getAllUnboundExternalVariables()) {
            QName typeQName = variableTypes.get(variable);
            Object value = variableResolver.resolveVariable(variable);
            if (typeQName != null) {
                if (value.getClass().getName().startsWith("java.lang")) {
                    exp.bindAtomicValue(variable, value.toString(),
                            xqconn.createAtomicType(XQItemType.XQBASETYPE_ANYATOMICTYPE));
                } else if (value instanceof Node) {
                    exp.bindNode(variable, (Node) value, xqconn.createNodeType());
                } else if (value instanceof NodeList) {
                    NodeList nodeList = (NodeList) value;
                    ArrayList nodeArray = new ArrayList();
                    for (int i = 0; i < nodeList.getLength(); i++) {
                        nodeArray.add(nodeList.item(i));
                    }
                    XQSequence sequence = xqconn.createSequence(nodeArray.iterator());
                    exp.bindSequence(variable, sequence);
                }
            }
        }
        // evaluate the expression so as to initialize the variables
        try {
            exp.executeQuery();
        } catch (XQException xpee) {
            // swallow errors caused by uninitialized variables 
        }
    } catch (XQException xqe) {
        __log.debug(xqe);
        __log.info("Couldn't validate properly expression " + xqueryStr);
    } catch (WrappedResolverException wre) {
        if (wre._compilationMsg != null)
            throw new CompilationException(wre._compilationMsg, wre);
        if (wre.getCause() instanceof CompilationException)
            throw (CompilationException) wre.getCause();
        throw wre;
    }
}

From source file:org.apache.ode.bpel.elang.xquery10.compiler.XQuery10ExpressionCompilerImpl.java

private void doJaxpCompile(OXQuery10ExpressionBPEL20 out, Expression source) throws CompilationException {
    String xqueryStr;//ww w.  j  a v  a  2  s  . c  o m
    Node node = source.getExpression();
    if (node == null) {
        throw new CompilationException(__msgs.errEmptyExpression(source.getURI(),
                new QName(source.getElement().getNamespaceURI(), source.getElement().getNodeName())));
    }
    if (node.getNodeType() != Node.TEXT_NODE && node.getNodeType() != Node.ELEMENT_NODE
            && node.getNodeType() != Node.CDATA_SECTION_NODE) {
        throw new CompilationException(__msgs.errUnexpectedNodeTypeForXPath(DOMUtils.domToString(node)));
    }
    xqueryStr = DOMUtils.domToString(node);
    xqueryStr = xqueryStr.trim();
    if (xqueryStr.length() == 0) {
        throw new CompilationException(__msgs.warnXPath20Syntax(DOMUtils.domToString(node), "empty string"));
    }

    try {
        XQDataSource xqds = new SaxonXQDataSource(new Configuration());
        XQConnection xqconn = xqds.getConnection();

        __log.debug("Compiling expression " + xqueryStr);
        Configuration configuration = ((SaxonXQConnection) xqconn).getConfiguration();
        configuration.setAllNodesUntyped(true);
        configuration.setHostLanguage(Configuration.XQUERY);

        XQStaticContext staticContext = xqconn.getStaticContext();
        JaxpFunctionResolver funcResolver = new JaxpFunctionResolver(_compilerContext, out,
                source.getNamespaceContext(), _bpelNS);
        JaxpVariableResolver variableResolver = new JaxpVariableResolver(_compilerContext, out);

        XQueryDeclarations declarations = new XQueryDeclarations();
        NSContext nsContext = source.getNamespaceContext();
        Set<String> prefixes = nsContext.getPrefixes();
        if (!nsContext.getUriSet().contains(Namespaces.ODE_EXTENSION_NS)) {
            nsContext.register("ode", Namespaces.ODE_EXTENSION_NS);
        }
        for (String prefix : prefixes) {
            String uri = nsContext.getNamespaceURI(prefix);
            staticContext.declareNamespace(prefix, uri);
            if ("".equals(prefix)) {
                declarations.declareDefaultElementNamespace(uri);
            } else if ("bpws".equals(prefix)) {
                declarations.declareNamespace("bpws", "java:" + Constants.XQUERY_FUNCTION_HANDLER_COMPILER);
            } else {
                declarations.declareNamespace(prefix, uri);
            }
        }
        declarations.declareVariable(getQName(nsContext, Namespaces.ODE_EXTENSION_NS, "pid"),
                getQName(nsContext, Namespaces.XML_SCHEMA, "integer"));
        //            Map<URI, Source> schemaDocuments = _compilerContext.getSchemaSources();
        //            for (URI schemaUri : schemaDocuments.keySet()) {
        //               Source schemaSource = schemaDocuments.get(schemaUri);
        //               // Don't add schema sources, since our Saxon library is not schema-aware.
        //               // configuration.addSchemaSource(schemaSource);
        //            }
        configuration.setSchemaValidationMode(Validation.SKIP);
        List<OScope.Variable> variables = _compilerContext.getAccessibleVariables();
        Map<QName, QName> variableTypes = new HashMap<QName, QName>();
        for (String variableName : getVariableNames(xqueryStr)) {
            OScope.Variable variable = getVariable(variables, variableName);
            if (variable == null) {
                continue;
            }
            OVarType type = variable.type;
            QName nameQName = getNameQName(variableName);
            QName typeQName = getTypeQName(variableName, type);
            variableTypes.put(nameQName, typeQName);
            String prefix = typeQName.getPrefix();
            if (prefix == null || "".equals(prefix.trim())) {
                prefix = getPrefixForUri(nsContext, typeQName.getNamespaceURI());
            }
            // don't declare typed variables, as our engine is not schema-aware
            // declarations.declareVariable(variable.name, typeQName);
            declarations.declareVariable(variableName);
        }

        // Add implicit declarations as prolog to the user-defined XQuery
        out.xquery = declarations.toString() + xqueryStr;

        // Check the XQuery for compilation errors
        xqconn.setStaticContext(staticContext);
        XQPreparedExpression exp = xqconn.prepareExpression(out.xquery);

        // Pre-evaluate variables and functions by executing query
        node.setUserData(XQuery10BpelFunctions.USER_DATA_KEY_FUNCTION_RESOLVER, funcResolver, null);
        exp.bindItem(XQConstants.CONTEXT_ITEM, xqconn.createItemFromNode(node, xqconn.createNodeType()));
        // Bind external variables to dummy runtime values
        for (QName variable : exp.getAllUnboundExternalVariables()) {
            QName typeQName = variableTypes.get(variable);
            Object value = variableResolver.resolveVariable(variable);
            if (typeQName != null) {
                if (value.getClass().getName().startsWith("java.lang")) {
                    exp.bindAtomicValue(variable, value.toString(),
                            xqconn.createAtomicType(XQItemType.XQBASETYPE_ANYATOMICTYPE));
                } else if (value instanceof Node) {
                    exp.bindNode(variable, (Node) value, xqconn.createNodeType());
                } else if (value instanceof NodeList) {
                    NodeList nodeList = (NodeList) value;
                    ArrayList nodeArray = new ArrayList();
                    for (int i = 0; i < nodeList.getLength(); i++) {
                        nodeArray.add(nodeList.item(i));
                    }
                    XQSequence sequence = xqconn.createSequence(nodeArray.iterator());
                    exp.bindSequence(variable, sequence);
                }
            }
        }
        // evaluate the expression so as to initialize the variables
        try {
            exp.executeQuery();
        } catch (XQException xpee) {
            // swallow errors caused by uninitialized variables
        } finally {
            // reset the expression's user data, in order to avoid
            // serializing the function resolver in the compiled bpel file.
            if (node != null) {
                node.setUserData(XQuery10BpelFunctions.USER_DATA_KEY_FUNCTION_RESOLVER, null, null);
            }
        }
    } catch (XQException xqe) {
        __log.debug(xqe);
        __log.info("Couldn't validate properly expression " + xqueryStr);
        throw new CompilationException(
                __msgs.errXQuery10Syntax(xqueryStr, "Couldn't validate XQuery expression"));
    } catch (WrappedResolverException wre) {
        if (wre._compilationMsg != null)
            throw new CompilationException(wre._compilationMsg, wre);
        if (wre.getCause() instanceof CompilationException)
            throw (CompilationException) wre.getCause();
        throw wre;
    }
}