Example usage for org.dom4j Element attributeIterator

List of usage examples for org.dom4j Element attributeIterator

Introduction

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

Prototype

Iterator<Attribute> attributeIterator();

Source Link

Document

DOCUMENT ME!

Usage

From source file:org.mwolff.generator.xml.XMLHelper.java

License:Open Source License

private static void extractClassAttributes(final Element element, ClassStructure classStructure) {

    for (@SuppressWarnings("unchecked")
    final Iterator<Attribute> attributeIterator = element.attributeIterator(); attributeIterator.hasNext();) {

        final Attribute attribute = attributeIterator.next();

        if ("identifier".equals(attribute.getName())) {
            classStructure.setIdentifier(attribute.getValue());
        }/*from ww w.j  av  a 2s  . c o  m*/

        if ("extends".equals(attribute.getName())) {
            classStructure.setExtendsString(attribute.getValue());
        }

        if ("implements".equals(attribute.getName())) {
            classStructure.setImplementsString(attribute.getValue());
        }

    }
}

From source file:org.mwolff.generator.xml.XMLHelper.java

License:Open Source License

private static void createInstanceVariables(ClassStructure classStructure, Element innerElement) {

    final List<InstanceVariable> variableList = new ArrayList<InstanceVariable>();
    @SuppressWarnings("unchecked")
    final List<Element> instanceVarialbleList = innerElement.elements();

    for (Element instanceVariables : instanceVarialbleList) {

        final InstanceVariable variable = new InstanceVariable();
        variable.setCardinality("none");

        for (@SuppressWarnings("unchecked")
        final Iterator<Attribute> variableIterator = instanceVariables.attributeIterator(); variableIterator
                .hasNext();) {// ww w.  ja  va  2s.  com

            final Attribute attribute = variableIterator.next();

            LOG.debug(attribute.getName());

            if ("id".equals(attribute.getName())) {
                variable.setIdentifier(attribute.getValue());
            }

            if ("type".equals(attribute.getName())) {
                variable.setType(attribute.getValue());
            }

            if ("scope".equals(attribute.getName())) {
                variable.setModifier(attribute.getValue());
            }

            if ("cardinality".equals(attribute.getName())) {
                variable.setCardinality(attribute.getValue());
            }
        }

        variableList.add(variable);
        LOG.info("Create new instance variable named " + variable.getIdentifier());
    }
    classStructure.setInstanceVariableList(variableList);
}

From source file:org.olat.ims.qti.editor.beecom.parser.OutcomesProcessingParser.java

License:Apache License

/**
 * @see org.olat.ims.qti.editor.beecom.IParser#parse(org.dom4j.Element)
 *//*from  w ww . ja v  a 2  s .c om*/
@Override
public Object parse(final Element element) {
    // assert element.getName().equalsIgnoreCase("outcomes_processing");

    final OutcomesProcessing outcomesProcessing = new OutcomesProcessing();

    final List decvars = element.selectNodes("*/decvar");
    if (decvars.size() == 0) {
        return outcomesProcessing;
    }

    final Element decvar = (Element) decvars.get(0);
    for (final Iterator iter = decvar.attributeIterator(); iter.hasNext();) {
        final Attribute attr = (Attribute) iter.next();
        outcomesProcessing.setField(attr.getName(), attr.getValue());
    }
    return outcomesProcessing;
}

From source file:org.onosproject.yang.serializers.utils.SerializersUtil.java

License:Apache License

/**
 * Converts XML atrtibutes into annotated node info.
 *
 * @param element XML element//from  ww w.  j a  va 2s.  c  om
 * @param id      resource id of an element
 * @return annotated node info
 */
public static AnnotatedNodeInfo convertXmlAttributesToAnnotations(Element element, ResourceId id) {
    Iterator iter = element.attributeIterator();
    if (!iter.hasNext()) {
        // element does not have any attributes
        return null;
    }
    AnnotatedNodeInfo.Builder builder = DefaultAnnotatedNodeInfo.builder();
    builder = builder.resourceId(id);
    while (iter.hasNext()) {
        Attribute attr = (Attribute) iter.next();
        DefaultAnnotation annotation = new DefaultAnnotation(attr.getQualifiedName(), attr.getValue());
        builder = builder.addAnnotation(annotation);
    }
    return builder.build();
}

From source file:org.onosproject.yms.app.ych.defaultcodecs.xml.XmlCodecListener.java

License:Apache License

@Override
public void enterXmlElement(Element element, XmlNodeType nodeType, Element rootElement) {
    if (element.equals(rootElement)) {
        return;//from  w w w .  ja  v a 2  s .  co m
    }

    YdtContextOperationType opType = null;

    for (Iterator iter = element.attributeIterator(); iter.hasNext();) {
        Attribute attr = (Attribute) iter.next();
        if (attr.getName().equals(OPERATION)) {
            opType = YdtContextOperationType.valueOf(attr.getValue().toUpperCase());
        }
    }

    String nameSpace = null;
    if (element.getNamespace() != null) {
        nameSpace = element.getNamespace().getURI();
    }

    /*
     * When new module has to be added, and if curnode has reference of
     * previous module, then we need to traverse back to parent(logical root
     * node).
     */
    if (ydtExtBuilder.getRootNode() == ydtExtBuilder.getCurNode().getParent() && prevNodeNamespace != null
            && !prevNodeNamespace.equals(nameSpace)) {
        ydtExtBuilder.traverseToParent();
    }

    if (nodeType == OBJECT_NODE && element.content() == null || element.content().isEmpty()) {
        nodeType = TEXT_NODE;
    }
    if (nodeType == OBJECT_NODE) {
        if (ydtExtBuilder != null) {
            if (ydtExtBuilder.getCurNode() == ydtExtBuilder.getRootNode()) {
                ydtExtBuilder.addChild(null, nameSpace, opType);
            }
            ydtExtBuilder.addChild(element.getName(), nameSpace, opType);
        }
    } else if (nodeType == TEXT_NODE) {

        if (ydtExtBuilder != null) {
            if (ydtExtBuilder.getCurNode() == ydtExtBuilder.getRootNode()) {
                ydtExtBuilder.addChild(null, nameSpace, opType);
            }
            ydtExtBuilder.addLeaf(element.getName(), nameSpace, element.getText());
        }
    }

    if (nameSpace != null) {
        prevNodeNamespace = nameSpace;
    }
}

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

License:Open Source License

public static String elementToDebugString(Element element) {
    // Open start tag
    final StringBuilder sb = new StringBuilder("<");
    sb.append(element.getQualifiedName());

    // Attributes if any
    for (Iterator i = element.attributeIterator(); i.hasNext();) {
        final Attribute currentAttribute = (Attribute) i.next();

        sb.append(' ');
        sb.append(currentAttribute.getQualifiedName());
        sb.append("=\"");
        sb.append(currentAttribute.getValue());
        sb.append('\"');
    }//  www.ja va  2  s .c  o  m

    final boolean isEmptyElement = element.elements().isEmpty() && element.getText().length() == 0;
    if (isEmptyElement) {
        // Close empty element
        sb.append("/>");
    } else {
        // Close start tag
        sb.append('>');
        sb.append("[...]");
        // Close element with end tag
        sb.append("</");
        sb.append(element.getQualifiedName());
        sb.append('>');
    }

    return sb.toString();
}

From source file:org.orbeon.oxf.xml.XMLUtils.java

License:Open Source License

/**
 * Convert dom4j attributes to SAX attributes.
 *
 * @param element   dom4j Element//from  w w w .  jav a  2  s  .  com
 * @return          SAX Attributes
 */
public static AttributesImpl getSAXAttributes(Element element) {
    final AttributesImpl result = new AttributesImpl();
    for (Iterator i = element.attributeIterator(); i.hasNext();) {
        final org.dom4j.Attribute attribute = (org.dom4j.Attribute) i.next();

        result.addAttribute(attribute.getNamespaceURI(), attribute.getName(), attribute.getQualifiedName(),
                XMLReceiverHelper.CDATA, attribute.getValue());
    }
    return result;
}

From source file:org.peerfact.impl.scenario.DefaultConfigurator.java

License:Open Source License

public void configureAttributes(Object component, Element elem, Set<String> consAttrs) {
    for (Iterator<Element> iter = elem.attributeIterator(); iter.hasNext();) {
        Attribute attr = (Attribute) iter.next();
        String name = attr.getName();
        if (!name.equals(CLASS_TAG) && !name.equals(STATIC_CREATION_METHOD_TAG)
                && !consAttrs.contains(name.toLowerCase()) && !name.equals(X_INCLUDE_ATTRIBUTE)) {
            try {
                // try to configure as boolean, int, double, String, or long
                String value = getAttributeValue(attr);
                Method method = null;

                String methodName = getMethodName(SET_METHOD_PREFIX_TAG, name);
                Class<? extends Object> classToConfigure = component.getClass();
                Method[] methods = classToConfigure.getMethods();
                for (int i = 0; i < methods.length; i++) {
                    if (methods[i].getName().equals(methodName) && methods[i].getParameterTypes().length == 1) {
                        if (method == null) {
                            method = methods[i];
                        } else {
                            log.error("Found two possible methods " + method + " and " + methods[i]);
                            throw new IllegalArgumentException("Cannot set property " + name
                                    + " as there are more than one matching methods in " + classToConfigure);
                        }// www  .j  a v  a2s.c  o  m
                    }
                }
                if (method == null) {
                    throw new IllegalArgumentException("Cannot set property " + name
                            + " as there are no matching methods in class " + classToConfigure);
                }
                Class<?> typeClass = method.getParameterTypes()[0];
                Object param = convertValue(value, typeClass);
                method.invoke(component, param);
                // TODO legal bool or int parameter could be string!
                // catch (NoSuchMethodException e) { invoke with string ...
            } catch (Exception e) {
                throw new ConfigurationException("Failed to set the property " + name + " in " + component, e);
            }
        }
    }

}

From source file:org.pentaho.supportutility.config.retriever.JackRabbitConfigRetriever.java

License:Open Source License

/**
 * removes password node//from ww  w . ja va 2  s .c  o m
 * 
 * @param element
 * @return boolean
 */
public static boolean removeNode(Element element) {

    for (int j = 0; j < element.nodeCount(); j++) {

        Node param = element.node(j);
        Element par = (Element) param;
        for (Iterator<?> n = par.attributeIterator(); n.hasNext();) {

            Attribute attribute = (Attribute) n.next();
            if (attribute.getName().equalsIgnoreCase("name")) {
                if (attribute.getStringValue().equals("password")) {
                    element.remove(param);
                }
            }
        }
    }

    return true;
}

From source file:org.sapia.util.xml.confix.Dom4jProcessor.java

License:Open Source License

private Object process(Object aParent, Element anElement, String setterName) throws ProcessingException {
    String aName = anElement.getName();

    if (setterName == null) {
        setterName = aName;//from   w  ww . ja  v  a  2s.c o  m
    }

    CreationStatus status = null;

    try {
        status = getObjectFactory().newObjectFor(anElement.getNamespace().getPrefix(),
                anElement.getNamespace().getURI(), aName, aParent);
    } catch (ObjectCreationException oce) {
        if (aParent == null) {
            String aMessage = "Unable to create an object for the element " + anElement;

            throw new ProcessingException(aMessage, oce);
        }
        List children;
        if ((aParent != null)
                && (containsMethod("set", aParent, aName) || containsMethod("add", aParent, aName))
                && ((children = anElement.elements()).size() == 1)) {
            Element child = (Element) children.get(0);
            process(aParent, child, setterName);

            return aParent;
        }

        try {
            String aValue = anElement.getTextTrim();

            invokeSetter(aParent.getClass().getName(), aParent, aName, aValue);

            return aParent;
        } catch (ConfigurationException ce) {
            String aMessage = "Unable to create an object nor to call a setter for the element " + anElement;
            oce.printStackTrace();
            throw new ProcessingException(aMessage, ce);
        }
    }

    String text = anElement.getTextTrim();

    if (text.length() > 0) {
        try {
            invokeSetter(aName, status.getCreated(), "Text", text);
        } catch (ConfigurationException ce) {
            String aMessage = "The object '" + aName + "' does not accept free text";

            throw new ProcessingException(aMessage, ce);
        }
    }

    try {
        // Process the attributes of the DOM element
        for (Iterator it = anElement.attributeIterator(); it.hasNext();) {
            Attribute attr = (Attribute) it.next();

            invokeSetter(aName, status.getCreated(), attr.getName(), attr.getValue());
        }

        // Process the child elements
        for (Iterator it = anElement.elementIterator(); it.hasNext();) {
            Element child = (Element) it.next();

            if (status.getCreated() instanceof Dom4jHandlerIF) {
                ((Dom4jHandlerIF) status.getCreated()).handleElement(child);
            } else if (status.getCreated() instanceof XMLConsumer) {
                XMLConsumer cons = (XMLConsumer) status.getCreated();
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                XMLWriter writer;
                try {
                    writer = new XMLWriter(bos, OutputFormat.createPrettyPrint());
                } catch (UnsupportedEncodingException e) {
                    throw new ProcessingException("Could not instantiate XMLWriter", e);
                }

                try {
                    Element copy = child.createCopy();
                    copy.setDocument(null);
                    writer.write(DocumentHelper.createDocument(copy));
                    ByteArrayInputStream in = new ByteArrayInputStream(bos.toByteArray());
                    InputSource is = new InputSource(in);
                    cons.consume(is);
                } catch (Exception e) {
                    throw new ProcessingException("Could not pipe content of element: "
                            + child.getQualifiedName() + " to XMLConsumer", e);
                }
            } else {
                process(status.getCreated(), child);
            }
        }

        // before assigning to parent, check if object
        // implements ObjectCreationCallback.
        if (status.getCreated() instanceof ObjectCreationCallback) {
            status._created = ((ObjectCreationCallback) status.getCreated()).onCreate();
        }

        // assign obj to parent through setXXX or addXXX
        if ((aParent != null) && !status.wasAssigned() && !(status.getCreated() instanceof NullObject)) {
            assignToParent(aParent, status.getCreated(), setterName);
        }

        if (status.getCreated() instanceof NullObject) {
            return null;
        }

        return status.getCreated();
    } catch (ConfigurationException ce) {
        String aMessage = "Unable to process the content of the element " + aName;

        throw new ProcessingException(aMessage, ce);
    }
}