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:de.tudarmstadt.ukp.dkpro.wsd.senseval.reader.Semeval2AWReader.java

License:Apache License

@SuppressWarnings("unchecked")
@Override/*from  w w w.  ja  v a  2 s  .  c  o m*/
public void getNext(JCas jCas) throws IOException, CollectionException {
    int offset = 0;
    String s = "";
    Element text = textIterator.next();

    for (Iterator<Element> sentenceIterator = text.elementIterator(SENTENCE_ELEMENT_NAME); sentenceIterator
            .hasNext();) {

        Map<String, WSDItem> wsdItems = new HashMap<String, WSDItem>();
        Map<String, LexicalItemConstituent> lics = new HashMap<String, LexicalItemConstituent>();
        Map<String, String> sats = new HashMap<String, String>();
        Element sentence = sentenceIterator.next();
        Sentence sentenceAnnotation = new Sentence(jCas);
        sentenceAnnotation.setBegin(offset);

        // Loop over all nodes to get the document text in order
        for (Iterator<Node> nodeIterator = sentence.nodeIterator(); nodeIterator.hasNext();) {

            Node node = nodeIterator.next();
            String nodeText = node.getText().replace('\n', ' ');
            String nodeName = node.getName();

            if (nodeName == null) {
                offset += nodeText.length();
                s += nodeText;
                continue;
            }

            // If the node is a satellite, create a LexicalItemConstituent
            if (nodeName.equals(SATELLITE_ELEMENT_NAME)) {
                String id = ((Element) node).attributeValue(ID_ATTRIBUTE_NAME);
                lics.put(id,
                        newLexicalItemConstituent(jCas, id, LIC_TYPE_SATELLITE, offset, nodeText.length()));
            }

            // If the node is a head, create a LexicalItemConstituent and a WSDItem
            else if (nodeName.equals(HEAD_ELEMENT_NAME)) {
                Element head = (Element) node;
                String id = head.attributeValue(ID_ATTRIBUTE_NAME);
                String satellites = head.attributeValue(SATELLITES_ATTRIBUTE_NAME);

                lics.put(id, newLexicalItemConstituent(jCas, id, LIC_TYPE_HEAD, offset, nodeText.length()));
                wsdItems.put(id, newWsdItem(jCas, id, LIC_TYPE_HEAD, offset, nodeText.length(),
                        head.attributeValue(POS_ATTRIBUTE_NAME), head.attributeValue(LEMMA_ATTRIBUTE_NAME)));

                if (satellites != null)
                    sats.put(id, satellites);
            }

            // If the node is any other element, something is wrong
            else if (node.getNodeTypeName().equals("Entity") == false) {
                throw new CollectionException("unknown_element", new Object[] { node.getName() });
            }

            offset += nodeText.length();
            s += nodeText;
        }

        // Add a sentence annotation
        sentenceAnnotation.setEnd(offset);
        sentenceAnnotation.addToIndexes();

        populateLexicalItemConstituents(jCas, wsdItems, lics, sats);
    }

    jCas.setDocumentText(s);

    try {
        setDocumentMetadata(jCas, text.attributeValue(ID_ATTRIBUTE_NAME));
    } catch (URISyntaxException e) {
        throw new IOException(e);
    }

    textCount++;
}

From source file:de.tu_berlin.cit.intercloud.xmpp.core.packet.Message.java

License:Open Source License

/**
 * Returns the first child element of this packet that matches the
 * given name and namespace. If no matching element is found,
 * <tt>null</tt> will be returned. This is a convenience method to avoid
 * manipulating this underlying packet's Element instance directly.<p>
 *
 * Child elements in extended namespaces are used to extend the features
 * of XMPP. Examples include a "user is typing" indicator and invitations to
 * group chat rooms. Although any valid XML can be included in a child element
 * in an extended namespace, many common features have been standardized
 * as <a href="http://xmpp.org/extensions/">XMPP Extension Protocols</a>
 * (XEPs)./*w  w w  . j  a v a2 s.co  m*/
 *
 * @param name the element name.
 * @param namespace the element namespace.
 * @return the first matching child element, or <tt>null</tt> if there
 *      is no matching child element.
 */
@SuppressWarnings("unchecked")
public Element getChildElement(String name, String namespace) {
    for (Iterator<Element> i = element.elementIterator(name); i.hasNext();) {
        Element element = i.next();
        if (element.getNamespaceURI().equals(namespace)) {
            return element;
        }
    }
    return null;
}

From source file:de.tu_berlin.cit.intercloud.xmpp.core.packet.Message.java

License:Open Source License

@SuppressWarnings("unchecked")
public List<Element> getChildElements(String name, String namespace) {
    ArrayList<Element> elements = new ArrayList<Element>();
    for (Iterator<Element> i = element.elementIterator(name); i.hasNext();) {
        Element element = i.next();
        if (element.getNamespaceURI().equals(namespace)) {
            elements.add(element);//from  w  w  w. j  a v a 2 s  . c o m
        }
    }
    return elements;
}

From source file:de.tu_berlin.cit.intercloud.xmpp.core.packet.Roster.java

License:Open Source License

/**
 * Adds a new item to the roster. If the roster packet already contains an item
 * using the same JID, the information in the existing item will be overwritten
 * with the new information.<p>/* w  w w  .  j  a  v a 2s. c o  m*/
 *
 * The XMPP specification recommends that if the roster item is associated with another
 * instant messaging user (human), that the JID be in bare form (e.g. user@domain).
 * Use the {@link JID#toBareJID() toBareJID()} method for a bare JID.
 *
 * @param jid the JID.
 * @param name the nickname.
 * @param ask the ask type.
 * @param subscription the subscription type.
 * @param groups a Collection of groups.
 * @return the newly created item.
 */
@SuppressWarnings("unchecked")
public Item addItem(JID jid, String name, Ask ask, Subscription subscription, Collection<String> groups) {
    if (jid == null) {
        throw new NullPointerException("JID cannot be null");
    }
    if (subscription == null) {
        throw new NullPointerException("Subscription cannot be null");
    }
    Element query = element.element(new QName("query", Namespace.get("jabber:iq:roster")));
    if (query == null) {
        query = element.addElement("query", "jabber:iq:roster");
    }
    Element item = null;
    for (Iterator<Element> i = query.elementIterator("item"); i.hasNext();) {
        Element el = i.next();
        if (el.attributeValue("jid").equals(jid.toString())) {
            item = el;
        }
    }
    if (item == null) {
        item = query.addElement("item");
    }
    item.addAttribute("jid", jid.toBareJID());
    item.addAttribute("name", name);
    if (ask != null) {
        item.addAttribute("ask", ask.toString());
    }
    item.addAttribute("subscription", subscription.toString());
    // Erase existing groups in case the item previously existed.
    for (Iterator<Element> i = item.elementIterator("group"); i.hasNext();) {
        item.remove(i.next());
    }
    // Add in groups.
    if (groups != null) {
        for (String group : groups) {
            item.addElement("group").setText(group);
        }
    }
    return new Item(jid, name, ask, subscription, groups);
}

From source file:de.tu_berlin.cit.intercloud.xmpp.core.packet.Roster.java

License:Open Source License

/**
 * Removes an item from this roster.//from   w  w w .  ja  va 2  s  .c o  m
 *
 * @param jid the JID of the item to remove.
 */
@SuppressWarnings("unchecked")
public void removeItem(JID jid) {
    Element query = element.element(new QName("query", Namespace.get("jabber:iq:roster")));
    if (query != null) {
        for (Iterator<Element> i = query.elementIterator("item"); i.hasNext();) {
            Element item = i.next();
            if (item.attributeValue("jid").equals(jid.toString())) {
                query.remove(item);
                return;
            }
        }
    }
}

From source file:de.tu_berlin.cit.intercloud.xmpp.core.packet.Roster.java

License:Open Source License

/**
 * Returns an unmodifiable copy of the {@link Item Items} in the roster packet.
 *
 * @return an unmodifable copy of the {@link Item Items} in the roster packet.
 *//*from  w ww .ja  v a2 s.  co m*/
@SuppressWarnings("unchecked")
public Collection<Item> getItems() {
    Collection<Item> items = new ArrayList<Item>();
    Element query = element.element(new QName("query", Namespace.get("jabber:iq:roster")));
    if (query != null) {
        for (Iterator<Element> i = query.elementIterator("item"); i.hasNext();) {
            Element item = i.next();
            String jid = item.attributeValue("jid");
            String name = item.attributeValue("name");
            String ask = item.attributeValue("ask");
            String subscription = item.attributeValue("subscription");
            Collection<String> groups = new ArrayList<String>();
            for (Iterator<Element> j = item.elementIterator("group"); j.hasNext();) {
                Element group = j.next();
                groups.add(group.getText().trim());
            }
            Ask askStatus = ask == null ? null : Ask.valueOf(ask);
            Subscription subStatus = subscription == null ? null : Subscription.valueOf(subscription);
            items.add(new Item(new JID(jid), name, askStatus, subStatus, groups));
        }
    }
    return Collections.unmodifiableCollection(items);
}

From source file:de.tu_berlin.cit.rwx4j.xmpp.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:
 * <pre>/*from ww w  .j  av  a2  s.c  o  m*/
 * &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 toRemove = new ArrayList();
    Iterator iter = element.elementIterator(childName);
    while (iter.hasNext()) {
        toRemove.add(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[")) {
            childElement.addCDATA(value.substring(9, value.length() - 3));
        } else {
            childElement.setText(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);
}

From source file:de.xwic.sandbox.server.installer.XmlImport.java

License:Apache License

/**
 * @param root//from   w ww.  j  a  v  a  2s. c  o  m
 */
private void importConfig(Element root) {

    IPicklisteDAO dao = (IPicklisteDAO) DAOSystem.getDAO(IPicklisteDAO.class);

    for (Iterator<?> it = root.elementIterator("key"); it.hasNext();) {
        Element element = (Element) it.next();
        String id = element.attributeValue("id");

        Element elValue = element.element("value");
        Element elPl = element.element("picklistentry");
        if (elValue != null) {
            ServerConfig.set(id, elValue.getTextTrim());
        } else if (elPl != null) {
            String list = elPl.attributeValue("list");
            String lang = elPl.attributeValue("lang");
            String text = elPl.getTextTrim();
            if (list != null && lang != null && text != null) {
                IPickliste pListe = dao.getPicklisteByKey(list);
                if (pListe != null) {
                    PicklistTextQuery tquery = new PicklistTextQuery();
                    tquery.setLanguageId(lang);
                    tquery.setBezeichnung(text);
                    tquery.setPicklisteID(pListe.getId());

                    List<?> result = dao.getEntities(null, tquery);
                    if (result.isEmpty()) {
                        log.info("WARNING: Picklistentry not found specified for " + id);
                        log.info("Creating entry '" + text + "'");

                        IPicklistEntry entry = dao.createPickListEntry(pListe);
                        for (Iterator<?> itLang = ConfigurationManager.getSetup().getLanguages()
                                .iterator(); itLang.hasNext();) {
                            Language language = (Language) itLang.next();
                            dao.createBezeichnung(entry, language.getId(), text);
                        }

                        ServerConfig.set(id, entry.getId());

                    } else {
                        IPicklistText pText = (IPicklistText) result.get(0);
                        ServerConfig.set(id, pText.getPicklistEntry().getId());
                        if (result.size() > 1) {
                            log.info("WARNING: Found more then one picklistentries that match for ID " + id);
                        }
                    }
                }
            }
        }

    }

}

From source file:de.xwic.sandbox.server.installer.XmlImport.java

License:Apache License

/**
 * @param root//  w w w.  ja v a2s . com
 * @throws ConfigurationException
 */
private void importAll(Element data) throws ConfigurationException {

    for (Iterator<?> it = data.elementIterator(XmlExport.ELM_ENTITIES); it.hasNext();) {

        Element elEntities = (Element) it.next();
        importEntities(elEntities);

    }

}

From source file:de.xwic.sandbox.server.installer.XmlImport.java

License:Apache License

/**
 * @param elEntities/*  www. ja va2s  .com*/
 * @throws ConfigurationException
 */
private void importEntities(Element elEntities) throws ConfigurationException {

    String type = elEntities.attributeValue("type");
    DAO dao = DAOSystem.findDAOforEntity(type);
    EntityDescriptor descr = DAOSystem.getEntityDescriptor(type);

    int count = 0;
    for (Iterator<?> it = elEntities.elementIterator(XmlExport.ELM_ENTITY); it.hasNext();) {

        Element elEntity = (Element) it.next();
        String idStr = elEntity.attributeValue("id");
        int id = (idStr != null && idStr.length() != 0) ? Integer.parseInt(elEntity.attributeValue("id")) : -1;

        IEntity entity = dao.createEntity();
        readEntityProperties(descr, elEntity, entity);

        dao.update(entity);
        if (id != -1) {
            importedEntities.put(new EntityKey(type, id), Integer.valueOf(entity.getId()));
        }
        //log.info((count++) + " imp " + type + " id: "+ id + " as " + entity.getId());
        count++;
    }
    log.info("imported " + count + " entities.");

}