Example usage for org.dom4j Node getUniquePath

List of usage examples for org.dom4j Node getUniquePath

Introduction

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

Prototype

String getUniquePath();

Source Link

Document

Returns the XPath expression which will return a nodeset of one node which is the current node.

Usage

From source file:com.cladonia.xngreditor.actions.ToolsStripTextAction.java

License:Open Source License

/**
 * The implementation of the validate action, called after a user action.
 * /*  w  w  w  .  j av a2s  .co  m*/
 * @param event
 *            the action event.
 */
public void actionPerformed(ActionEvent event) {

    if (dialog == null) {
        dialog = new ToolsStripTextDialog(parent, props);
    }
    //called to make sure that the model is up to date to
    //prevent any problems found when undo-ing etc.
    parent.getView().updateModel();
    //get the document
    final ExchangerDocument document = parent.getDocument();
    if (document.isError()) {
        MessageHandler.showError(parent, "Please make sure the document is well-formed.", "Parser Error");
        return;
    }
    //create temporary document
    String currentXPath = null;
    Node node = (Node) document.getLastNode(parent.getView().getEditor().getCursorPosition(), true);

    if (props.isUniqueXPath()) {
        currentXPath = node.getUniquePath();
    } else {
        currentXPath = node.getPath();
    }
    dialog.show(currentXPath);
    if (!dialog.isCancelled()) {
        parent.setWait(true);
        parent.setStatus("Stripping Document Text ...");
        // Run in Thread!!!
        Runnable runner = new Runnable() {

            public void run() {

                try {

                    if ((dialog.elementsCheckBox.isSelected()) || (dialog.attributesCheckBox.isSelected())) {

                        ExchangerDocument tempDoc = new ExchangerDocument(document.getText());
                        String newDocument = null;

                        if (dialog.xpathPanel.xpathBox.isSelected()) {
                            String xpathPredicate = dialog.xpathPanel.getXpathPredicate();
                            newDocument = treeWalk(tempDoc, xpathPredicate,
                                    dialog.elementsCheckBox.isSelected(),
                                    dialog.attributesCheckBox.isSelected(),
                                    dialog.mixedContentCheckBox.isSelected(), TRAVERSE_CHILDREN);
                        } else {

                            newDocument = treeWalk(tempDoc, dialog.elementsCheckBox.isSelected(),
                                    dialog.attributesCheckBox.isSelected(),
                                    dialog.mixedContentCheckBox.isSelected());
                        }
                        if (newDocument != null) {
                            if (dialog.toNewDocumentRadio.isSelected()) {
                                //user has selected to create the result as a
                                // new document
                                parent.open(new ExchangerDocument(newDocument), null);
                            } else {
                                parent.getView().getEditor().setText(newDocument);
                                SwingUtilities.invokeLater(new Runnable() {

                                    public void run() {

                                        parent.switchToEditor();
                                        parent.getView().updateModel();
                                    }
                                });
                            }
                        }
                    }
                } catch (Exception e) {
                    // This should never happen, just report and continue
                    MessageHandler.showError(parent, "Cannot Strip Document Text", "Tools Strip Text Error");
                }

                finally {
                    parent.setStatus("Done");
                    parent.setWait(false);
                }
            }
        };
        // Create and start the thread ...
        Thread thread = new Thread(runner);
        thread.start();
        //          }
    }
}

From source file:com.cladonia.xngreditor.actions.ToolsUppercaseAction.java

License:Open Source License

/**
 * The implementation of the validate action, called 
 * after a user action./*  www.  j a va2 s .co  m*/
 *
 * @param event the action event.
 */
public void actionPerformed(ActionEvent event) {
    if (dialog == null) {
        dialog = new ToolsUppercaseDialog(parent, props);
    }

    //called to make sure that the model is up to date to 
    //prevent any problems found when undo-ing etc.
    parent.getView().updateModel();

    final ExchangerDocument document = parent.getDocument();

    if (document.isError()) {
        MessageHandler.showError(parent, "Please make sure the document is well-formed.", "Parser Error");
        return;
    }

    String currentXPath = null;
    Node node = (Node) document.getLastNode(parent.getView().getEditor().getCursorPosition(), true);

    if (props.isUniqueXPath()) {
        currentXPath = node.getUniquePath();
    } else {
        currentXPath = node.getPath();
    }

    dialog.show(currentXPath);

    if (!dialog.isCancelled()) {

        parent.setWait(true);
        parent.setStatus("Changing Case ...");

        // Run in Thread!!!
        Runnable runner = new Runnable() {
            public void run() {
                try {

                    //make sure one of the options was selected
                    if ((dialog.elementsRadio.isSelected()) || (dialog.attributeRadio.isSelected())
                            || (dialog.elementsAndAttributesRadio.isSelected())) {
                        ExchangerDocument tempDoc = new ExchangerDocument(document.getText());

                        String newDocument = null;
                        boolean TRAVERSE_CHILDREN = true;

                        if (dialog.xpathPanel.xpathBox.isSelected()) {
                            String xpathPredicate = dialog.xpathPanel.getXpathPredicate();
                            newDocument = uppercase(tempDoc, xpathPredicate, dialog.elementsRadio.isSelected(),
                                    dialog.attributeRadio.isSelected(),
                                    dialog.elementsAndAttributesRadio.isSelected(), TRAVERSE_CHILDREN);

                        } else {

                            //set the string to the new empty document
                            newDocument = uppercase(tempDoc, dialog.elementsRadio.isSelected(),
                                    dialog.attributeRadio.isSelected(),
                                    dialog.elementsAndAttributesRadio.isSelected());
                        }
                        if (newDocument != null) {
                            if (dialog.toNewDocumentRadio.isSelected()) {
                                //user has selected to create the result as a new document
                                parent.open(new ExchangerDocument(newDocument), null);
                            } else {
                                parent.getView().getEditor().setText(newDocument);
                                SwingUtilities.invokeLater(new Runnable() {
                                    public void run() {
                                        parent.switchToEditor();

                                        parent.getView().updateModel();
                                    }
                                });
                            }
                        } //end if
                    } //end if

                } catch (Exception e) {
                    // This should never happen, just report and continue
                    MessageHandler.showError(parent, "Cannot Convert To Uppercase", "Tools Uppercase Error");
                } finally {
                    parent.setStatus("Done");
                    parent.setWait(false);
                }
            }//end run  

        };//end runnable

        // Create and start the thread ...
        Thread thread = new Thread(runner);
        thread.start();
        //          }

    }
}

From source file:com.cladonia.xngreditor.ExchangerView.java

License:Open Source License

public void setSelectedNode(Node node, boolean endTag, Vector namespaces, int y) {
    while (node != null) {
        Vector results = document.search(node.getUniquePath(), namespaces);

        if (results.size() > 0) {
            Node n = (Node) results.elementAt(0);

            if (n != null) {
                if (current instanceof Editor) {
                    if (n instanceof XElement) {
                        ((Editor) current).selectElement((XElement) n, endTag, y);
                    } else if (n instanceof XAttribute) {
                        ((Editor) current).selectAttribute((XAttribute) n, y);
                    }// www.j a  va 2 s .c o m
                } else if (current instanceof Viewer) {
                    if (n instanceof XElement) {
                        ((Viewer) current).setSelectedElement((XElement) n, endTag, y);
                    } else if (n instanceof XAttribute) {
                        ((Viewer) current).setSelectedElement((XElement) ((XAttribute) n).getParent(), false,
                                y);
                    }
                } else if (current instanceof Designer) {
                    if (n instanceof XElement) {
                        ((Designer) current).setSelectedNode((XElement) n, y);
                    } else if (n instanceof XAttribute) {
                        ((Designer) current).setSelectedNode((XAttribute) n, y);
                    }
                    /*} else if ( current instanceof Grid) {
                       if ( n instanceof XElement) {
                          ((Grid)current).setSelectedElement( (XElement)n, null);
                       } else if ( n instanceof XAttribute) {
                          ((Grid)current).setSelectedElement( (XAttribute)n, null);
                       }*/
                } else if (current instanceof PluginViewPanel) {
                    if (n instanceof XElement) {
                        ((PluginViewPanel) current).setSelectedElement((XElement) n);
                    } else if (n instanceof XAttribute) {
                        ((PluginViewPanel) current).setSelectedElement((XAttribute) n);
                    }
                }

            }
            return;
        }

        endTag = false;
        node = (Node) node.getParent();
    }
}

From source file:com.dtolabs.shared.resources.ResourceXMLParser.java

License:Apache License

/**
 * Return a String describing the DOM node's location and parent type name
 *
 * @param e the node/*from  w  w w.j a v a  2s .c o m*/
 *
 * @return string describing xpath location and parent "type" element name
 */
protected static String reportNodeErrorLocation(final Node e) {
    return "at xpath " + e.getUniquePath();
}

From source file:hk.hku.cecid.piazza.commons.util.PropertyTree.java

License:Open Source License

/**
 * Gets all the existing property xpaths.
 * //from   w  w w .j av  a 2  s.  c om
 * @return all the existing property xpaths.
 * @see hk.hku.cecid.piazza.commons.util.PropertySheet#propertyNames()
 */
public Enumeration propertyNames() {
    Iterator nodes = getPropertyNodes("//*[count(./*)=0]").iterator();
    Vector propNames = new Vector();

    while (nodes.hasNext()) {
        Node node = (Node) nodes.next();
        propNames.addElement(node.getUniquePath());
    }

    return propNames.elements();
}

From source file:it.eng.qbe.datasource.configuration.dao.fileimpl.InLineFunctionsDAOFileImpl.java

License:Mozilla Public License

public HashMap<String, InLineFunction> loadInLineFunctions(String dialect) {

    FileInputStream in;/*  w  w w .jav  a 2s.  c om*/
    InputStream is;
    Document document;
    String group;
    String name;
    String desc;
    String nParams;
    String code;
    List functionsNodes;
    Iterator it;
    Node functionNode;
    Node dialectNode;

    logger.debug("IN");

    in = null;
    try {
        if (getInLineFunctions() != null && getInLineFunctions().size() > 0) {
            logger.info("Functions for dialect " + dialect + " yet loaded.");
            return getInLineFunctions();
        }

        is = getClass().getClassLoader().getResourceAsStream(FUNCTIONS_FILE_NAME);
        Assert.assertNotNull(is, "Input stream cannot be null");

        logger.debug("Functions will be loaded from file [" + FUNCTIONS_FILE_NAME + "]");

        document = readFile(is);
        Assert.assertNotNull(document, "Document cannot be null");

        functionsNodes = document.selectNodes("//" + ROOT_TAG + "/" + FIELD_TAG + "");
        logger.debug("Found [" + functionsNodes.size() + "] functions");

        it = functionsNodes.iterator();
        while (it.hasNext()) {
            functionNode = (Node) it.next();
            group = functionNode.valueOf("@" + FIELD_TAG_GROUP_ATTR);
            name = functionNode.valueOf("@" + FIELD_TAG_NAME_ATTR);
            desc = functionNode.valueOf("@" + FIELD_TAG_DESC_ATTR);
            nParams = functionNode.valueOf("@" + FIELD_TAG_NPARAMS_ATTR);
            dialectNode = null;
            //get the code function only for the dialect managed
            if (dialect.equalsIgnoreCase(QuerySerializationConstants.DIALECT_MYSQL)) {
                dialectNode = functionNode
                        .selectSingleNode(functionNode.getUniquePath() + "/" + FIELD_TAG_MYSQL_DIALECT + "");
            } else if (dialect.equalsIgnoreCase(QuerySerializationConstants.DIALECT_HSQL)) {
                dialectNode = functionNode
                        .selectSingleNode(functionNode.getUniquePath() + "/" + FIELD_TAG_HQL_DIALECT + "");
            } else if (dialect.equalsIgnoreCase(QuerySerializationConstants.DIALECT_ORACLE)
                    || dialect.equalsIgnoreCase(QuerySerializationConstants.DIALECT_ORACLE9i10g)) {
                dialectNode = functionNode
                        .selectSingleNode(functionNode.getUniquePath() + "/" + FIELD_TAG_ORACLE_DIALECT + "");
            } else if (dialect.equalsIgnoreCase(QuerySerializationConstants.DIALECT_INGRES)) {
                dialectNode = functionNode
                        .selectSingleNode(functionNode.getUniquePath() + "/" + FIELD_TAG_INGRES_DIALECT + "");
            } else if (dialect.equalsIgnoreCase(QuerySerializationConstants.DIALECT_POSTGRES)) {
                dialectNode = functionNode
                        .selectSingleNode(functionNode.getUniquePath() + "/" + FIELD_TAG_POSTGRES_DIALECT + "");
            } else {
                dialectNode = functionNode.selectSingleNode(
                        functionNode.getUniquePath() + "/" + FIELD_TAG_SQLSERVER_DIALECT + "");
            }
            code = "";
            if (dialectNode != null) {
                code = dialectNode.valueOf("@" + FIELD_TAG_CODE_ATTR);
            }
            InLineFunction func = new InLineFunction();
            func.setDialect(dialect);
            func.setName(name);
            func.setGroup(group);
            func.setDesc(desc);
            func.setnParams(Integer.valueOf(nParams));
            func.setCode(code);
            addInLineFunction(func);
            logger.debug("Function [" + mapInLineFunctions.get(func.name) + "] loaded succesfully");
        }

    } catch (Throwable t) {
        if (t instanceof DAOException)
            throw (DAOException) t;
        throw new DAOException(
                "An unpredicted error occurred while loading functions on file [" + FUNCTIONS_FILE_NAME + "]",
                t);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                throw new DAOException(
                        "Impossible to properly close stream to file file [" + FUNCTIONS_FILE_NAME + "]", e);
            }
        }
        logger.debug("OUT");
    }

    return getInLineFunctions();
}

From source file:org.craftercms.core.processors.impl.template.TemplateProcessor.java

License:Open Source License

/**
 * Processes the content of certain nodes (found by the {@code NodeScanner} in the item's descriptor as templates,
 * by compiling the node text templates through the {@code templateCompiler} and then processing the compiled
 * template with a model returned by {@code modelFactory}.
 *
 * @throws ItemProcessingException if an error occurred while processing a template
 *///  w  w w  .ja v a 2s . c o m
public Item process(Context context, CachingOptions cachingOptions, Item item) throws ItemProcessingException {
    String descriptorUrl = item.getDescriptorUrl();
    Document descriptorDom = item.getDescriptorDom();

    if (descriptorDom != null) {
        List<Node> templateNodes = templateNodeScanner.scan(descriptorDom);
        if (CollectionUtils.isNotEmpty(templateNodes)) {
            for (Node templateNode : templateNodes) {
                String templateNodePath = templateNode.getUniquePath();

                if (logger.isDebugEnabled()) {
                    logger.debug("Template found in " + descriptorUrl + " at " + templateNodePath);
                }

                String templateId = templateNodePath + "@" + descriptorUrl;
                String template = templateNode.getText();
                IdentifiableStringTemplateSource templateSource = new IdentifiableStringTemplateSource(
                        templateId, template);

                Object model = modelFactory.getModel(item, templateNode, template);
                StringWriter output = new StringWriter();

                try {
                    CompiledTemplate compiledTemplate = templateCompiler.compile(templateSource);
                    compiledTemplate.process(model, output);
                } catch (TemplateException e) {
                    throw new ItemProcessingException("Unable to process the template " + templateId, e);
                }

                templateNode.setText(output.toString());
            }
        }
    }

    return item;
}

From source file:org.danann.cernunnos.runtime.XmlGrammar.java

License:Apache License

public Phrase newPhrase(Node n) {

    // Assertions...
    if (n == null) {
        String msg = "Argument 'n [Node]' cannot be null.";
        throw new IllegalArgumentException(msg);
    }/* w  w  w . j  a va  2  s . com*/

    List<String> chunks = new LinkedList<String>();
    String chunkMe = n.getText();
    while (chunkMe.length() != 0) {
        if (chunkMe.startsWith(Phrase.OPEN_PHRASE_DELIMITER)) {
            chunks.add(Phrase.OPEN_PHRASE_DELIMITER);
            chunkMe = chunkMe.substring(2);
        } else {
            chunks.add(chunkMe.substring(0, 1));
            chunkMe = chunkMe.substring(1);
        }
    }

    List<Phrase> children = new LinkedList<Phrase>();
    StringBuffer buffer = new StringBuffer();
    int openCount = 0;
    for (String chunk : chunks) {
        switch (openCount) {
        case 0:
            if (chunk.equals(Phrase.OPEN_PHRASE_DELIMITER)) {
                if (buffer.length() > 0) {
                    children.add(new LiteralPhrase(buffer.toString()));
                    buffer.setLength(0);
                }
                ++openCount;
            } else {
                buffer.append(chunk);
            }
            break;
        default:
            if (chunk.equals(Phrase.OPEN_PHRASE_DELIMITER)) {
                ++openCount;
                buffer.append(chunk);
            } else if (chunk.equals(Phrase.CLOSE_PHRASE_DELIMITER)) {
                --openCount;
                if (openCount == 0) {

                    // Time to create a dynamic component...
                    String expression = buffer.toString();
                    String name = null; // Name of the phrase to use...
                    String nested = null; // Content passed to the phrase

                    // Determine if a Phrase impl was specified or if we should use the default...
                    int openParenIndex = expression.indexOf("(");
                    if (openParenIndex != -1 && expression.endsWith(")")) {
                        // A phrase impl was specified -- use it!
                        try {
                            name = expression.substring(0, openParenIndex);
                            nested = expression.substring(expression.indexOf("(") + 1, expression.length() - 1);
                        } catch (Throwable t) {
                            String msg = "The specified expression is not well formed:  " + expression;
                            throw new RuntimeException(msg, t);
                        }
                    } else {
                        // Use the default phrase impl...
                        name = Grammar.DEFAULT_PHRASE_IMPL.getName();
                        nested = expression;
                    }

                    Entry y = getEntry(name, Entry.Type.PHRASE);
                    Phrase p = null;
                    try {

                        // Create & bootstrap the phrase...
                        EntityConfig config = prepareEntryConfig(y, fac.createText(nested), n.getUniquePath());
                        Phrase enclosed = (Phrase) y.getFormula().getImplementationClass().newInstance();
                        enclosed.init(config);
                        p = new RuntimePhraseDecorator(enclosed, config);

                    } catch (Throwable t) {
                        String msg = "Unable to create the specified phrase:  " + name;
                        throw new RuntimeException(msg, t);
                    }

                    children.add(p);
                    buffer.setLength(0);
                } else {
                    buffer.append(chunk);
                }
            } else {
                buffer.append(chunk);
            }
            break;
        }
    }
    if (buffer.length() > 0) {
        // Add anything that's left...
        children.add(new LiteralPhrase(buffer.toString()));
    }

    return new ConcatenatingPhrase(children);

}

From source file:org.danann.cernunnos.runtime.XmlGrammar.java

License:Apache License

private EntityConfig prepareEntryConfig(Entry n, Node d) {
    return prepareEntryConfig(n, d, d.getUniquePath());
}

From source file:org.danann.cernunnos.runtime.XmlGrammar.java

License:Apache License

private EntityConfig prepareEntryConfig(Entry n, Node d, String source) {

    // Assertions...
    if (n == null) {
        String msg = "Argument 'n [Entry]' cannot be null.";
        throw new IllegalArgumentException(msg);
    }//from   w  w w. j a  v a  2 s .c o m
    if (d == null) {
        String msg = "Argument 'd [Element]' cannot be null.";
        throw new IllegalArgumentException(msg);
    }
    if (source == null) {
        String msg = "Argument 'source' cannot be null.";
        throw new IllegalArgumentException(msg);
    }

    // Report any use of deprecated entries...
    if (n.isDeprecated()) {
        StringBuilder msg = new StringBuilder();
        msg.append("USE OF DEPRECATED API:  A deprecated ENTRY was referenced.").append("\n\t\tEntry Name:  ")
                .append(n.getName()).append("\n\t\tDeprecated Since:  ").append(n.getDeprecation().getVersion())
                .append("\n\t\tEntry Type:  ").append(n.getType()).append("\n\t\tSource:  ").append(source)
                .append("\n");
        log.warn(msg.toString());
    }

    try {

        Formula f = n.getFormula();

        Map<Reagent, Object> mappings = new HashMap<Reagent, Object>();
        List<Reagent> needed = new ArrayList<Reagent>(f.getReagents());
        needed.removeAll(n.getMappings().keySet());
        for (Reagent r : needed) {
            Object value = r.getReagentType().evaluate(this, d, r.getXpath());

            // Report any use of deprecated reagents...
            if (r.isDeprecated() && value != null) {
                StringBuilder msg = new StringBuilder();
                msg.append("USE OF DEPRECATED API:  A value was specified for a deprecated REAGENT.")
                        .append("\n\t\tReagent Name:  ").append(r.getName()).append("\n\t\tDeprecated Since:  ")
                        .append(r.getDeprecation().getVersion()).append("\n\t\tEntry Name:  ")
                        .append(n.getName()).append("\n\t\tEntry Type:  ").append(n.getType())
                        .append("\n\t\tSource:  ").append(d.getUniquePath() + "/" + r.getXpath()).append("\n");
                log.warn(msg.toString());
            }

            if (value == null) {
                // First see if there's a default...
                if (r.hasDefault()) {
                    value = r.getDefault();
                } else {
                    String msg = "The required expression '" + r.getXpath()
                            + "' is missing from the following node:  " + d.asXML();
                    throw new RuntimeException(msg);
                }
            }
            mappings.put(r, value);
        }
        mappings.putAll(n.getMappings());

        String entryName = null;
        if (n.getType().equals(Entry.Type.TASK)) {
            entryName = "<" + n.getName() + ">";
        } else if (n.getType().equals(Entry.Type.PHRASE)) {
            entryName = "${" + n.getName() + "}";
        } else {
            throw new RuntimeException("Unsupported Entry Type:  " + n.getType());
        }

        return new SimpleEntityConfig(this, entryName, source, n.getFormula(), mappings);

    } catch (Throwable t) {
        StringBuilder msg = new StringBuilder();
        msg.append("Unable to prepare an EntityConfig based on the specified information:")
                .append("\n\t\tEntity Name:  ").append(n.getName()).append("\n\t\tSource:  ").append(source);
        throw new RuntimeException(msg.toString(), t);
    }

}