Example usage for org.dom4j VisitorSupport VisitorSupport

List of usage examples for org.dom4j VisitorSupport VisitorSupport

Introduction

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

Prototype

public VisitorSupport() 

Source Link

Usage

From source file:org.orbeon.oxf.processor.InstanceToParametersProcessor.java

License:Open Source License

public ProcessorOutput createOutput(String name) {
    final ProcessorOutput output = new ProcessorOutputImpl(InstanceToParametersProcessor.this, name) {
        public void readImpl(PipelineContext pipelineContext, final XMLReceiver xmlReceiver) {
            try {
                Element filterElement = readInputAsDOM4J(pipelineContext, INPUT_FILTER).getRootElement();
                Document instance = (Document) readInputAsDOM4J(pipelineContext, INPUT_INSTANCE).clone();
                DocumentWrapper instanceWrapper = new DocumentWrapper(instance,
                        ((LocationData) instance.getRootElement().getData()).getSystemID(),
                        XPathCache.getGlobalConfiguration());

                // Mark all nodes referenced by XPath expressions
                final Set<Object> markedNodes = new HashSet<Object>();
                for (Iterator i = filterElement.elements().iterator(); i.hasNext();) {
                    Element paramElement = (Element) i.next();
                    Attribute refAttribute = paramElement.attribute("ref");
                    String excludeRef = refAttribute.getValue();
                    PooledXPathExpression xpath = XPathCache.getXPathExpression(
                            instanceWrapper.getConfiguration(), instanceWrapper.wrap(instance), excludeRef,
                            new NamespaceMapping(Dom4jUtils.getNamespaceContextNoDefault(paramElement)),
                            getLocationData());

                    markedNodes.add(xpath.evaluateSingleToJavaReturnToPoolOrNull());
                }// w  w w .ja  v a  2 s  .  c om

                // See if all nodes are marked
                final boolean[] allMarked = { true };
                instance.accept(new VisitorSupport() {
                    public void visit(Element node) {
                        super.visit(node);
                        if (node.elements().size() == 0 && !markedNodes.contains(node))
                            allMarked[0] = false;
                    }

                    public void visit(Attribute node) {
                        super.visit(node);
                        if (!markedNodes.contains(node))
                            allMarked[0] = false;
                    }
                });

                // Output as SAX
                xmlReceiver.startDocument();
                xmlReceiver.startElement("", PARAMETERS_ELEMENT, PARAMETERS_ELEMENT, XMLUtils.EMPTY_ATTRIBUTES);
                if (!allMarked[0]) {
                    // If all the nodes of the instance map to parameters, we don't output the instance parameter
                    outputParameter("$instance", XFormsUtils.encodeXML(instance, false), xmlReceiver);
                }
                xmlReceiver.endElement("", PARAMETERS_ELEMENT, PARAMETERS_ELEMENT);
                xmlReceiver.endDocument();

            } catch (Exception e) {
                throw new OXFException(e);
            }
        }
    };
    addOutput(OUTPUT_DATA, output);
    return output;
}

From source file:org.orbeon.oxf.processor.sql.SQLProcessor.java

License:Open Source License

protected void execute(final PipelineContext context, XMLReceiver xmlReceiver) {
    try {//w  w w .ja v a  2 s. com
        // Cache, read and interpret the config input
        Config config = readCacheInputAsObject(context, getInputByName(INPUT_CONFIG),
                new CacheableInputReader<Config>() {
                    public Config read(PipelineContext context, ProcessorInput input) {
                        // Read the config input document
                        Node config = readInputAsDOM4J(context, input);
                        Document configDocument = config.getDocument();

                        // Extract XPath expressions and also check whether any XPath expression is used at all
                        // NOTE: This could be done through streaming below as well
                        // NOTE: For now, just match <sql:param select="/*" type="xs:base64Binary"/>
                        List xpathExpressions = new ArrayList();
                        boolean useXPathExpressions = false;
                        for (Iterator i = XPathUtils.selectIterator(configDocument,
                                "//*[namespace-uri() = '" + SQL_NAMESPACE_URI + "' and @select]"); i
                                        .hasNext();) {
                            Element element = (Element) i.next();
                            useXPathExpressions = true;
                            String typeAttribute = element.attributeValue("type");
                            if ("xs:base64Binary".equals(typeAttribute)) {
                                String selectAttribute = element.attributeValue("select");
                                xpathExpressions.add(selectAttribute);
                            }
                        }

                        // Normalize spaces. What this does is to coalesce adjacent text nodes, and to remove
                        // resulting empty text, unless the text is contained within a sql:text element.
                        configDocument.accept(new VisitorSupport() {
                            private boolean endTextSequence(Element element, Text previousText) {
                                if (previousText != null) {
                                    String value = previousText.getText();
                                    if (value == null || value.trim().equals("")) {
                                        element.remove(previousText);
                                        return true;
                                    }
                                }
                                return false;
                            }

                            @Override
                            public void visit(Element element) {
                                // Don't touch text within sql:text elements
                                if (!SQL_NAMESPACE_URI.equals(element.getNamespaceURI())
                                        || !"text".equals(element.getName())) {
                                    Text previousText = null;
                                    for (int i = 0, size = element.nodeCount(); i < size;) {
                                        Node node = element.node(i);
                                        if (node instanceof Text) {
                                            Text text = (Text) node;
                                            if (previousText != null) {
                                                previousText.appendText(text.getText());
                                                element.remove(text);
                                            } else {
                                                String value = text.getText();
                                                // Remove empty text nodes
                                                if (value == null || value.length() < 1) {
                                                    element.remove(text);
                                                } else {
                                                    previousText = text;
                                                    i++;
                                                }
                                            }
                                        } else {
                                            if (!endTextSequence(element, previousText))
                                                i++;
                                            previousText = null;
                                        }
                                    }
                                    endTextSequence(element, previousText);
                                }
                            }
                        });
                        // Create SAXStore
                        try {
                            final SAXStore store = new SAXStore();
                            final LocationSAXWriter locationSAXWriter = new LocationSAXWriter();
                            locationSAXWriter.setContentHandler(store);
                            locationSAXWriter.write(configDocument);
                            // Return the normalized document
                            return new Config(store, useXPathExpressions, xpathExpressions);
                        } catch (SAXException e) {
                            throw new OXFException(e);
                        }
                    }
                });

        // Either read the whole input as a DOM, or try to serialize
        Node data = null;
        XPathXMLReceiver xpathReceiver = null;

        // Check if the data input is connected
        boolean hasDataInput = getConnectedInputs().get(INPUT_DATA) != null;
        if (!hasDataInput && config.useXPathExpressions)
            throw new OXFException(
                    "The data input must be connected when the configuration uses XPath expressions.");
        if (!hasDataInput || !config.useXPathExpressions) {
            // Just use an empty document
            data = Dom4jUtils.NULL_DOCUMENT;
        } else {
            // There is a data input connected and there are some XPath expressions operating on it
            boolean useXPathContentHandler = false;
            if (config.xpathExpressions.size() > 0) {
                // Create XPath content handler
                final XPathXMLReceiver _xpathReceiver = new XPathXMLReceiver();
                // Add expressions and check whether we can try to stream
                useXPathContentHandler = true;
                for (Iterator i = config.xpathExpressions.iterator(); i.hasNext();) {
                    String expression = (String) i.next();
                    boolean canStream = _xpathReceiver.addExpresssion(expression, false);// FIXME: boolean nodeSet
                    if (!canStream) {
                        useXPathContentHandler = false;
                        break;
                    }
                }
                // Finish setting up the XPathContentHandler
                if (useXPathContentHandler) {
                    _xpathReceiver.setReadInputCallback(new Runnable() {
                        public void run() {
                            readInputAsSAX(context, INPUT_DATA, _xpathReceiver);
                        }
                    });
                    xpathReceiver = _xpathReceiver;
                }
            }
            // If we can't stream, read everything in
            if (!useXPathContentHandler)
                data = readInputAsDOM4J(context, INPUT_DATA);
        }

        // Try to read datasource input if any
        Datasource datasource = null;
        {
            List datasourceInputs = (List) getConnectedInputs().get(INPUT_DATASOURCE);
            if (datasourceInputs != null) {
                if (datasourceInputs.size() > 1)
                    throw new OXFException("At most one one datasource input can be connected.");
                ProcessorInput datasourceInput = (ProcessorInput) datasourceInputs.get(0);
                datasource = Datasource.getDatasource(context, this, datasourceInput);
            }
        }

        // Replay the config SAX store through the interpreter
        config.configInput.replay(
                new RootInterpreter(context, getPropertySet(), data, datasource, xpathReceiver, xmlReceiver));
    } catch (OXFException e) {
        throw e;
    } catch (Exception e) {
        throw new OXFException(e);
    }
}

From source file:org.orbeon.oxf.xforms.submission.XFormsModelSubmission.java

License:Open Source License

private Document reRootAndPrune(final NodeInfo currentNodeInfo, boolean resolvedRelevant,
        String resolvedAnnotate) {

    final Document documentToSubmit;
    if (currentNodeInfo instanceof VirtualNode) {
        final Node currentNode = (Node) ((VirtualNode) currentNodeInfo).getUnderlyingNode();

        // "A node from the instance data is selected, based on attributes on the submission
        // element. The indicated node and all nodes for which it is an ancestor are considered for
        // the remainder of the submit process. "
        if (currentNode instanceof Element) {
            // Create subset of document
            documentToSubmit = Dom4jUtils.createDocumentCopyParentNamespaces((Element) currentNode);
        } else {//w w w .ja  v a2  s  . com
            // Use entire instance document
            documentToSubmit = Dom4jUtils.createDocumentCopyElement(currentNode.getDocument().getRootElement());
        }

        if (resolvedRelevant) {
            // "Any node which is considered not relevant as defined in 6.1.4 is removed."
            final Node[] nodeToDetach = new Node[1];
            do {
                // NOTE: This is not very efficient, but at least we avoid NPEs that we would get by
                // detaching elements within accept(). Should implement a more efficient algorithm to
                // prune non-relevant nodes.
                nodeToDetach[0] = null;
                documentToSubmit.accept(new VisitorSupport() {

                    public final void visit(Element element) {
                        checkInstanceData(element);
                    }

                    public final void visit(Attribute attribute) {
                        checkInstanceData(attribute);
                    }

                    private void checkInstanceData(Node node) {
                        if (nodeToDetach[0] == null) {
                            // Check "relevant" MIP and remove non-relevant nodes
                            if (!InstanceData.getInheritedRelevant(node))
                                nodeToDetach[0] = node;
                        }
                    }
                });
                if (nodeToDetach[0] != null)
                    nodeToDetach[0].detach();

            } while (nodeToDetach[0] != null);
        }

        // Annotate with alerts if needed
        if (StringUtils.isNotBlank(resolvedAnnotate))
            annotateWithAlerts(containingDocument, documentToSubmit, resolvedAnnotate);

        // TODO: handle includenamespaceprefixes
    } else {
        // Submitting read-only instance backed by TinyTree (no MIPs to check)
        if (currentNodeInfo.getNodeKind() == org.w3c.dom.Node.ELEMENT_NODE) {
            documentToSubmit = TransformerUtils.tinyTreeToDom4j(currentNodeInfo);
        } else {
            documentToSubmit = TransformerUtils.tinyTreeToDom4j(currentNodeInfo.getRoot());
        }
    }
    return documentToSubmit;
}

From source file:org.orbeon.oxf.xforms.submission.XFormsSubmissionUtils.java

License:Open Source License

/**
 * Check whether an XML sub-tree satisfies validity and required MIPs.
 *
 * @param indentedLogger        logger/*from  www  .j  ava  2 s . com*/
 * @param startNode             node to check
 * @param recurse               whether to recurse into attributes and descendant nodes
 * @return                      true iif the sub-tree passes the checks
 */
public static boolean isSatisfiesValid(final IndentedLogger indentedLogger, final Node startNode,
        boolean recurse) {

    if (recurse) {
        // Recurse into attributes and descendant nodes
        final boolean[] instanceSatisfiesValidRequired = new boolean[] { true };
        startNode.accept(new VisitorSupport() {

            public final void visit(Element element) {
                final boolean valid = checkInstanceData(element);

                instanceSatisfiesValidRequired[0] &= valid;

                if (!valid && indentedLogger.isDebugEnabled()) {
                    indentedLogger.logDebug("", "found invalid element", "element name",
                            Dom4jUtils.elementToDebugString(element));
                }
            }

            public final void visit(Attribute attribute) {
                final boolean valid = checkInstanceData(attribute);

                instanceSatisfiesValidRequired[0] &= valid;

                if (!valid && indentedLogger.isDebugEnabled()) {
                    indentedLogger.logDebug("", "found invalid attribute", "attribute name",
                            Dom4jUtils.attributeToDebugString(attribute), "parent element",
                            Dom4jUtils.elementToDebugString(attribute.getParent()));
                }
            }

            private boolean checkInstanceData(Node node) {
                return InstanceData.getValid(node);
            }
        });
        return instanceSatisfiesValidRequired[0];
    } else {
        // Just check the current node
        return InstanceData.getValid(startNode);
    }
}

From source file:org.orbeon.oxf.xforms.submission.XFormsSubmissionUtils.java

License:Open Source License

/**
 * Create an application/x-www-form-urlencoded string, encoded in UTF-8, based on the elements and text content
 * present in an XML document.//from w  w w  . j a  v  a 2 s.c  o  m
 *
 * @param document      document to analyze
 * @param separator     separator character
 * @return              application/x-www-form-urlencoded string
 */
public static String createWwwFormUrlEncoded(final Document document, final String separator) {

    final StringBuilder sb = new StringBuilder(100);
    document.accept(new VisitorSupport() {
        public final void visit(Element element) {
            // We only care about elements

            final List children = element.elements();
            if (children == null || children.size() == 0) {
                // Only consider leaves
                final String text = element.getText();
                if (text != null && text.length() > 0) {
                    // Got one!
                    final String localName = element.getName();

                    if (sb.length() > 0)
                        sb.append(separator);

                    try {
                        sb.append(URLEncoder.encode(localName, "UTF-8"));
                        sb.append('=');
                        sb.append(URLEncoder.encode(text, "UTF-8"));
                        // TODO: check if line breaks will be correcly encoded as "%0D%0A"
                    } catch (UnsupportedEncodingException e) {
                        // Should not happen: UTF-8 must be supported
                        throw new OXFException(e);
                    }
                }
            }
        }
    });

    return sb.toString();
}

From source file:org.orbeon.oxf.xforms.submission.XFormsSubmissionUtils.java

License:Open Source License

/**
 * Implement support for XForms 1.1 section "11.9.7 Serialization as multipart/form-data".
 *
 * @param document          XML document to submit
 * @return                  MultipartRequestEntity
 *//* w  w w .ja  v a2s .co  m*/
public static MultipartEntity createMultipartFormData(final Document document) throws IOException {

    // Visit document
    final MultipartEntity multipartEntity = new MultipartEntity();
    document.accept(new VisitorSupport() {
        public final void visit(Element element) {
            try {
                // Only care about elements

                // Only consider leaves i.e. elements without children elements
                final List children = element.elements();
                if (children == null || children.size() == 0) {

                    final String value = element.getText();
                    {
                        // Got one!
                        final String localName = element.getName();
                        final QName nodeType = InstanceData.getType(element);

                        if (XMLConstants.XS_ANYURI_QNAME.equals(nodeType)) {
                            // Interpret value as xs:anyURI

                            if (InstanceData.getValid(element) && value.trim().length() > 0) {
                                // Value is valid as per xs:anyURI
                                // Don't close the stream here, as it will get read later when the MultipartEntity
                                // we create here is written to an output stream
                                addPart(multipartEntity, URLFactory.createURL(value).openStream(), element,
                                        value);
                            } else {
                                // Value is invalid as per xs:anyURI
                                // Just use the value as is (could also ignore it)
                                multipartEntity.addPart(localName,
                                        new StringBody(value, Charset.forName("UTF-8")));
                            }

                        } else if (XMLConstants.XS_BASE64BINARY_QNAME.equals(nodeType)) {
                            // Interpret value as xs:base64Binary

                            if (InstanceData.getValid(element) && value.trim().length() > 0) {
                                // Value is valid as per xs:base64Binary
                                addPart(multipartEntity,
                                        new ByteArrayInputStream(NetUtils.base64StringToByteArray(value)),
                                        element, null);
                            } else {
                                // Value is invalid as per xs:base64Binary
                                // Just use the value as is (could also ignore it)
                                multipartEntity.addPart(localName,
                                        new StringBody(value, Charset.forName("UTF-8")));
                            }
                        } else {
                            // Just use the value as is
                            multipartEntity.addPart(localName, new StringBody(value, Charset.forName("UTF-8")));
                        }
                    }
                }
            } catch (IOException e) {
                throw new OXFException(e);
            }
        }
    });

    return multipartEntity;
}

From source file:org.orbeon.oxf.xml.dom4j.Dom4jUtils.java

License:Open Source License

/**
 * Go over the Node and its children and make sure that there are no two contiguous text nodes so as to ensure that
 * XPath expressions run correctly. As per XPath 1.0 (http://www.w3.org/TR/xpath):
 *
 * "As much character data as possible is grouped into each text node: a text node never has an immediately
 * following or preceding sibling that is a text node."
 *
 * dom4j Text and CDATA nodes are combined together.
 *
 * @param nodeToNormalize Node hierarchy to normalize
 * @return                the input node, normalized
 */// w  w  w  .java2s  . c o  m
public static Node normalizeTextNodes(Node nodeToNormalize) {
    final List<Node> nodesToDetach = new ArrayList<Node>();
    nodeToNormalize.accept(new VisitorSupport() {
        public void visit(Element element) {
            final List children = element.content();
            Node previousNode = null;
            StringBuilder sb = null;
            for (Iterator i = children.iterator(); i.hasNext();) {
                final Node currentNode = (Node) i.next();
                if (previousNode != null) {
                    if (isTextOrCDATA(previousNode) && isTextOrCDATA(currentNode)) {
                        final CharacterData previousNodeText = (CharacterData) previousNode;
                        if (sb == null)
                            sb = new StringBuilder(previousNodeText.getText());
                        sb.append(currentNode.getText());
                        nodesToDetach.add(currentNode);
                    } else if (isTextOrCDATA(previousNode)) {
                        // Update node if needed
                        if (sb != null) {
                            previousNode.setText(sb.toString());
                        }
                        previousNode = currentNode;
                        sb = null;
                    } else {
                        previousNode = currentNode;
                        sb = null;
                    }
                } else {
                    previousNode = currentNode;
                    sb = null;
                }
            }
            // Update node if needed
            if (previousNode != null && sb != null) {
                previousNode.setText(sb.toString());
            }
        }
    });
    // Detach nodes only in the end so as to not confuse the acceptor above
    for (final Node currentNode : nodesToDetach) {
        currentNode.detach();
    }

    return nodeToNormalize;
}

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

License:Apache License

/**
 * ??Page//from   ww w.  j a  va2s .c om
 * 
 * @param pageClsStr
 * @param dataSrcClsStr
 * @param ele
 * @param fieldList 
 */
private void parsePage(final String pageClsStr, Element ele, final List<AutoField> fieldList) throws Exception {
    ele.accept(new VisitorSupport() {

        @Override
        public void visit(Element node) {
            if (!"field".equals(node.getName())) {
                return;
            }

            String fieldName = node.attributeValue("name");
            String type = node.attributeValue("type");
            if (fieldName == null || "".equals(fieldName) || type == null || "".equals(type)) {
                return;
            }

            AutoField autoField = new AutoField(fieldName, type);

            Object commentObj = node.getData();
            if (commentObj != null) {
                autoField.setComment(commentObj.toString().trim());
            }

            fieldList.add(autoField);
        }
    });
}

From source file:tokyo.northside.jrst.JRSTReader.java

License:Open Source License

/**
 * On commence par decouper tout le document en Element, puis on construit
 * l'article a partir de ces elements.//from   w  w w .  ja v a  2  s  . c  o m
 *
 * @param reader
 * @return le document cree
 * @throws Exception
 */
public Document read(Reader reader) throws Exception {
    JRSTLexer lexer = new JRSTLexer(reader);
    try {
        Element root = composeDocument(lexer);

        Document result = DocumentHelper.createDocument();
        result.setRootElement(root);

        root.accept(new VisitorSupport() {
            @Override
            public void visit(Element e) {
                // remove all level attribute
                e.addAttribute(LEVEL, null);
                // Constrution du sommaire
                String type = e.attributeValue(TYPE);
                if (type != null) {
                    if (type.equals(CONTENTS)) {
                        composeContents(e);
                        e.addAttribute(TYPE, null);
                    }
                }

                if (TRUE.equalsIgnoreCase(e.attributeValue(ATTR_INLINE))) {
                    e.addAttribute(ATTR_INLINE, null);
                    try {
                        inline(e);
                    } catch (DocumentException eee) {
                        if (log.isWarnEnabled()) {
                            log.warn("Can't inline text for " + e, eee);
                        }
                    } catch (UnsupportedEncodingException ee) {
                        if (log.isWarnEnabled()) {
                            log.warn("Unsupported encoding " + e, ee);
                        }
                    }
                }
            }
        });

        return result;
    } catch (Exception eee) {
        log.error(String.format("JRST parsing error line %d char %s:\n%s", lexer.getLineNumber(),
                lexer.getCharNumber(), lexer.readNotBlanckLine()));
        throw eee;
    }
}