Example usage for org.jdom2 Element getAttributes

List of usage examples for org.jdom2 Element getAttributes

Introduction

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

Prototype

public List<Attribute> getAttributes() 

Source Link

Document

This returns the complete set of attributes for this element, as a List of Attribute objects in no particular order, or an empty list if there are none.

Usage

From source file:de.andrena.tools.macker.rule.RuleSetBuilder.java

License:Open Source License

private Collection<Attribute> getAttributes(final Element patternElem) {
    return patternElem.getAttributes();
}

From source file:delfos.io.xml.recommendations.RecommendationsToXML.java

License:Open Source License

/**
 * Convierte el elemento XML indicado en un objeto que representa las recomendaciones al usuario.
 *
 * @param element Elemento XML a convertir.
 * @return Recomendaciones.//from w  w  w .j av a 2  s.c o m
 *
 * @throws IllegalArgumentException Si el elemento no contiene la informacin necesaria para recuperar un objeto
 * {@link Recommendations}.
 *
 * @see RecommendationsToXML#getRecommendationsElement(delfos.RS.Recommendation.Recommendations)
 *
 */
public static Recommendations getRecommendations(Element element) {

    if (!element.getName().equals(RECOMMENDATIONS_ELEMENT_NAME)) {
        throw new IllegalArgumentException("Element name doesn't match this reader: found '" + element.getName()
                + "' expected '" + RECOMMENDATIONS_ELEMENT_NAME + "'");
    }

    String idTarget = element.getAttributeValue(ID_TARGET_ATTRIBUTE_NAME);

    Map<DetailField, Object> details = new TreeMap<>();
    for (Attribute attribute : element.getAttributes()) {

        if (ID_TARGET_ATTRIBUTE_NAME.equals(attribute.getName())) {
            continue;
        }

        DetailField detailField = DetailField.valueOfNoCase(attribute.getName());

        String detailFieldValueString = attribute.getValue();
        Object detailFieldValue = detailField.parseValue(detailFieldValueString);

        details.put(detailField, detailFieldValue);

    }

    RecommendationComputationDetails recommendationComputationDetails = new RecommendationComputationDetails(
            details);
    List<Recommendation> recommendations = new LinkedList<>();
    for (Object r : element.getChildren(RECOMMENDATION_ELEMENT_NAME)) {
        Element recommendationElement = (Element) r;

        if (!recommendationElement.getName().equals(RECOMMENDATION_ELEMENT_NAME)) {
            throw new IllegalArgumentException("Element name doesn't match this reader: found '"
                    + recommendationElement.getName() + "' expected '" + RECOMMENDATION_ELEMENT_NAME + "'");
        }
        int idItem = Integer.parseInt(recommendationElement.getAttributeValue(ID_ITEM_ATTRIBUTE_NAME));
        double preference = Double
                .parseDouble(recommendationElement.getAttributeValue(PREFERENCE_ATTRIBUTE_NAME));
        recommendations.add(new Recommendation(idItem, preference));
    }

    return RecommendationsFactory.createRecommendations(idTarget, recommendations,
            recommendationComputationDetails);
}

From source file:delfos.main.managers.experiment.join.xml.AggregateResultsXML.java

License:Open Source License

public Map<String, Object> extractCaseParametersMapFromElement(Element element) {
    Map<String, Object> valuesByColumnName = new TreeMap<>();

    String elementName = element.getName();
    if (element.getAttribute("name") != null) {
        elementName = elementName + "." + element.getAttributeValue("name");
    }//  w  ww.  ja  v a 2s .  c o m

    if (elementName.equals(CASE_ROOT_ELEMENT_NAME)) {
        for (Attribute attribute : element.getAttributes()) {
            String name = CaseStudyXML.CASE_ROOT_ELEMENT_NAME + "." + attribute.getName();
            String value = attribute.getValue();
            valuesByColumnName.put(name, value);
        }
    }

    if (elementName.equals(RelevanceCriteriaXML.ELEMENT_NAME)) {

        double threshold = RelevanceCriteriaXML.getRelevanceCriteria(element).getThreshold().doubleValue();
        valuesByColumnName.put(RelevanceCriteriaXML.ELEMENT_NAME, threshold);

    } else if (element.getChildren().isEmpty()) {
        String columnName;
        String value;

        if (!element.hasAttributes()) {
            throw new IllegalArgumentException("arg");
        }

        if (element.getAttribute("name") != null) {
            columnName = elementName;
            value = element.getAttributeValue("name");
        } else if (element.getAttribute("parameterName") != null) {
            columnName = element.getAttributeValue("parameterName");
            value = element.getAttributeValue("parameterValue");
        } else {
            throw new IllegalStateException("arg");
        }

        valuesByColumnName.put(columnName, value);

    } else {
        for (Element child : element.getChildren()) {

            if (child.getName().equals(AGGREGATE_VALUES_ELEMENT_NAME)) {
                continue;
            }

            if (child.getName().equals(EXECUTIONS_RESULTS_ELEMENT_NAME)) {
                throw new IllegalArgumentException("The file is a full results file!");
            }

            Map<String, Object> extractCaseParametersMapFromElement = extractCaseParametersMapFromElement(
                    child);

            for (Map.Entry<String, Object> entry : extractCaseParametersMapFromElement.entrySet()) {
                String columnNameWithPrefix = elementName + "." + entry.getKey();

                Object value = entry.getValue();

                valuesByColumnName.put(columnNameWithPrefix, value);
            }

        }
    }
    return valuesByColumnName;

}

From source file:devicemodel.conversions.XmlConversions.java

public static Element nodeToXml(DeviceNode node) {
    Element elem = new Element(node.getName());
    if (node.getAttributes().size() > 0) {
        for (String key : node.getAttributes().keySet()) {
            elem.getAttributes().add(new Attribute(key, node.getAttribute(key)));
        }/*from w w  w. j a v  a2s.  c o m*/
    }
    if (node.getValue() != null) {
        elem.setText(node.getValue());
    }

    if (node.getChildren().size() > 0) {
        List<String> children = node.getChildrenNamesSorted();
        for (String child : children) {
            elem.getChildren().add(nodeToXml(node.getChild(child)));
        }
    }

    return elem;
}

From source file:devicemodel.conversions.XmlConversions.java

public static DeviceNode xmlToNode(Element e, String id) {

    String[] ids = new String[] { "" };

    if (e.getAttribute("ids") != null) {
        ids = e.getAttributeValue("ids").split(",");
        e.removeAttribute("ids");
    }/*from   ww  w. ja v a 2  s.  c om*/

    DeviceNode node = new DeviceNode(e.getName() + id);

    node.setValue(e.getTextTrim());

    for (Attribute a : e.getAttributes()) {
        node.getAttributes().put(a.getName(), a.getValue());
    }

    for (String cid : ids) {
        for (Element c : e.getChildren()) {
            try {
                node.addChild(xmlToNode(c, cid));
            } catch (Exception ex) {
            }
        }
    }

    return node;
}

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./* w  w  w  .  j a v a  2s.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:helpers.XMLParser.java

public static ParsedSingleXML parseSingleDoc(String xml) {
    ParsedSingleXML doc = null;/*  w w  w.j  av a  2  s  .  c o  m*/
    try {

        SAXBuilder saxBuilder = new SAXBuilder();
        Document document = saxBuilder.build(new StringReader(xml));

        Element root = document.getRootElement();
        List<Attribute> rootAttributes = root.getAttributes();
        doc = new ParsedSingleXML(root.getName());
        for (Attribute attr : rootAttributes) {
            doc.addAttr(attr.getName(), attr.getValue());
        }

        XMLRow row;

        List<Element> rootChildren = root.getChildren();
        List<Element> tempChildren;
        List<Attribute> tempAttributes;

        for (Element child : rootChildren) {

            tempChildren = child.getChildren();
            row = new XMLRow(child.getName());
            tempAttributes = child.getAttributes();
            for (Attribute attr : tempAttributes) {
                row.addRootAttr(attr.getName(), attr.getValue());
            }

            for (Element tChild : tempChildren) {
                row.addRowElement(tChild.getName(), tChild.getValue());
            }

            doc.addRow(row);
        }

    } catch (JDOMException ex) {
        Logger.getLogger(XMLParser.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(XMLParser.class.getName()).log(Level.SEVERE, null, ex);
    }

    return doc;

}

From source file:io.smartspaces.workbench.project.jdom.JdomProjectGroupTemplateSpecificationReader.java

License:Apache License

/**
 * Get any attributes attached to the project.
 *
 * @param spec//from  ww w. j a v a2s  .  co m
 *          the specification whose data is being read
 * @param rootElement
 *          root element of the XML DOM containing the project data
 */
private void getSpecificationAttributes(GroupProjectTemplateSpecification spec, Element rootElement) {
    @SuppressWarnings("unchecked")
    List<Attribute> attributes = rootElement.getAttributes();
    for (Attribute attribute : attributes) {
        spec.addAttribute(attribute.getName(), attribute.getValue());
    }
}

From source file:io.smartspaces.workbench.project.jdom.JdomProjectReader.java

License:Apache License

/**
 * Get any attributes attached to the project.
 *
 * @param project//from www  .j av a2s  .  c  o m
 *          the project description whose data is being read
 * @param rootElement
 *          root element of the XML DOM containing the project data
 */
private void getProjectAttributes(Project project, Element rootElement) {
    @SuppressWarnings("unchecked")
    List<Attribute> attributes = rootElement.getAttributes();
    for (Attribute attribute : attributes) {
        project.addAttribute(attribute.getName(), attribute.getValue());
    }
}

From source file:io.wcm.handler.richtext.impl.RichTextRewriteContentHandlerImpl.java

License:Apache License

/**
 * Support data structures where link metadata is stored in mutliple HTML5 data-* attributes.
 * @param pResourceProps Valuemap to write link metadata to
 * @param element Link element//from   w  w w  .  j  a v a2  s  .c  o  m
 * @return true if any metadata attribute was found
 */
private boolean getAnchorMetadataFromData(ValueMap pResourceProps, Element element) {
    boolean foundAny = false;

    List<Attribute> attributes = element.getAttributes();
    for (Attribute attribute : attributes) {
        if (DataPropertyUtil.isHtml5DataName(attribute.getName())) {
            String value = attribute.getValue();
            if (StringUtils.isNotEmpty(value)) {
                String property = DataPropertyUtil.toHeadlessCamelCaseName(attribute.getName());
                if (StringUtils.startsWith(value, "[") && StringUtils.endsWith(value, "]")) {
                    try {
                        JSONArray jsonArray = new JSONArray(value);
                        String[] values = new String[jsonArray.length()];
                        for (int i = 0; i < jsonArray.length(); i++) {
                            values[i] = jsonArray.optString(i);
                        }
                        pResourceProps.put(property, values);
                    } catch (JSONException ex) {
                        // ignore
                    }
                } else {
                    // decode if required
                    value = decodeIfEncoded(value);
                    pResourceProps.put(property, value);
                }
                foundAny = true;
            }
        }
    }

    return foundAny;
}