Example usage for org.w3c.dom Node getUserData

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

Introduction

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

Prototype

public Object getUserData(String key);

Source Link

Document

Retrieves the object associated to a key on a this node.

Usage

From source file:Main.java

/**
 * Gets the index of the Node instance's "current" child from user data on
 * the Node instance.//from  w w w  .j  a  v  a  2  s.  c  om
 * 
 * @param node Node instance from which to get index.
 * @return Index of node's "current" child. A value of -1 indicates
 * inability to get index from node.
 */
public static int getCurrentChildIndex(Node node) {
    int index = -1;
    if (node != null) {
        Object obj = node.getUserData(KEY_CURRENT_CHILD_INDEX);
        if (obj instanceof Integer) {
            index = ((Integer) obj).intValue();
        }
    }
    return index;
}

From source file:Main.java

/**
 * Reverse Engineers an XPath Expression of a given Node in the DOM.
 * /*w  ww.j ava2 s. com*/
 * @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.constraints.RelevanceSelector.java

private static boolean isEnabled(Node nodeImpl) {
    ModelItem item = (ModelItem) nodeImpl.getUserData("");
    return item == null || item.isRelevant();
}

From source file:de.betterform.xml.xforms.model.constraints.RelevanceSelector.java

private static void addElement(Element relevantParent, Node instanceNode) {
    Document relevantDocument = relevantParent.getOwnerDocument();
    Element relevantElement;//from   w  w  w. j a va2 s.c  o  m

    if (instanceNode.getNamespaceURI() == null) {
        relevantElement = relevantDocument.createElement(instanceNode.getNodeName());
    } else {
        relevantElement = relevantDocument.createElementNS(instanceNode.getNamespaceURI(),
                instanceNode.getNodeName());
    }

    // needed in instance serializer ...
    relevantElement.setUserData("", instanceNode.getUserData(""), null);

    relevantParent.appendChild(relevantElement);
    addAttributes(relevantElement, instanceNode);
    addChildren(relevantElement, instanceNode);
}

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

public static ModelItem createModelItem(Node node) {
    String id = Model.generateModelItemId();
    ModelItem modelItem;/*from w w  w . jav a2 s  . c  om*/
    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:de.betterform.agent.web.servlet.ErrorServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    WebUtil.nonCachingResponse(response);
    //pick up the exception details
    String xpath = "unknown";
    String cause = "";
    String msg = (String) getSessionAttribute(request, "betterform.exception.message");
    if (msg != null) {
        int start = msg.indexOf("::");
        if (start > 3) {
            xpath = msg.substring(start + 2);
            msg = msg.substring(0, start);
        }/*from w ww . j  a  va  2s . c  o  m*/
        //todo: don't we need an 'else' here?
    }
    Exception ex = (Exception) getSessionAttribute(request, "betterform.exception");
    if (ex != null && ex.getCause() != null && ex.getCause().getMessage() != null) {
        cause = ex.getCause().getMessage();
    }

    //create XML structure for exception details
    Element rootNode = DOMUtil.createRootElement("error");
    DOMUtil.appendElement(rootNode, "context", request.getContextPath());
    DOMUtil.appendElement(rootNode, "url", request.getSession().getAttribute("betterform.referer").toString());
    DOMUtil.appendElement(rootNode, "xpath", xpath);
    DOMUtil.appendElement(rootNode, "message", msg);
    DOMUtil.appendElement(rootNode, "cause", cause);

    //transform is different depending on exception type
    if (ex instanceof XFormsErrorIndication) {
        Object o = ((XFormsErrorIndication) ex).getContextInfo();
        if (o instanceof HashMap) {
            HashMap<String, Object> map = (HashMap) ((XFormsErrorIndication) ex).getContextInfo();
            if (map.size() != 0) {
                Element contextinfo = rootNode.getOwnerDocument().createElement("contextInfo");
                rootNode.appendChild(contextinfo);
                for (Map.Entry<String, Object> entry : map.entrySet()) {
                    DOMUtil.appendElement(rootNode, entry.getKey(), entry.getValue().toString());
                }
            }
        }
        //todo: check -> there are contextInfos containing a simple string but seems to be integrated within above error message already - skip for now
        /*
                    else{
                    }
        */
        Document hostDoc = (Document) getSessionAttribute(request, "betterform.hostDoc");
        String serializedDoc = DOMUtil.serializeToString(hostDoc);
        //reparse
        try {
            byte bytes[] = serializedDoc.getBytes("UTF-8");
            Document newDoc = PositionalXMLReader.readXML(new ByteArrayInputStream(bytes));
            DOMUtil.prettyPrintDOM(newDoc);
            //eval xpath
            Node n = XPathUtil.evaluateAsSingleNode(newDoc, xpath);
            String linenumber = (String) n.getUserData("lineNumber");
            DOMUtil.appendElement(rootNode, "lineNumber", linenumber);

            DOMUtil.prettyPrintDOM(rootNode);

            WebUtil.doTransform(getServletContext(), response, newDoc, "highlightError.xsl", rootNode);
        } catch (Exception e) {
            e.printStackTrace();
        }

    } else {
        WebUtil.doTransform(getServletContext(), response, rootNode.getOwnerDocument(), "error.xsl", null);
    }
}

From source file:de.betterform.connector.serializer.MultipartRelatedSerializer.java

protected void visitNode(Map cache, Node node, MimeMultipart multipart) throws Exception {

    ModelItem item = (ModelItem) node.getUserData("");
    if (item != null && item.getDeclarationView().getDatatype() != null
            && item.getDeclarationView().getDatatype().equalsIgnoreCase("anyURI")) {
        String name = item.getFilename();
        if (name == null || item.getValue() == null || item.getValue().equals("")) {
            return;
        }/*ww  w .  j  av a  2 s. c  o  m*/

        String cid = (String) cache.get(name);
        if (cid == null) {
            int count = multipart.getCount();
            cid = name + "@part" + (count + 1);

            MimeBodyPart part = new MimeBodyPart();
            part.setContentID("<" + cid + ">");

            DataHandler dh = new DataHandler(new ModelItemDataSource(item));
            part.setDataHandler(dh);

            part.addHeader("Content-Type", item.getMediatype());
            part.addHeader("Content-Transfer-Encoding", "base64");
            part.setDisposition("attachment");
            part.setFileName(name);
            multipart.addBodyPart(part);
            cache.put(name, cid);
        }

        Element element = (Element) node;
        // remove text node
        NodeList list = node.getChildNodes();
        for (int i = 0; i < list.getLength(); i++) {
            Node n = list.item(i);
            if (n.getNodeType() != Node.TEXT_NODE) {
                continue;
            }
            n.setNodeValue("cid:" + cid);
            break;
        }
    } else {
        NodeList list = node.getChildNodes();
        for (int i = 0; i < list.getLength(); i++) {
            Node n = list.item(i);
            if (n.getNodeType() == Node.ELEMENT_NODE) {
                visitNode(cache, n, multipart);
            }
        }
    }
}

From source file:de.betterform.xml.events.impl.DefaultXMLEventService.java

/**
 * Dispatches the specified event to the given target.
 *
 * @param target the event target.//  w w  w  .j a v  a  2  s .  co m
 * @param type specifies the event type.
 * @param bubbles specifies wether the event can bubble.
 * @param cancelable specifies wether the event's default action can be prevented.
 * @param context optionally specifies contextual information.
 * @return <code>true</code> if one of the event listeners called
 * <code>preventDefault</code>, otherwise <code>false</code>.
 */
public boolean dispatch(EventTarget target, String type, boolean bubbles, boolean cancelable, Object context) {
    if (LOGGER.isDebugEnabled()) {
        if (target instanceof Node) {
            Node node = (Node) target;
            Object object = node.getUserData("");
            if (object instanceof XFormsElement) {
                //Note: the cast seems pointless here but makes sure the right toString method is called
                LOGGER.debug("dispatch event: " + type + " to " + ((XFormsElement) object).toString());
            }
        } else {
            LOGGER.debug("dispatch event: " + type + " to " + target);
        }
    }

    XMLEvent event = this.eventFactory.createXMLEvent(type);
    this.eventInitializer.initXMLEvent(event, type, bubbles, cancelable, context);

    long start;
    long end;

    start = System.currentTimeMillis();
    boolean preventDefault = target.dispatchEvent(event);
    end = System.currentTimeMillis();
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("dispatch event: " + type + " handling needed " + (end - start) + " ms");
    }

    if (!event.getCancelable() || !preventDefault) {
        DefaultAction action = lookup(target, type);

        if (action != null) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("dispatch event: " + type + " default action at " + action);
            }

            // todo: set event phase without downcast ?
            ((XercesXMLEvent) event).eventPhase = XMLEvent.DEFAULT_ACTION;
            start = System.currentTimeMillis();
            action.performDefault(event);
            end = System.currentTimeMillis();
            if (LOGGER.isTraceEnabled()) {
                LOGGER.trace("dispatch event: " + type + " default action needed " + (end - start) + " ms");
            }
        }
    }

    return preventDefault;
}

From source file:de.betterform.xml.xforms.action.ToggleAction.java

/**
 * Performs the <code>toggle</code> action.
 *
 * @throws XFormsException if an error occurred during <code>toggle</code>
 * processing./*from  w  w  w  . ja v a 2  s . c  o  m*/
 */
public void perform() throws XFormsException {
    String evaluatedCaseId = caseId.getValue();
    Object caseObject = null;
    if (isRepeated()) {
        caseObject = null;
        RepeatItem repeatItem = (RepeatItem) this.container.lookup(getRepeatItemId());
        Node caseNode = de.betterform.xml.xpath.impl.saxon.XPathUtil.getAsNode(
                XPathUtil.evaluate(repeatItem.getElement(), ".//*[@caseId='" + caseId.getValue() + "']"), 1);
        if (caseNode != null) {
            caseObject = caseNode.getUserData("");
        }
    }
    if (caseObject == null) {
        caseObject = this.container.lookup(evaluatedCaseId);
    }

    if (caseObject == null || !(caseObject instanceof Case)) {
        throw new XFormsBindingException("invalid case id at " + DOMUtil.getCanonicalPath(this.getElement()),
                this.target, evaluatedCaseId);
    }

    // obtain case and switch elements
    Case toSelect = (Case) caseObject;
    Switch switchElement = toSelect.getSwitch();
    Case isSelected = switchElement.getSelected();

    // perform selection/deselection
    if (!toSelect.getId().equals(isSelected.getId())) {
        isSelected.deselect();
    }

    if (!isSelected.getId().equals(toSelect.getId())) {
        toSelect.select();
    }

    // dispatch xforms-deselect and xforms-select events
    if (!toSelect.getId().equals(isSelected.getId())) {
        this.container.dispatch(isSelected.getTarget(), XFormsEventNames.DESELECT, null);
    }
    if (!isSelected.getId().equals(toSelect.getId())) {
        this.container.dispatch(toSelect.getTarget(), XFormsEventNames.SELECT, null);
    }

    // dispatch internal betterform event
    HashMap map = new HashMap();
    map.put("selected", toSelect.getId());
    map.put("deselected", isSelected.getId());
    this.container.dispatch(switchElement.getTarget(), BetterFormEventNames.SWITCH_TOGGLED, map);

    //as we did an optimization to only update selected 'case' elements we need to refresh after a toggle
    doRefresh(true);
}

From source file:de.betterform.xml.xforms.model.constraints.DependencyGraph.java

/**
 * determines which nodes are referenced by given xpath expression and returns them as nodes.
 *
 * @param xpath - the xpath expression under examination
 * @return a list with nodes referenced in given xpath
 *//*  w  w  w. j ava2s. c  o m*/
public Vector getXPathRefNodes(BetterFormXPathContext relativeContext, String xpath, Set references)
        throws XFormsException {
    Vector refNodes = new Vector();
    Iterator pathes = references.iterator();

    while (pathes.hasNext()) {
        String refPath = pathes.next().toString();

        List resultSet = XPathCache.getInstance().evaluate(relativeContext, refPath);

        for (int i = 0; i < resultSet.size(); ++i) {
            Node node = (Node) XPathUtil.getAsNode(resultSet, i + 1);
            ModelItem modelItem = null;
            if (node != null) {
                modelItem = (ModelItem) node.getUserData("");
            }

            if (modelItem == null && node != null) {
                modelItem = Instance.createModelItem(node);
            }

            if (modelItem != null) {
                // add *existing* reference node
                refNodes.add(modelItem.getNode());
            }
        }
    }

    return refNodes;
}