Example usage for org.dom4j Element elementIterator

List of usage examples for org.dom4j Element elementIterator

Introduction

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

Prototype

Iterator<Element> elementIterator(QName qName);

Source Link

Document

Returns an iterator over the elements contained in this element which match the given fully qualified name.

Usage

From source file:be.mxs.common.util.pdf.general.dossierCreators.StaffDossierPDFCreator.java

private Vector parsePredefinedWeekSchedulesFromXMLConfigValue() {
    Vector schedules = new Vector();

    // read xml containing predefined weekSchedules
    try {//from  ww  w.  j  a va 2s.c o  m
        SAXReader xmlReader = new SAXReader();
        String sXMLValue = MedwanQuery.getInstance().getConfigString("defaultWeekschedules");
        org.dom4j.Document document = xmlReader.read(new StringReader(sXMLValue));

        if (document != null) {
            org.dom4j.Element root = document.getRootElement();
            Iterator scheduleElems = root.elementIterator("WeekSchedule");

            PredefinedWeekSchedule schedule;
            org.dom4j.Element scheduleElem, timeBlockElem;
            while (scheduleElems.hasNext()) {
                schedule = new PredefinedWeekSchedule();

                scheduleElem = (org.dom4j.Element) scheduleElems.next();
                schedule.id = scheduleElem.attributeValue("id");
                schedule.type = scheduleElem.attributeValue("scheduleType");
                schedule.xml = scheduleElem.asXML();

                // timeblocks
                Iterator timeBlockElems = scheduleElem.element("TimeBlocks").elementIterator("TimeBlock");
                while (timeBlockElems.hasNext()) {
                    timeBlockElem = (org.dom4j.Element) timeBlockElems.next();

                    TimeBlock timeBlock = new TimeBlock();
                    timeBlock.id = checkString(timeBlockElem.attributeValue("id"));
                    timeBlock.dayIdx = checkString(timeBlockElem.elementText("DayIdx"));
                    timeBlock.beginHour = checkString(timeBlockElem.elementText("BeginHour"));
                    timeBlock.endHour = checkString(timeBlockElem.elementText("EndHour"));

                    schedule.timeBlocks.add(timeBlock);
                }

                Collections.sort(schedule.timeBlocks); // on day     
                schedules.add(schedule);
            }
        }
    } catch (Exception e) {
        if (Debug.enabled)
            e.printStackTrace();
        Debug.printProjectErr(e, Thread.currentThread().getStackTrace());
    }

    return schedules;
}

From source file:ch.javasoft.metabolic.compress.config.MetabolicCompressionConfig.java

License:BSD License

/**
 * Returns the compression methods derived from the xml configuration, or 
 * {@link CompressionMethod#NONE} if no methods are specified.
 * //from   w w w. j  a v a 2s. c  om
 * @return   the compression methods   
 * @throws XmlConfigException      if a method cannot be parsed 
 */
public CompressionMethod[] getCompressionMethods() throws XmlConfigException {
    Element elMethods = mRoot.element(XmlElement.compression_methods.getXmlName());
    if (elMethods == null)
        return CompressionMethod.NONE;
    Iterator it = elMethods.elementIterator(XmlElement.method.getXmlName());
    List<CompressionMethod> cmpMethods = new ArrayList<CompressionMethod>();
    while (it.hasNext()) {
        Element elMethod = (Element) it.next();
        String methodName = elMethod.attributeValue(XmlAttribute.name.getXmlName());
        String strOn = elMethod.attributeValue(XmlAttribute.value.getXmlName());
        boolean on = strOn == null ? true : Boolean.parseBoolean(strOn);
        if (on) {
            try {
                cmpMethods.add(CompressionMethod.valueOf(methodName));
            } catch (Exception ex) {
                throw new XmlConfigException("invalid compression method: " + methodName, elMethod);
            }
        }
    }
    CompressionMethod[] res = new CompressionMethod[cmpMethods.size()];
    return cmpMethods.toArray(res);
}

From source file:ch.javasoft.metabolic.efm.config.DistributedConfig.java

License:BSD License

/**
 * Constructor for <code>DistributedConfig</code> with xml configuration.
 * The configuration element looks like this:
 * <pre>//from  w  w w .j  a  v  a 2 s. c  om
 <distribute partition="65536"><!--use power of 4-->
    <nodes vmargs = "-Xmx2500M" level="OFF">
       <node name="node01.cluster.lan" vmargs="-Xmx1G" level="INFO"/>
       <node name="node02.cluster.lan"/>
       <node name="node03.cluster.lan"/>
       <node name="node04.cluster.lan"/>
    </nodes>
    <command value="/usr/bin/rsh [nodename] cd [workdir] ; /usr/bin/java [vmargs] -cp [classpath] [class] [args]"/>
 </distribute>
 * </pre>
 * @param elDistribute         the <tt>distribute</tt> xml element
 * @throws XmlConfigException   if an xml configuration exception occurs,
 *                         for instance due to invalid xml structure
 */
public DistributedConfig(Element elDistribute) throws XmlConfigException {
    final Element elNodes = XmlUtil.getRequiredSingleChildElement(elDistribute, XmlElement.nodes);
    final Element elCommand = XmlUtil.getRequiredSingleChildElement(elDistribute, XmlElement.command);
    final String sPartition = XmlUtil.getRequiredAttributeValue(elDistribute, XmlAttribute.partition);
    final String sThreshold = XmlUtil.getOptionalAttributeValue(elDistribute, XmlAttribute.candidate_threshold,
            "0");

    final List<String> nodeNames = new ArrayList<String>();
    final List<String> vmArgs = new ArrayList<String>();
    final List<String> logLevels = new ArrayList<String>();

    @SuppressWarnings("unchecked")
    final Iterator<Element> nodeIt = elNodes.elementIterator(XmlElement.node.getXmlName());
    while (nodeIt.hasNext()) {
        final Element elNode = nodeIt.next();
        nodeNames.add(XmlUtil.getRequiredAttributeValue(elNode, XmlAttribute.name));
        //vmargs
        String vmargs = elNode.attributeValue(XmlAttribute.vmargs.getXmlName());
        if (vmargs == null)
            vmargs = elNodes.attributeValue(XmlAttribute.vmargs.getXmlName());
        vmArgs.add(vmargs);
        //log level
        String logLevel = elNode.attributeValue(XmlAttribute.level.getXmlName());
        if (logLevel == null)
            logLevel = elNodes.attributeValue(XmlAttribute.level.getXmlName());
        if (logLevel == null)
            logLevel = Level.INFO.getName();
        logLevels.add(logLevel);
    }
    this.nodeNames = Collections.unmodifiableList(nodeNames);
    this.vmArgs = Collections.unmodifiableList(vmArgs);
    this.logLevels = Collections.unmodifiableList(logLevels);
    this.command = XmlUtil.getRequiredAttributeValue(elCommand, XmlAttribute.value);
    try {
        this.partition = Integer.parseInt(sPartition);
    } catch (Exception e) {
        throw new XmlConfigException(
                "cannot parse distribute attribute 'partitions': " + sPartition + ", e=" + e, elDistribute, e);
    }
    try {
        this.candidateThreashold = Long.parseLong(sThreshold);
    } catch (Exception e) {
        throw new XmlConfigException(
                "cannot parse distribute attribute 'candidate-threshold': " + sThreshold + ", e=" + e,
                elDistribute, e);
    }
    //check partition, must be power of 4
    int cur = 1;
    while (partition / cur > 1) {
        cur <<= 2;// *= 4
    }
    if (partition != cur) {
        throw new IllegalArgumentException("distributed partition must be a power of 4, but is " + partition);
    }
}

From source file:ch.javasoft.metabolic.parse.SbmlParser.java

License:BSD License

private Map<String, CompartmentMetabolite> parseMetabolites(Element elMetas,
        Map<Annotateable, Map<String, String>> annotations) throws DocumentException {
    Map<String, CompartmentMetabolite> metas = new LinkedHashMap<String, CompartmentMetabolite>();
    Iterator it = elMetas.elementIterator(ELEMENT_METABOLITE);
    while (it.hasNext()) {
        Element el = (Element) it.next();
        String metaId = el.attributeValue(ATTRIBUTE_ID);
        String metaName = el.attributeValue(ATTRIBUTE_NAME);
        String compartment = el.attributeValue(ATTRIBUTE_COMPARTMENT);
        CompartmentMetabolite meta = metaName == null ? new CompartmentMetabolite(metaId, compartment)
                : new CompartmentMetabolite(metaId, metaName, compartment);

        if (metas.put(metaId, meta) != null) {
            throw new DocumentException("duplicate metabolite: " + metaId);
        }/*ww  w . j av a2 s.  co  m*/
        parseAnnotations(el, meta, annotations);
    }
    return metas;
}

From source file:ch.javasoft.metabolic.parse.SbmlParser.java

License:BSD License

private static void parseAnnotations(Element element, Annotateable annotateable,
        Map<Annotateable, Map<String, String>> annotations) throws DocumentException {
    Iterator noteIt = element.elementIterator(ELEMENT_NOTES);
    while (noteIt.hasNext()) {
        Element notes = (Element) noteIt.next();
        Iterator htmlpIt = notes.elementIterator(ELEMENT_HTML_P);
        while (htmlpIt.hasNext()) {
            Element note = (Element) htmlpIt.next();
            String txt = note.getText();
            String[] keyVal = txt.trim().split(":");
            if (keyVal.length != 2) {
                throw new DocumentException("invalid annotation format: " + txt);
            }/*from   w  ww  . java  2 s .c  o  m*/
            String key = keyVal[0].trim();
            String val = keyVal[1].trim();
            getAnnotationMap(annotations, annotateable, true).put(key, val);
        }
    }
}

From source file:ch.javasoft.metabolic.parse.SbmlParser.java

License:BSD License

@SuppressWarnings("unchecked")
private static Iterator<Element> elementIterator(Element parent, String childName) {
    return parent == null ? Collections.emptyList().iterator() : parent.elementIterator(childName);
}

From source file:ch.javasoft.xml.config.XmlConfig.java

License:BSD License

/**
 * Parses the given document and returns an XmlConfig instance. Note that
 * this document is expected to contain an application element (direct child
 * of root element) with a name attribute and possible with arg child nodes.
 * Such a document is usually received by calling {@link #toXmlDocument()}.
 *//* ww w  . j  ava 2  s  . c o m*/
@SuppressWarnings("unchecked")
public static XmlConfig fromXmlDocument(Document doc) {
    final Element app = doc.getRootElement().element(XmlElement.application.getXmlName());
    final String appName = app.attributeValue(XmlAttribute.name.getXmlName());
    final List<String> args = new ArrayList<String>();
    final Iterator<Element> it = app.elementIterator(XmlElement.arg.getXmlName());
    while (it.hasNext()) {
        args.add(it.next().attributeValue(XmlAttribute.value.getXmlName()));
    }
    doc.remove(app);
    return new XmlConfig(appName, doc, args.toArray(new String[args.size()]));
}

From source file:ch.javasoft.xml.config.XmlUtil.java

License:BSD License

/**
 * Returns the child element of the given type which has the desired 
 * attribute value in the given attribute. In xpath, this would be somewhat
 * like <code>/child[@attribute=$attributeValue]</code>
 * <p>/*w w  w .j  a  va2  s .c  om*/
 * If multiple children match the criteria, an exception is thrown. If no
 * child matching the criteria is found, then either <code>null</code> is
 * returned (if <code>throwExceptionIfNull==false</code>), or an exception
 * is thrown (otherwise).
 * 
 * @param element            the parent element containing the desired 
 *                         child element
 * @param child               specifies the name of the child element
 * @param attribute            specifies the name of the identifying attribute
 * @param attributeValue      the desired attribute value
 * @param throwExceptionIfNull   if <code>true</code>, an exception is thrown 
 *                         if no child matches the criteria
 * @return                  the desired child element, or 
 *                         <code>null</code> if 
 *                         <code>throwExceptionIfNull==false</code> and
 *                         no child element matched the criteria
 * @throws XmlConfigException   If multiple matches occur, or if no match
 *                         was found and exception throwing is desired
 *                         for this case (see <code>throwExceptionIfNull</code>)
 */
@SuppressWarnings("unchecked")
public static Element getChildElementByAttributeValue(Element element, XmlNode child, XmlNode attribute,
        String attributeValue, boolean throwExceptionIfNull) throws XmlConfigException {
    Element res = null;
    Iterator<Element> it = element.elementIterator(child.getXmlName());
    while (it.hasNext()) {
        Element el = it.next();
        String attValue = el.attributeValue(attribute.getXmlName());
        if (attributeValue.equals(attValue)) {
            if (res == null)
                res = el;
            else {
                throw new XmlConfigException("multiple matches for " + child.getXmlName()
                        + " children with attribute " + attribute.getXmlName() + "='" + attributeValue + "'",
                        element);
            }
        }
    }
    if (res == null && throwExceptionIfNull) {
        throw new XmlConfigException("missing " + child.getXmlName() + " child with attribute "
                + attribute.getXmlName() + "='" + attributeValue + "'", element);
    }
    return res;
}

From source file:ch.javasoft.xml.config.XmlUtil.java

License:BSD License

/**
 * Returns a typed iterator for child elements of a certain type
 * /* w ww . jav a  2 s .  c  om*/
 * @param element    parent of which certain child elements are desired
 * @param childType node defining the name of the desired child elements
 */
@SuppressWarnings("unchecked")
public static Iterator<Element> getChildElements(Element element, XmlNode childType) throws XmlConfigException {
    return element.elementIterator(childType.getXmlName());
}

From source file:cn.com.iscs.base.util.XMLProperties.java

License:Open Source License

/**
 * Sets a property to an array of values. Multiple values matching the same
 * property is mapped to an XML file as multiple elements containing each
 * value. For example, using the name "foo.bar.prop", and the value string
 * array containing {"some value", "other value", "last value"} would produce
 * the following XML:/*from   ww w.j  a v  a  2 s. c  o m*/
 * 
 * <pre>
 * &lt;foo&gt;
 *     &lt;bar&gt;
 *         &lt;prop&gt;some value&lt;/prop&gt;
 *         &lt;prop&gt;other value&lt;/prop&gt;
 *         &lt;prop&gt;last value&lt;/prop&gt;
 *     &lt;/bar&gt;
 * &lt;/foo&gt;
 * </pre>
 * 
 * @param name
 *          the name of the property.
 * @param values
 *          the values for the property (can be empty but not null).
 */
public void setProperties(String name, List<String> values) {
    String[] propName = parsePropertyName(name);
    // Search for this property by traversing down the XML heirarchy,
    // stopping one short.
    Element element = document.getRootElement();
    for (int i = 0; i < propName.length - 1; i++) {
        // If we don't find this part of the property in the XML heirarchy
        // we add it as a new node
        if (element.element(propName[i]) == null) {
            element.addElement(propName[i]);
        }
        element = element.element(propName[i]);
    }
    String childName = propName[propName.length - 1];
    // We found matching property, clear all children.
    List<Element> toRemove = new ArrayList<Element>();
    Iterator iter = element.elementIterator(childName);
    while (iter.hasNext()) {
        toRemove.add((Element) iter.next());
    }
    for (iter = toRemove.iterator(); iter.hasNext();) {
        element.remove((Element) iter.next());
    }
    // Add the new children.
    for (String value : values) {
        Element childElement = element.addElement(childName);
        if (value.startsWith("<![CDATA[")) {
            Iterator it = childElement.nodeIterator();
            while (it.hasNext()) {
                Node node = (Node) it.next();
                if (node instanceof CDATA) {
                    childElement.remove(node);
                    break;
                }
            }
            childElement.addCDATA(value.substring(9, value.length() - 3));
        } else {
            childElement.setText(StringEscapeUtils.escapeXml(value));
        }
    }
    saveProperties();

    // Generate event.
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("value", values);
    //    PropertyEventDispatcher.dispatchEvent(name, PropertyEventDispatcher.EventType.xml_property_set, params);
}