Example usage for org.jdom2 Element getDescendants

List of usage examples for org.jdom2 Element getDescendants

Introduction

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

Prototype

@Override
public <F extends Content> IteratorIterable<F> getDescendants(final Filter<F> filter) 

Source Link

Document

Returns an iterator that walks over all descendants in document order applying the Filter to return only content that match the filter rule.

Usage

From source file:es.upm.dit.xsdinferencer.extraction.extractorImpl.TypesExtractorImpl.java

License:Apache License

/**
 * Recursive method that traverses an element to extract all the possible information from it.
 * It is recursive because it calls itself for each child of the element (obviously, infinite recursion 
 * is not possible as there are not, or there should not be, parent-child loops).  
 * The index of the current document is necessary in order to add well some information to 
 * the statistics./*from   ww  w  .  j a va  2  s .c  om*/
 * @param documentIndex index of current document
 * @param element the element to traverse (as a JDOM2 {@link Element})
 * @param enclosingComplexType the complex type which will contain the current element
 */
private void traverseElement(int documentIndex, Element element, String enclosingComplexType) {
    //Elements in the XSI namespace should be ignored
    if (element.getNamespaceURI().equalsIgnoreCase(XSI_NAMESPACE_URI))
        return;
    List<String> realPathUnfiltered = getRealPathOfElementUnfiltered(element, configuration, false,
            solvedNamespaceToPrefixMapping);
    String realPathFiltered = filterAndJoinRealPath(realPathUnfiltered);//Path for the statistics
    List<String> typePathUnfiltered = getRealPathOfElementUnfiltered(element, configuration, false,
            solvedNamespaceToPrefixMapping);
    List<String> suitablePath = getSuitablePath(typePathUnfiltered);//Path for type name inferencing
    //First, we will register the information of width and depth
    //The root is in a level whose width is 1, if we did not do the following, that width would be never registered
    if (element.isRootElement()) {
        statistics.registerWidth(documentIndex, 1);
    }
    statistics.registerDepth(documentIndex, realPathUnfiltered.size());
    int width = element.getChildren().size();
    if (width > 0) {
        statistics.registerWidth(documentIndex, width);
    }
    TypeNameInferencer typeNameInferencer = configuration.getTypeNameInferencer();
    String complexTypeName = typeNameInferencer.inferTypeName(suitablePath, configuration);//Complex type of this element
    //      //Little workaround that ensures that the same complex type is used 
    //      //when the elements on its path are the same (same name and namespace) but some of them 
    //      //use different namespace prefixes
    //      List<String> realPathUnfilteredKey=getRealPathOfElementUnfiltered(element, configuration, false, solvedNamespaceToPrefixMapping);
    //      List<String> suitablePathKey=getSuitablePath(realPathUnfilteredKey);//Path for type name inferencing
    //      String complexTypeNameKey = typeNameInferencer.inferTypeName(suitablePathKey, configuration);//Complex type of this element
    String complexTypeNameKey = complexTypeName;
    //The complex type object of this element.
    ComplexType complexType = complexTypes.get(complexTypeNameKey);
    if (complexType == null) {
        complexType = new ComplexType(complexTypeName, null, null, null);
        complexTypes.put(complexTypeNameKey, complexType); //New complex type
    }
    complexType.addSourceNodeNamespaceAndName(element.getNamespaceURI(), element.getName());
    //Comment processing
    for (Comment comment : element.getDescendants(Filters.comment())) {
        if (comment.getParentElement().equals(element))
            complexType.getComments().add(comment.getText());
    }

    //Key to find the corresponding SchemaElement
    //This key is: if the SchemaElement has an enclosing complex type (i.e., it is not a valid root), its name will be:
    //enclosingComplexType+typeNamesSeparator+elementName
    //If the element is a suitable root, the key is the name of the element.
    String schemaElementKey = (!enclosingComplexType.equals(""))
            ? enclosingComplexType + configuration.getTypeNamesAncestorsSeparator() + element.getName()
            : element.getName();
    if (configuration.getTypeNameInferencer() instanceof NameTypeNameInferencer) {
        schemaElementKey = element.getName(); //If we use a name-based type inferencer, the key is the name and we avoid problems.
    }
    SchemaElement schemaElement = elements.get(element.getNamespaceURI(), schemaElementKey);
    if (schemaElement == null) {
        schemaElement = new SchemaElement(element.getName(), element.getNamespaceURI(), complexType);//Complex type already not known.
        elements.put(element.getNamespaceURI(), schemaElementKey, schemaElement);
    }
    boolean wasAlreadyValidRoot = schemaElement.isValidRoot();
    schemaElement.setValidRoot(wasAlreadyValidRoot || element.isRootElement());

    ComplexTypeStatisticsEntry complexTypeStatisticsEntry = statistics.getComplexTypeInfo().get(complexType);
    if (complexTypeStatisticsEntry == null) {
        complexTypeStatisticsEntry = new ComplexTypeStatisticsEntry(xmlDocuments.size());
        statistics.getComplexTypeInfo().put(complexType, complexTypeStatisticsEntry);
    }

    AttributeListInferencer attributeListInferencer = attributeListInferencers.get(complexTypeName);

    if (attributeListInferencer == null) {
        attributeListInferencer = inferencersFactory.getAttributeListInferencerInstance(complexTypeName,
                configuration, solvedNamespaceToPrefixMapping, statistics);
        attributeListInferencers.put(complexTypeName, attributeListInferencer);
    }
    attributeListInferencer.learnAttributeList(element.getAttributes(), documentIndex);

    SimpleTypeInferencer simpleTypeInferencer = simpleTypeInferencersOfComplexTypes.get(complexTypeName);
    if (simpleTypeInferencer == null) {
        simpleTypeInferencer = inferencersFactory.getSimpleTypeInferencerInstance(complexTypeName,
                configuration);
        simpleTypeInferencersOfComplexTypes.put(complexTypeName, simpleTypeInferencer);
    }
    simpleTypeInferencer.learnValue(element.getText(), element.getNamespaceURI(), element.getName());

    //      SchemaElement previousChildSchemaElement=null; //We need to store the previous child in order to add the edge between it and the current child.
    List<SchemaElement> schemaElementChildren = new ArrayList<>(element.getChildren().size());
    for (int i = 0; i < element.getChildren().size(); i++) {
        Element child = element.getChildren().get(i);
        traverseElement(documentIndex, child, complexTypeName);
        String childSchemaElementKey = complexTypeName + configuration.getTypeNamesAncestorsSeparator()
                + child.getName();
        if (configuration.getTypeNameInferencer() instanceof NameTypeNameInferencer) {
            childSchemaElementKey = child.getName(); // If we use the name-based type name inferencer, the name is the key
        }
        SchemaElement childSchemaElement = elements.get(child.getNamespaceURI(), childSchemaElementKey);//The SchemaElement object does exist because the method traverseElement is called before this.
        //         if(i==0){
        //            automaton.addEdge(automaton.getInitialState(), childSchemaElement);
        //         }
        //         else {
        //            automaton.addEdge(previousChildSchemaElement, childSchemaElement);
        //            if(i==(element.getChildren().size()-1)){
        //               automaton.addEdge(childSchemaElement, automaton.getFinalState());
        //            }
        //         }
        complexTypeStatisticsEntry.registerElementCount(childSchemaElement, documentIndex);
        schemaElementChildren.add(childSchemaElement);
        //         previousChildSchemaElement=childSchemaElement;
    }

    ExtendedAutomaton automaton = automatons.get(complexTypeName);
    if (automaton == null) {
        automaton = new ExtendedAutomaton();
        SchemaElement initialState = new SchemaElement("initial", DEFAULT_PSEUDOELEMENTS_NAMESPACE, null);
        automaton.setInitialState(initialState);
        SchemaElement finalState = new SchemaElement("final", DEFAULT_PSEUDOELEMENTS_NAMESPACE, null);
        automaton.setFinalState(finalState);
        automatons.put(complexTypeName, automaton);
    }

    List<SchemaElement> schemaElementChildrenWithInitialAndFinal = new ArrayList<>(schemaElementChildren);
    schemaElementChildrenWithInitialAndFinal.add(0, automaton.getInitialState());
    schemaElementChildrenWithInitialAndFinal.add(automaton.getFinalState());
    automaton.learn(schemaElementChildrenWithInitialAndFinal);

    complexTypeStatisticsEntry.registerSubpatternsFromList(schemaElementChildren);
    complexTypeStatisticsEntry.registerValueOfNodeCount(element.getText(), schemaElement, documentIndex);

    statistics.registerElementAtPathCount(realPathFiltered, documentIndex);
    statistics.registerValueAtPathCount(realPathFiltered, element.getText(), documentIndex);
    if (enclosingComplexType.equals("")) {
        statistics.registerRootElementOccurrence(schemaElement);
    }
}

From source file:esiptestbed.mudrod.ontology.pre.AggregateTriples.java

License:Apache License

/**
 * Method of identifying a specific child given a element name
 * @param str element name// w  w w .  j  av  a  2  s.  c  om
 * @param ele parent element
 * @return the element of child
 */
public Element findChild(String str, Element ele) {
    Iterator<?> processDescendants = ele.getDescendants(new ElementFilter());
    String name = "";
    Element result = null;

    while (processDescendants.hasNext()) {
        Element e = (Element) processDescendants.next();
        name = e.getName();
        if (name.equals(str)) {
            result = e;
            return result;
        }
    }
    return result;

}

From source file:jgoose.IEC61850_GOOSE_ICD_file.java

License:Open Source License

public IEC61850_GOOSE_ICD_file(String icd_filename, String ied_name)
        throws JDOMException, IOException, IEC61850_GOOSE_Exception {
    boolean found_ConnectedAP = false;
    short found_Addressing_data = 0;
    boolean found_IED = false;

    xml_builder = new SAXBuilder();
    xml_file = new File(icd_filename);
    xml_document = (Document) xml_builder.build(xml_file);

    // Checks that the XML file is indeed an SCL file
    if (xml_document.getRootElement().getName() != "SCL")
        throw new IEC61850_GOOSE_Exception("XML input file is not of SCL type");

    root_namespace = xml_document.getRootElement().getNamespace();

    // Retrieve Node Communication
    Element comm_element = xml_document.getRootElement().getChild("Communication", root_namespace);

    // Retrieves all elements named "ConnectedAP" within Communication node
    Filter<Element> elementFilter = new ElementFilter("ConnectedAP");

    // Search for a ConnectedAP with a matching iedName
    for (Iterator<Element> ConnectedAP_IT = comm_element.getDescendants(elementFilter); ConnectedAP_IT
            .hasNext();) {/*w w  w.  jav  a  2 s.  c o  m*/
        Element current_element = ConnectedAP_IT.next();

        if (current_element.getAttributeValue("iedName").equals(ied_name)) {
            // We found the ConnectedAP node with the correct iedName
            found_ConnectedAP = true;

            iedName = current_element.getAttributeValue("iedName");

            ConnectedAP_in_Comm_section = current_element;
            apName = ConnectedAP_in_Comm_section.getAttributeValue("apName");

            // walks to the "Address" children 
            Element ConnectedAP_in_Comm_section_Address = ConnectedAP_in_Comm_section.getChild("Address",
                    root_namespace);
            List<Element> p_nodes_LIST = ConnectedAP_in_Comm_section_Address.getChildren("P", root_namespace);

            // Walks all P nodes to retrieve addressing data
            for (int position = 0; position < p_nodes_LIST.size(); position++) {
                if (p_nodes_LIST.get(position).getAttributeValue("type").contentEquals("IP")) {
                    ipAddress = p_nodes_LIST.get(position).getValue();
                    found_Addressing_data |= 1;
                } else if (p_nodes_LIST.get(position).getAttributeValue("type").contentEquals("IP-SUBNET")) {
                    ipSubnet = p_nodes_LIST.get(position).getValue();
                    found_Addressing_data |= 2;
                } else if (p_nodes_LIST.get(position).getAttributeValue("type").contentEquals("IP-GATEWAY")) {
                    ipGateway = p_nodes_LIST.get(position).getValue();
                    found_Addressing_data |= 4;
                } else if (p_nodes_LIST.get(position).getAttributeValue("type").contentEquals("MAC-Address")) {
                    macAddress = p_nodes_LIST.get(position).getValue();
                    found_Addressing_data |= 8;
                }
            }

            // If all 4 addressing data fields were not found, we rise an exception.
            if (found_Addressing_data != 15)
                throw new IEC61850_GOOSE_Exception("Missing addressing data in SCL file: " + icd_filename
                        + " iedName: " + iedName + " apName: " + apName);
        }
    }

    if (found_ConnectedAP == false)
        throw new IEC61850_GOOSE_Exception("ConnectedAP section with corresponding IED name: " + iedName
                + " not found in SCL file: " + icd_filename);

    // Now we have to find the IED and the Access Point in the <IED> section
    // Retrieve IED Children
    List<Element> ied_nodes_LIST = xml_document.getRootElement().getChildren("IED", root_namespace);
    for (int position = 0; position < ied_nodes_LIST.size(); position++) {
        if (ied_nodes_LIST.get(position).getAttributeValue("name").equals(ied_name)
                && ied_nodes_LIST.get(position).getChild("AccessPoint", root_namespace)
                        .getAttributeValue("name").equals(apName)) {
            IED_section = ied_nodes_LIST.get(position);
            found_IED = true;
        }
    }

    if (found_IED == false)
        throw new IEC61850_GOOSE_Exception("IED section with corresponding AccessPoint name: " + apName
                + " not found in SCL file: " + icd_filename);
}

From source file:jgoose.IEC61850_GOOSE_ICD_file.java

License:Open Source License

void decodeDataSetBlock(String dataSetName, String ldInstance) throws IEC61850_GOOSE_Exception {
    /*/* ww  w  . j av a 2  s  . c  om*/
     * In this part, we decode the the DataSet block in order to find each signal in it
     */

    boolean found_DataSet = false;
    GOOSESignalsList = new ArrayList<GOOSESignalAttributes>();

    // Retrieves all elements named "DataSet" within IED
    Filter<Element> elementFilter = new ElementFilter("DataSet");

    // Search for a DataSet with a matching name
    for (Iterator<Element> DataSet_IT = IED_section.getDescendants(elementFilter); DataSet_IT.hasNext();) {
        Element current_element = DataSet_IT.next();

        if (current_element.getAttributeValue("name").equals(dataSetName)) {
            DataSet_node = current_element;
            found_DataSet = true;
        }
    }

    if (found_DataSet == false)
        throw new IEC61850_GOOSE_Exception("<DataSet> named" + dataSetName + "not found");

    /*
     * Now that we found the DataSet, we are looking for the signals in it
     */

    FCDA_nodes_LIST = DataSet_node.getChildren("FCDA", root_namespace);

    // Walks all FCDA nodes to retrieve the signals
    for (int position = 0; position < FCDA_nodes_LIST.size(); position++) {

        // Search for a signals, FCDA nodes, with matching ldInst
        if (FCDA_nodes_LIST.get(position).getAttributeValue("ldInst").contentEquals(ldInstance)) {
            // We found a signal with the right ldInst
            GOOSESignalAttributes new_GOOSESignal = new GOOSESignalAttributes();

            // We save all signal information
            new_GOOSESignal.lnClass = FCDA_nodes_LIST.get(position).getAttributeValue("lnClass");
            new_GOOSESignal.lnInst = Integer
                    .parseInt(FCDA_nodes_LIST.get(position).getAttributeValue("lnInst"));
            new_GOOSESignal.doName = FCDA_nodes_LIST.get(position).getAttributeValue("doName");
            new_GOOSESignal.daName = FCDA_nodes_LIST.get(position).getAttributeValue("daName");
            new_GOOSESignal.fc = FCDA_nodes_LIST.get(position).getAttributeValue("fc");

            // We insert the signal in the signal list
            GOOSESignalsList.add(new_GOOSESignal);
        }
    }

    if (GOOSESignalsList.size() == 0) {
        throw new IEC61850_GOOSE_Exception(
                "Could not find any signal with ldInst name: " + ldInstance + " in DataSet: " + dataSetName);
    }

    /*
     * Now we have to extract all signal attributes
     */

    for (int position = 0; position < GOOSESignalsList.size(); position++) {

        GOOSESignalAttributes current_GOOSESignal = GOOSESignalsList.get(position);

        boolean found_NodeType = false;

        /*
         * Now we have to extract the lnType using the lnClass and the inst number
         */

        boolean found_LDevice = false;

        // Retrieves all elements named "LDevice" within the SCL file
        elementFilter = new ElementFilter("LDevice");

        // Search for a LDevice block with name matching ldInstance in the IED section
        for (Iterator<Element> LDevice_IT = IED_section.getDescendants(elementFilter); LDevice_IT.hasNext();) {
            Element current_element = LDevice_IT.next();

            // We found one matching element
            if (current_element.getAttributeValue("inst").equals(ldInstance)) {
                // Something is wrong, its the second time we find a LDevice block with a matching name
                if (found_LDevice == true)
                    throw new IEC61850_GOOSE_Exception(
                            "There is more than one <LDevice> block named:" + ldInstance + " in the SCL file");
                else
                    found_LDevice = true;

                boolean found_IECData = false;

                // Retrieves all elements named "LN" within IED node
                elementFilter = new ElementFilter("LN");

                // Search for a LN block with a matching lnClass and inst prefix
                for (Iterator<Element> LN_IT = current_element.getDescendants(elementFilter); LN_IT
                        .hasNext();) {
                    Element innerloop_element = LN_IT.next();

                    if (innerloop_element.getAttributeValue("lnClass").equals(current_GOOSESignal.lnClass)
                            && innerloop_element.getAttributeValue("inst")
                                    .equals(String.valueOf(current_GOOSESignal.lnInst))) {
                        /*
                         *  We found the right LN node. We save the lnType
                         */
                        current_GOOSESignal.lnType_id = innerloop_element.getAttributeValue("lnType");

                        Element DOI_element = innerloop_element.getChild("DOI", root_namespace);

                        if (DOI_element.getAttributeValue("name").equals(current_GOOSESignal.doName)) {
                            Element DAI_element = DOI_element.getChild("DAI", root_namespace);

                            if (DAI_element.getAttributeValue("name").equals(current_GOOSESignal.daName)) {
                                Element Private_element = DAI_element.getChild("Private", root_namespace);

                                /* 
                                 * Save IEC 60870-5-104 data for every signal
                                 */

                                if (Private_element.getAttributeValue("type")
                                        .contentEquals("IEC_60870_5_104")) {
                                    Namespace iec_60870_5_104_namespace = Namespace.getNamespace(
                                            "IEC_60870_5_104", "http://www.iec.ch/61850-80-1/2007/SCL");
                                    Element IEC_element = Private_element.getChild("GlobalAddress104",
                                            iec_60870_5_104_namespace);

                                    current_GOOSESignal.casdu = Integer
                                            .parseInt(IEC_element.getAttributeValue("casdu"));
                                    current_GOOSESignal.ioa = Integer
                                            .parseInt(IEC_element.getAttributeValue("ioa"));
                                    current_GOOSESignal.ti = Integer
                                            .parseInt(IEC_element.getAttributeValue("ti"));

                                    found_IECData = true;
                                }
                            }
                        }

                    }

                }

                if (found_IECData == false)
                    throw new IEC61850_GOOSE_Exception(
                            "<LN> block with corresponding lnClass, inst, lnType, DOI name"
                                    + "and  DAI name not found in <IED> for signal "
                                    + String.valueOf(position + 1));
            }
        }

        if (found_LDevice == false)
            throw new IEC61850_GOOSE_Exception(
                    "There is no <LDevice> block named:" + ldInstance + " in the SCL file");

        // Retrieve Node DataTypeTemplates
        Element dataTypeTemplate_element = xml_document.getRootElement().getChild("DataTypeTemplates",
                root_namespace);

        // Retrieves all elements named "LNodeType" within DataTypeTemplates node
        elementFilter = new ElementFilter("LNodeType");

        // Search for a LNodeType block with a matching lnClass and id
        for (Iterator<Element> LNodeType_IT = dataTypeTemplate_element
                .getDescendants(elementFilter); LNodeType_IT.hasNext();) {
            Element current_element = LNodeType_IT.next();

            if (current_element.getAttributeValue("lnClass").equals(current_GOOSESignal.lnClass)
                    && current_element.getAttributeValue("id")
                            .equals(String.valueOf(current_GOOSESignal.lnType_id))) {
                // Walks all DO nodes
                List<Element> do_nodes_LIST = current_element.getChildren("DO", root_namespace);

                // Walks all DO nodes to retrieve addressing data
                for (int do_position = 0; do_position < do_nodes_LIST.size(); do_position++) {
                    // Looks for a DO node with the correct name
                    if (do_nodes_LIST.get(do_position).getAttributeValue("name")
                            .equals(current_GOOSESignal.doName)) {
                        current_GOOSESignal.do_type = do_nodes_LIST.get(do_position).getAttributeValue("type");
                        found_NodeType = true;
                    }
                }
            }
        }

        if (found_NodeType == false)
            throw new IEC61850_GOOSE_Exception("<DO> node within <LNodeType> block with corresponding name, "
                    + "lnClass and id not found in <DataTypeTemplates> for signal "
                    + String.valueOf(position + 1));

        boolean found_NodebType = false;

        // Retrieves all elements named "DOType" within DataTypeTemplates node
        elementFilter = new ElementFilter("DOType");

        // Search for a DOType block with a matching id
        for (Iterator<Element> DOType_IT = dataTypeTemplate_element.getDescendants(elementFilter); DOType_IT
                .hasNext();) {
            Element current_element = DOType_IT.next();

            if (current_element.getAttributeValue("id").equals(current_GOOSESignal.do_type)) {
                current_GOOSESignal.cdc = current_element.getAttributeValue("cdc");
                current_GOOSESignal.desc = current_element.getAttributeValue("desc");

                // Walks all DA nodes
                List<Element> da_nodes_LIST = current_element.getChildren("DA", root_namespace);

                // Walks all DO nodes to retrieve addressing data
                for (int da_position = 0; da_position < da_nodes_LIST.size(); da_position++) {
                    // Looks for a DA node with the correct fc and name
                    if (da_nodes_LIST.get(da_position).getAttributeValue("fc").equals(current_GOOSESignal.fc)
                            && da_nodes_LIST.get(da_position).getAttributeValue("name")
                                    .equals(current_GOOSESignal.daName)) {
                        current_GOOSESignal.bType = da_nodes_LIST.get(da_position).getAttributeValue("bType");
                        found_NodebType = true;
                    }
                }

            }
        }

        if (found_NodebType == false)
            throw new IEC61850_GOOSE_Exception("<DA> node within <DOType> block with corresponding fc, name,"
                    + "  and id not found in <DataTypeTemplates> for signal " + String.valueOf(position + 1));
    }

    return;
}

From source file:jodtemplate.pptx.preprocessor.ShortListPreprocessor.java

License:Apache License

@Override
public Document process(final Map<String, Object> context, final Document document, final Slide slide,
        final Resources resources, final Configuration configuration) throws JODTemplateException {
    final IteratorIterable<Element> parentElements = document
            .getDescendants(Filters.element(parentElement, getNamespace()));
    final List<Element> parentElementsList = new ArrayList<>();
    while (parentElements.hasNext()) {
        parentElementsList.add(parentElements.next());
    }/*from w  w  w. jav a2  s .  com*/

    for (final Element parent : parentElementsList) {
        final IteratorIterable<Element> atElements = parent
                .getDescendants(Filters.element(PPTXDocument.T_ELEMENT, getNamespace()));
        final List<Element> atElementsList = new ArrayList<>();
        while (atElements.hasNext()) {
            atElementsList.add(atElements.next());
        }

        final ExpressionHandler expressionHandler = configuration.getExpressionHandler();
        boolean isLoop = false;
        InlineListExpression expression = null;
        for (final Element at : atElementsList) {
            final String text = at.getText();
            if (configuration.getExpressionHandler().isInlineList(text)) {
                expression = expressionHandler.createInlineListExpression(text);
                at.setText(expressionHandler.createVariable(expression.getVariable()));
                isLoop = true;
            }
        }
        if (isLoop) {
            int apIndex = parent.getParent().indexOf(parent);
            final String beginList = expressionHandler.createBeginList(expression.getWhat(),
                    expression.getAs());
            final String endList = expressionHandler.createEndList();
            parent.getParent().addContent(apIndex, new Comment(beginList));
            apIndex++;
            parent.getParent().addContent(apIndex + 1, new Comment(endList));
        }
    }
    return document;
}

From source file:net.instantcom.mm7.MM7Message.java

License:Open Source License

@Override
public void load(Element element) {
    Element body = element.getChild("Body", element.getNamespace());

    // Extract MM7 namespace from SOAP body
    Iterator<?> i = body.getDescendants(new ElementFilter());
    while (i.hasNext()) {
        Element e = (Element) i.next();
        Namespace ns = e.getNamespace();
        if (ns != null && ns.getURI().contains("MM7")) {
            this.namespace = ns;
            break;
        }//from  w w  w  . jav  a  2s .c  o  m
    }

    if (this.namespace == null) {
        throw new IllegalStateException("can't autodetect MM7 namespace: " + body.toString());
    }

    Element header = element.getChild("Header", element.getNamespace());
    setTransactionId(header.getChildTextTrim("TransactionID", namespace));
}

From source file:no.imr.stox.functions.utils.JDOMUtils.java

public static Supplier<Stream<Element>> getElementStreamByTagName(Element parent, String nodeName) {
    IteratorIterable<Element> it = parent.getDescendants(new ElementFilter(nodeName));
    return () -> StreamSupport.stream(it.spliterator(), false);
}

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. ja v  a  2 s .c o m*/
 * @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;
}

From source file:org.imsglobal.lti.LTIUtil.java

License:Open Source License

/**
* Returns a named XML child element given a parent element.
* <p>//  w  w w  .  j av a2  s . co  m
* The first element will be returned if more than one exists with the given name.
* The first child element will be returned if the name is null.
*
* @param root  parent element
* @param name  name of child element
*
* @return child element, null if not found
*/
public static Element getXmlChild(Element root, String name) {

    Element child = null;
    if (name != null) {
        ElementFilter elementFilter = new ElementFilter(name);
        Iterator<Element> iter = (Iterator<Element>) root.getDescendants(elementFilter);
        if (iter.hasNext()) {
            child = iter.next();
        }
    } else {
        List<Element> elements = (List<Element>) root.getChildren();
        if (elements.size() >= 1) {
            child = elements.get(0);
        }
    }

    return child;

}

From source file:org.mycore.frontend.editor.MCREditorDefReader.java

License:Open Source License

private void checkDuplicateIDs(Element editor) {
    Set<String> ids = new HashSet<String>();
    Iterator<Element> elements = editor.getDescendants(Filters.element());
    while (elements.hasNext()) {
        String id = elements.next().getAttributeValue("id");
        if (id == null || id.trim().length() == 0) {
            continue;
        }//from  w  w  w.  j a  va2 s  . c om
        if (ids.contains(id)) {
            String msg = "Duplicate ID '" + id + "', already used in editor definition";
            throw new MCRConfigurationException(msg);
        } else {
            ids.add(id);
        }
    }
}