Example usage for org.jdom2 Element getQualifiedName

List of usage examples for org.jdom2 Element getQualifiedName

Introduction

In this page you can find the example usage for org.jdom2 Element getQualifiedName.

Prototype

public String getQualifiedName() 

Source Link

Document

Returns the full name of the element, in the form [namespacePrefix]:[localName].

Usage

From source file:com.c4om.utils.xmlutils.XPathUtils.java

License:Apache License

/**
 * It returns a path to a single element. The element (and its ancestors) is distinguished via its 
 * attributes set./*from w ww.  j a  va2 s.c  o m*/
 * @param currentElement the element whose path is to be calculated
 * @param contextElement the element to which a relative path will be calculated (null for an absolute path).
 * @return the path.
 * @throws IllegalArgumentException if the currentElement is not descendant of the contextElement
 * 
 */
public static String generateAttributeBasedPath(Element currentElement, Element contextElement) {
    StringBuilder builder = new StringBuilder();
    Element parent = currentElement.getParentElement();
    if (contextElement != null) {
        IteratorIterable<Element> descendants = contextElement.getDescendants(Filters.element());
        Set<Element> descendantsSet = ImmutableSet.copyOf((Iterable<Element>) descendants);
        if (!descendantsSet.contains(currentElement)) {
            throw new IllegalArgumentException("The provided element is not descendant of the stopElement");
        }
    }
    if (parent != contextElement) {
        String pathToParent = generateAttributeBasedPath(parent, contextElement);
        builder.append(pathToParent);
    } else if (contextElement != null) {
        builder.insert(0, ".");
    }
    builder.append("/");
    builder.append(currentElement.getQualifiedName());
    String filter = "[" + generateAttributesFilter(currentElement.getAttributes()) + "]";
    builder.append(filter);
    String result = builder.toString();
    return result;
}

From source file:com.izforge.izpack.util.xmlmerge.action.InsertAction.java

License:Open Source License

@Override
public void perform(Element originalElement, Element patchElement, Element outputParentElement) {

    if (patchElement == null && originalElement != null) {
        outputParentElement.addContent((Element) originalElement.clone());

    } else {/*from  ww w .  j  a  v  a  2 s  .  com*/
        List<Content> outputContent = outputParentElement.getContent();

        Iterator<Content> it = outputContent.iterator();

        int lastIndex = outputContent.size();

        while (it.hasNext()) {
            Content content = it.next();

            if (content instanceof Element) {
                Element element = (Element) content;

                if (element.getQualifiedName().equals(patchElement.getQualifiedName())) {
                    lastIndex = outputParentElement.indexOf(element);
                }
            }
        }

        List<Content> toAdd = new ArrayList<Content>();
        toAdd.add(patchElement);
        outputContent.addAll(Math.min(lastIndex + 1, outputContent.size()), toAdd);
    }
}

From source file:com.izforge.izpack.util.xmlmerge.matcher.AbstractTagMatcher.java

License:Open Source License

@Override
public boolean matches(Element originalElement, Element patchElement) {
    return equalsString(originalElement.getQualifiedName(), patchElement.getQualifiedName(),
            ignoreCaseElementName());//w  w w .  j  a v  a  2  s. c  om
}

From source file:com.kixeye.kixmpp.handler.KixmppEventEngine.java

License:Apache License

/**
 * Publishes a stanza.//w  w  w .  ja  v a  2s. com
 * 
 * @param channel
 * @param stanza
 */
public void publishStanza(Channel channel, Element stanza) {
    String to = stanza.getAttributeValue("to");

    DispatchQueue queue;

    try {
        if (to != null) {
            queue = queues.get("address:" + to);
        } else {
            queue = queues.get("channel:" + channel.hashCode());
        }
    } catch (ExecutionException e) {
        throw new RuntimeException(e);
    }

    if (to != null) {
        Set<KixmppStanzaHandler> recipientHandlers = stanzaHandlers
                .get(Tuple.from(stanza.getQualifiedName(), KixmppJid.fromRawJid(to)));

        if (recipientHandlers != null) {
            for (KixmppStanzaHandler handler : recipientHandlers) {
                queue.execute(new ExecuteStanzaHandler(handler, channel, stanza));
            }
        }

        recipientHandlers = stanzaHandlers.get(Tuple.from(HANDLER_WILDCARD, KixmppJid.fromRawJid(to)));

        if (recipientHandlers != null) {
            for (KixmppStanzaHandler handler : recipientHandlers) {
                queue.execute(new ExecuteStanzaHandler(handler, channel, stanza));
            }
        }
    }

    Set<KixmppStanzaHandler> globalHandlers = stanzaHandlers.get(Tuple.from(stanza.getQualifiedName()));

    if (globalHandlers != null) {
        for (KixmppStanzaHandler handler : globalHandlers) {
            queue.execute(new ExecuteStanzaHandler(handler, channel, stanza));
        }
    }

    globalHandlers = stanzaHandlers.get(Tuple.from(HANDLER_WILDCARD));

    if (globalHandlers != null) {
        for (KixmppStanzaHandler handler : globalHandlers) {
            queue.execute(new ExecuteStanzaHandler(handler, channel, stanza));
        }
    }
}

From source file:com.kixeye.kixmpp.KixmppCodec.java

License:Apache License

/**
 * @see io.netty.handler.codec.ByteToMessageCodec#decode(io.netty.channel.ChannelHandlerContext, io.netty.buffer.ByteBuf, java.util.List)
 *///from  w  w w .  java  2s. c  o m
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    if (logger.isDebugEnabled()) {
        logger.debug("Received: [{}]", in.toString(StandardCharsets.UTF_8));
    }

    int retryCount = 0;
    Exception thrownException = null;

    // feed the data into the async xml input feeded
    byte[] data = new byte[in.readableBytes()];
    in.readBytes(data);

    if (streamReader != null) {
        while (retryCount < 2) {
            try {
                asyncInputFeeder.feedInput(data, 0, data.length);

                int event = -1;

                while (isValidEvent(event = streamReader.next())) {
                    // handle stream start/end
                    if (streamReader.getDepth() == STANZA_ELEMENT_DEPTH - 1) {
                        if (event == XMLStreamConstants.END_ELEMENT) {
                            out.add(new KixmppStreamEnd());

                            asyncInputFeeder.endOfInput();
                            streamReader.close();

                            streamReader = null;
                            asyncInputFeeder = null;

                            break;
                        } else if (event == XMLStreamConstants.START_ELEMENT) {
                            StAXElementBuilder streamElementBuilder = new StAXElementBuilder(true);

                            streamElementBuilder.process(streamReader);

                            out.add(new KixmppStreamStart(null, true));
                        }
                        // only handle events that have element depth of 2 and above (everything under <stream:stream>..)
                    } else if (streamReader.getDepth() >= STANZA_ELEMENT_DEPTH) {
                        // if this is the beginning of the element and this is at stanza depth
                        if (event == XMLStreamConstants.START_ELEMENT
                                && streamReader.getDepth() == STANZA_ELEMENT_DEPTH) {
                            elementBuilder = new StAXElementBuilder(true);
                            elementBuilder.process(streamReader);

                            // get the constructed element
                            Element element = elementBuilder.getElement();

                            if ("stream:stream".equals(element.getQualifiedName())) {
                                throw new RuntimeException("Starting a new stream.");
                            }
                            // if this is the ending of the element and this is at stanza depth
                        } else if (event == XMLStreamConstants.END_ELEMENT
                                && streamReader.getDepth() == STANZA_ELEMENT_DEPTH) {
                            elementBuilder.process(streamReader);

                            // get the constructed element
                            Element element = elementBuilder.getElement();

                            out.add(element);

                            // just process the event
                        } else {
                            elementBuilder.process(streamReader);
                        }
                    }
                }

                break;
            } catch (Exception e) {
                retryCount++;

                logger.info("Attempting to recover from impropper XML: " + e.getMessage());

                thrownException = e;

                try {
                    streamReader.close();
                } finally {
                    streamReader = inputFactory.createAsyncXMLStreamReader();
                    asyncInputFeeder = streamReader.getInputFeeder();
                }
            }
        }

        if (retryCount > 1) {
            throw thrownException;
        }
    }
}

From source file:cz.muni.fi.mir.mathmlcanonicalization.modules.UnaryOperatorRemover.java

License:Apache License

private void removeUnaryOperator(final Element rootElem) {

    assert rootElem != null;

    /* Presentation MathML */
    final Set<String> pmCharsToRemove = getPropertySet(PM_UNARY_OPERATORS_TO_REMOVE);

    if (!pmCharsToRemove.isEmpty()) {

        // Unary operators
        List<Element> pmElemsToRemove = xpPMUnaryOperators.evaluate(rootElem);
        for (Element toRemove : pmElemsToRemove) {
            if (pmCharsToRemove.contains(toRemove.getValue())) {
                LOGGER.finest("Removing element '" + toRemove.getQualifiedName() + "' with value '"
                        + toRemove.getValue() + "'.");
                toRemove.detach();/*  ww w .  j a v a  2 s . c  o  m*/
            } else {
                LOGGER.finest("Skipping element '" + toRemove.getQualifiedName() + "' with value '"
                        + toRemove.getValue() + "'.");
            }
        }

        // Second of the double operators
        pmElemsToRemove = xpPMSecondOperatorInDoubleOperators.evaluate(rootElem);
        for (Element toRemove : pmElemsToRemove) {
            if (pmCharsToRemove.contains(toRemove.getValue())) {
                LOGGER.finest("Removing the second element out of double elements '"
                        + toRemove.getQualifiedName() + "' with value '" + toRemove.getValue() + "'.");
                toRemove.detach();
            } else {
                LOGGER.finest("Skipping the second element out of double elements '"
                        + toRemove.getQualifiedName() + "' with value '" + toRemove.getValue() + "'.");
            }
        }

    }

    LOGGER.finer("RemoveUnaryOperator Presentation MathML finished");

    /* Content MathML */
    List<Element> applyWithTwoChildrens = xpCMApplyWithTwoChildrens.evaluate(rootElem);
    final Set<String> cmOperatorsToRemove = getPropertySet(CM_UNARY_OPERATORS_TO_REMOVE);

    for (Element applyElem : applyWithTwoChildrens) {
        Element operator = applyElem.getChildren().get(0);
        if (cmOperatorsToRemove.contains(operator.getName())) {
            Element operand = applyElem.getChildren().get(1);
            LOGGER.finest("Removing operator '" + operator.getQualifiedName() + "' for operand '"
                    + operand.getQualifiedName() + "'.");
            operand.detach();
            Element parent = applyElem.getParentElement();
            int applyElemIndex = parent.indexOf(applyElem);
            parent.setContent(applyElemIndex, operand);
            applyElem.detach();
        }
    }

    LOGGER.finer("RemoveUnaryOperator Content MathML finished");

}

From source file:org.graphwalker.io.GraphML.java

License:Open Source License

/**
 * Parses the graphml file, and returns the model as a edu.uci.ics.jung.graph.impl.Graph
 * /*from w  w  w  . j  a  va 2 s  .  c om*/
 * @param fileName The graphml file
 * @return The graph
 */
private Graph parseFile(String fileName) {
    Graph graph = new Graph();
    graph.setFileKey(fileName);
    SAXBuilder parser = new SAXBuilder();

    try {
        logger.debug("Parsing file: " + fileName);
        Document doc = parser.build(Util.getFile(fileName));

        // Parse all vertices (nodes)
        Iterator<Element> iter_node = doc.getDescendants(new ElementFilter("node"));
        while (iter_node.hasNext()) {
            Object o = iter_node.next();
            if (o instanceof Element) {
                Element element = (Element) o;
                if (element.getAttributeValue("yfiles.foldertype") != null) {
                    logger.debug("  Excluded node: " + element.getAttributeValue("yfiles.foldertype"));
                    continue;
                }
                Iterator<Element> iterUMLNoteIter = element.getDescendants(new ElementFilter("UMLNoteNode"));
                if (iterUMLNoteIter.hasNext()) {
                    Iterator<Element> iter_label = element.getDescendants(new ElementFilter("NodeLabel"));
                    if (iter_label.hasNext()) {
                        Object o3 = iter_label.next();
                        Element nodeLabel = (Element) o3;
                        logger.debug("  Full name: '" + nodeLabel.getQualifiedName() + "'");
                        logger.debug("  Name: '" + nodeLabel.getTextTrim() + "'");
                        graph.setDescriptionKey(nodeLabel.getTextTrim());
                    }
                    continue;
                }
                logger.debug("  id: " + element.getAttributeValue("id"));

                // Used to remember which vertex to store the image location.
                Vertex currentVertex = null;

                Iterator<Element> iterNodeLabel = element.getDescendants(new ElementFilter("NodeLabel"));
                while (iterNodeLabel.hasNext()) {
                    Object o2 = iterNodeLabel.next();
                    if (o2 instanceof Element) {
                        Element nodeLabel = (Element) o2;
                        logger.debug("  Full name: '" + nodeLabel.getQualifiedName() + "'");
                        logger.debug("  Name: '" + nodeLabel.getTextTrim() + "'");
                        String str = nodeLabel.getTextTrim();

                        Vertex v = new Vertex();
                        graph.addVertex(v);
                        currentVertex = v;

                        // Parse description
                        Iterator<Element> iter_data = element.getDescendants(new ElementFilter("data"));
                        while (iter_data.hasNext()) {
                            Object o3 = iter_data.next();
                            if (o instanceof Element) {
                                Element data = (Element) o3;
                                if (!data.getAttributeValue("key").equals("d5"))
                                    continue;
                                v.setDesctiptionKey(data.getText());
                                break;
                            }
                        }

                        v.setIdKey(element.getAttributeValue("id"));
                        v.setVisitedKey(0);
                        v.setFileKey(fileName);
                        v.setFullLabelKey(str);
                        v.setIndexKey(getNewVertexAndEdgeIndex());
                        v.setLabelKey(Vertex.getLabel(str));
                        v.setMergeKey(AbstractElement.isMerged(str));
                        v.setNoMergeKey(AbstractElement.isNoMerge(str));
                        v.setBlockedKey(AbstractElement.isBlocked(str));
                        v.setSwitchModelKey(Vertex.isSwitchModel(str));

                        Integer index = AbstractElement.getIndex(str);
                        if (index != 0) {
                            v.setIndexKey(index);
                        }

                        v.setReqTagKey(AbstractElement.getReqTags(str));
                    }
                }

                // Extract any manual test instructions
                Iterator<Element> iterData = element.getDescendants(new ElementFilter("data"));
                while (iterData.hasNext() && currentVertex != null) {
                    Object o2 = iterData.next();
                    if (o2 instanceof Element) {
                        Element data = (Element) o2;
                        if (!data.getContent().isEmpty() && data.getContent(0) != null) {
                            String text = data.getContent(0).getValue().trim();
                            if (!text.isEmpty()) {
                                logger.debug("  Data: '" + text + "'");
                                currentVertex.setManualInstructions(text);
                            }
                        }
                    }
                }

                // Using the yEd editor, an image can be used to depict the vertex.
                // When merging multiple
                // graphs into one, the code below, stores the image location, which
                // will be used when
                // writing that merged graphml file.
                Iterator<Element> iterImage = element.getDescendants(new ElementFilter("Image"));
                while (iterImage.hasNext() && currentVertex != null) {
                    Object o2 = iterImage.next();
                    if (o2 instanceof Element) {
                        Element image = (Element) o2;
                        if (image.getAttributeValue("href") != null) {
                            logger.debug("  Image: '" + image.getAttributeValue("href") + "'");
                            currentVertex.setImageKey(image.getAttributeValue("href"));
                        }
                    }
                }
                Iterator<Element> iterGeometry = element.getDescendants(new ElementFilter("Geometry"));
                while (iterGeometry.hasNext() && currentVertex != null) {
                    Object o2 = iterGeometry.next();
                    if (o2 instanceof Element) {
                        Element geometry = (Element) o2;
                        logger.debug("  width: '" + geometry.getAttributeValue("width") + "'");
                        logger.debug("  height: '" + geometry.getAttributeValue("height") + "'");
                        logger.debug("  x position: '" + geometry.getAttributeValue("x") + "'");
                        logger.debug("  y position: '" + geometry.getAttributeValue("y") + "'");
                        currentVertex.setWidth(Float.parseFloat(geometry.getAttributeValue("width")));
                        currentVertex.setHeight(Float.parseFloat(geometry.getAttributeValue("height")));
                        currentVertex.setLocation(
                                new Point2D.Float(Float.parseFloat(geometry.getAttributeValue("x")),
                                        Float.parseFloat(geometry.getAttributeValue("y"))));
                    }
                }
                Iterator<Element> iterFill = element.getDescendants(new ElementFilter("Fill"));
                while (iterFill.hasNext() && currentVertex != null) {
                    Object o2 = iterFill.next();
                    if (o2 instanceof Element) {
                        Element fill = (Element) o2;
                        logger.debug("  fill color: '" + fill.getAttributeValue("color") + "'");
                        currentVertex.setFillColor(new Color(
                                Integer.parseInt(fill.getAttributeValue("color").replace("#", ""), 16)));
                    }
                }
            }
        }

        Object[] vertices = graph.getVertices().toArray();

        // Parse all edges (arrows or transitions)
        Iterator<Element> iter_edge = doc.getDescendants(new ElementFilter("edge"));
        while (iter_edge.hasNext()) {
            Object o = iter_edge.next();
            if (o instanceof Element) {
                Element element = (Element) o;
                logger.debug("  id: " + element.getAttributeValue("id"));

                Edge e = new Edge();

                Iterator<Element> iter2 = element.getDescendants(new ElementFilter("EdgeLabel"));
                Element edgeLabel = null;
                if (iter2.hasNext()) {
                    Object o2 = iter2.next();
                    if (o2 instanceof Element) {
                        edgeLabel = (Element) o2;
                        logger.debug("  Full name: '" + edgeLabel.getQualifiedName() + "'");
                        logger.debug("  Name: '" + edgeLabel.getTextTrim() + "'");
                        logger.debug(" Edge label x: " + edgeLabel.getAttributeValue("x"));
                        logger.debug(" Edge label y: " + edgeLabel.getAttributeValue("y"));
                        logger.debug(" Edge label width: " + edgeLabel.getAttributeValue("width"));
                        logger.debug(" Edge label height: " + edgeLabel.getAttributeValue("height"));
                        e.setLabelHeight(Float.parseFloat(edgeLabel.getAttributeValue("height")));
                        e.setLabelWidth(Float.parseFloat(edgeLabel.getAttributeValue("width")));
                        e.setLabelLocation(new Point2D.Float(Float.parseFloat(edgeLabel.getAttributeValue("x")),
                                Float.parseFloat(edgeLabel.getAttributeValue("y"))));
                    }
                }
                Iterator<Element> iter3 = element.getDescendants(new ElementFilter("Path"));
                Element edgePath = null;
                if (iter3.hasNext()) {
                    Object o3 = iter3.next();
                    if (o3 instanceof Element) {
                        edgePath = (Element) o3;
                        logger.debug("  Path sx: '" + edgePath.getAttributeValue("sx"));
                        logger.debug("  Path sy: '" + edgePath.getAttributeValue("sy"));
                        logger.debug("  Path tx: '" + edgePath.getAttributeValue("tx"));
                        logger.debug("  Path ty: '" + edgePath.getAttributeValue("ty"));
                        e.setPathSourceLocation(
                                new Point2D.Float(Float.parseFloat(edgePath.getAttributeValue("sx")),
                                        Float.parseFloat(edgePath.getAttributeValue("sy"))));
                        e.setPathTargetLocation(
                                new Point2D.Float(Float.parseFloat(edgePath.getAttributeValue("tx")),
                                        Float.parseFloat(edgePath.getAttributeValue("ty"))));
                    }
                }

                // Add edge path points if there is any.
                Iterator<Element> iter4 = element.getDescendants(new ElementFilter("Point"));
                Element edgePathPoint = null;
                while (iter4.hasNext()) {
                    Object o4 = iter4.next();
                    if (o4 instanceof Element) {
                        edgePathPoint = (Element) o4;
                        logger.debug("  PathPoint x: '" + edgePathPoint.getAttributeValue("x"));
                        logger.debug("  PathPoint y: '" + edgePathPoint.getAttributeValue("y"));
                        e.setPathPoints(
                                new Point2D.Float(Float.parseFloat(edgePathPoint.getAttributeValue("x")),
                                        Float.parseFloat(edgePathPoint.getAttributeValue("y"))));
                    }
                }

                logger.debug("  source: " + element.getAttributeValue("source"));
                logger.debug("  target: " + element.getAttributeValue("target"));

                Vertex source = null;
                Vertex dest = null;

                for (Object vertice : vertices) {
                    Vertex vertex = (Vertex) vertice;

                    // Find source vertex
                    if (vertex.getIdKey().equals(element.getAttributeValue("source"))
                            && vertex.getFileKey().equals(fileName)) {
                        source = vertex;
                    }
                    if (vertex.getIdKey().equals(element.getAttributeValue("target"))
                            && vertex.getFileKey().equals(fileName)) {
                        dest = vertex;
                    }
                }
                if (source == null) {
                    String msg = "Could not find starting node for edge. Name: '"
                            + element.getAttributeValue("source") + "' In file '" + fileName + "'";
                    logger.error(msg);
                    throw new RuntimeException(msg);
                }
                if (dest == null) {
                    String msg = "Could not find end node for edge. Name: '"
                            + element.getAttributeValue("target") + "' In file '" + fileName + "'";
                    logger.error(msg);
                    throw new RuntimeException(msg);
                }

                e.setIdKey(element.getAttributeValue("id"));
                e.setFileKey(fileName);
                e.setIndexKey(getNewVertexAndEdgeIndex());

                // Parse description
                Iterator<Element> iter_data = element.getDescendants(new ElementFilter("data"));
                while (iter_data.hasNext()) {
                    Object o3 = iter_data.next();
                    if (o instanceof Element) {
                        Element data = (Element) o3;
                        if (!data.getAttributeValue("key").equals("d9"))
                            continue;
                        e.setDesctiptionKey(data.getText());
                        break;
                    }
                }

                if (!graph.addEdge(e, source, dest)) {
                    String msg = "Failed adding edge: " + e + ", to graph: " + graph;
                    logger.error(msg);
                    throw new RuntimeException(msg);
                }

                if (edgeLabel != null) {
                    // The label of an edge has the following format:
                    // Label Parameter [Guard] / Action1;Action2;ActionN;
                    // Keyword
                    // Where the Label, Parameter. Guard, Actions and Keyword are
                    // optional.

                    String str = edgeLabel.getText();

                    e.setFullLabelKey(str);
                    String[] guardAndAction = Edge.getGuardAndActions(str);
                    String[] labelAndParameter = Edge.getLabelAndParameter(str);
                    e.setGuardKey(guardAndAction[0]);
                    e.setActionsKey(guardAndAction[1]);
                    e.setLabelKey(labelAndParameter[0]);
                    e.setParameterKey(labelAndParameter[1]);
                    e.setWeightKey(Edge.getWeight(str));
                    e.setBlockedKey(AbstractElement.isBlocked(str));

                    Integer index = AbstractElement.getIndex(str);
                    if (index != 0) {
                        e.setIndexKey(index);
                    }

                    e.setReqTagKey(AbstractElement.getReqTags(str));
                }
                e.setVisitedKey(0);
                logger.debug("  Added edge: '" + e.getLabelKey() + "', with id: " + e.getIndexKey());

                // Extract any manual test instructions
                Iterator<Element> iterData = element.getDescendants(new ElementFilter("data"));
                while (iterData.hasNext() && e != null) {
                    Object o2 = iterData.next();
                    if (o2 instanceof Element) {
                        Element data = (Element) o2;
                        if (!data.getContent().isEmpty() && data.getContent(0) != null) {
                            String text = data.getContent(0).getValue().trim();
                            if (!text.isEmpty()) {
                                logger.debug("  Data: '" + text + "'");
                                e.setManualInstructions(text);
                            }
                        }
                    }
                }
            }
        }
    } catch (RuntimeException e) {
        throw new RuntimeException("Could not parse file: '" + fileName + "'. " + e.getMessage());
    } catch (IOException e) {
        throw new RuntimeException("Could not parse file: '" + fileName + "'. " + e.getMessage());
    } catch (JDOMException e) {
        throw new RuntimeException("Could not parse file: '" + fileName + "'. " + e.getMessage());
    }

    logger.debug("Finished parsing graph: " + graph);
    removeBlockedEntities(graph);
    logger.debug("Graph after removing BLOCKED entities: " + graph);

    return graph;
}