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.innovationgate.wgpublisher.WGACore.java

License:Open Source License

/**
 * stores the given licenses data as wga.skey in config path and do necessary updates on wga.xml to reflect new license file
 * @param licenseData/*  w  w w  . j a  v  a  2  s.c  o  m*/
 * @throws WGSystemException 
 */
/*
public void storeLicenseData(byte[] licenseData) throws WGSystemException {
try {            
    File licenseFile = new File(configFile.getParentFile(), LICENSE_FILENAME);
                        
    if (licenseFile.exists()) {
        licenseFile.createNewFile();
    }
    ByteArrayInputStream bin = new ByteArrayInputStream(licenseData);
    FileOutputStream fout = new FileOutputStream(licenseFile);
    WGUtils.inToOut(bin, fout, 1024);
    fout.close();
    log.info("New license data successfully saved in license file '" + licenseFile.getAbsolutePath()  + "'.");
                        
    // update configuration
    updateConfig();            
}
catch (Exception e) {
    log.error("Unable to store license data.", e);
    throw new WGSystemException("Unable to store license data.", e);
}
        
}*/

private void loadOptions(Map<String, String> thePublisherOptions, Element publisherOptionElements) {
    Iterator publisherOptionsIt = publisherOptionElements.elementIterator("option");
    while (publisherOptionsIt.hasNext()) {
        Element publisherOptionElem = (Element) publisherOptionsIt.next();
        try {
            thePublisherOptions.put(publisherOptionElem.attributeValue("name"),
                    readOptionValue(publisherOptionElem));
        } catch (IOException e) {
            getLog().error("Exception decoding option '" + publisherOptionElem.attributeValue("name") + "'", e);
        }
    }
}

From source file:de.tud.kom.p2psim.impl.network.gnp.GnpNetLayerFactory.java

License:Open Source License

public void setGnpFile(String gnpFileName) {

    File gnpFile = new File(gnpFileName);
    hostPool = new HashMap<IPv4NetID, GnpHostInfo>();
    namedGroups = new HashMap<String, ArrayList<IPv4NetID>>();
    log.info("Read hosts from file " + gnpFile);

    SAXReader reader = new SAXReader(false);

    Document configuration = null;
    try {//  w  w  w.j a va 2s  . com
        configuration = reader.read(gnpFile);
    } catch (DocumentException e) {
        e.printStackTrace();
    }

    Element root = configuration.getRootElement();
    assert root.getName().equals("gnp");

    for (Object obj : root.elements()) {
        Element elem = (Element) obj;
        if (elem.getName().equals("GroupLookup")) {
            for (Iterator iter = elem.elementIterator("Group"); iter.hasNext();) {
                Element variable = (Element) iter.next();
                String id = variable.attributeValue("id");

                ArrayList<IPv4NetID> group = new ArrayList<IPv4NetID>();
                for (Iterator ipIter = variable.elementIterator("IPs"); ipIter.hasNext();) {
                    Element ipElement = (Element) ipIter.next();
                    String[] ips = ipElement.attributeValue("value").split(",");
                    for (int c = 0; c < ips.length; c++)
                        group.add(new IPv4NetID(Long.parseLong(ips[c])));
                }
                if (namedGroups.containsKey(id)) {
                    throw new IllegalStateException(
                            "Multiple Group Definition in " + gnpFileName + " ( Group: " + id + " )");
                } else {
                    namedGroups.put(id, group);
                }
            }
        } else if (elem.getName().equals("Hosts")) {
            for (Iterator iter = elem.elementIterator("Host"); iter.hasNext();) {
                Element variable = (Element) iter.next();

                // IP-Address
                IPv4NetID hostID = new IPv4NetID(Long.parseLong(variable.attributeValue("ip")));

                // GNP-Coordinates
                String[] coordinatesS = variable.attributeValue("coordinates").split(",");
                double[] coordinatesD = new double[coordinatesS.length];
                for (int c = 0; c < coordinatesD.length; c++)
                    coordinatesD[c] = Double.parseDouble(coordinatesS[c]);
                GnpPosition gnpPos = new GnpPosition(coordinatesD);

                // GeoLocation
                String continentalArea = variable.attributeValue("continentalArea");
                String countryCode = variable.attributeValue("countryCode");
                String region = variable.attributeValue("region");
                String city = variable.attributeValue("city");
                String isp = variable.attributeValue("isp");
                double longitude = Double.parseDouble(variable.attributeValue("longitude"));
                double latitude = Double.parseDouble(variable.attributeValue("latitude"));
                GeoLocation geoLoc = new GeoLocation(continentalArea, countryCode, region, city, isp, latitude,
                        longitude);

                GnpHostInfo hostInfo = new GnpHostInfo(geoLoc, gnpPos);
                hostPool.put(hostID, hostInfo);
            }
        } else if (elem.getName().equals("PingErLookup")) {
            pingErLookup = new PingErLookup();
            pingErLookup.loadFromXML(elem);

        } else if (elem.getName().equals("CountryLookup")) {
            countryLookup = new CountryLookup();
            countryLookup.importFromXML(elem);
        }
    }
}

From source file:de.tud.kom.p2psim.impl.network.gnp.topology.CountryLookup.java

License:Open Source License

/**
 * Import lockup data from an xml-element.
 * /*from  ww  w .  j a  va  2s .  c  o  m*/
 * @param element
 */
public void importFromXML(Element element) {
    Iterator<Element> iter = element.elementIterator("CountryKey");
    while (iter.hasNext()) {
        Element variable = iter.next();
        String code = variable.attributeValue("code");
        String[] names = new String[3];
        names[0] = variable.attributeValue("countryGeoIP");
        names[1] = variable.attributeValue("countryPingEr");
        names[2] = variable.attributeValue("regionPingEr");
        countryLookup.put(code, names);
        pingErCountryRegions.put(names[1], names[2]);
    }
}

From source file:de.tud.kom.p2psim.impl.network.gnp.topology.PingErLookup.java

License:Open Source License

/**
 * Loads the Class Attributes from an XML Element
 * //  w  ww.j  av  a 2  s .  com
 * @param element
 */
public void loadFromXML(Element element) {
    for (Iterator<Element> iter = element.elementIterator("SummaryReport"); iter.hasNext();) {
        Element variable = iter.next();
        String regionFrom = variable.attributeValue("from");
        String regionTo = variable.attributeValue("to");
        double minRtt = Double.parseDouble(variable.attributeValue("minimumRtt"));
        double averageRtt = Double.parseDouble(variable.attributeValue("averageRtt"));
        double delayVariation = Double.parseDouble(variable.attributeValue("delayVariation"));
        double packetLoss = Double.parseDouble(variable.attributeValue("packetLoss"));
        setData(regionFrom, regionTo, minRtt, DataType.MIN_RTT);
        setData(regionFrom, regionTo, averageRtt, DataType.AVERAGE_RTT);
        setData(regionFrom, regionTo, delayVariation, DataType.VARIATION_RTT);
        setData(regionFrom, regionTo, packetLoss, DataType.PACKET_LOSS);
    }
}

From source file:de.tud.kom.p2psim.impl.scenario.DefaultConfigurator.java

License:Open Source License

/**
 * Process the XML subtree./*from w ww. ja  v a 2  s  . com*/
 * 
 * @param parent
 *            root of the subtree
 */
private void configureFirstLevel(Element parent) {
    if (log.isDebugEnabled())
        log.debug("Configure simulator using " + parent.asXML());
    for (Object obj : parent.elements()) {
        Element elem = (Element) obj;
        if (elem.getName().equals(Configurator.DEFAULT_TAG)) {
            for (Iterator iter = elem.elementIterator(Configurator.VARIABLE_TAG); iter.hasNext();) {
                Element variable = (Element) iter.next();
                String name = variable.attributeValue(Configurator.VARIABLE_NAME_TAG);
                String value = variable.attributeValue(Configurator.VARIABLE_VALUE_TAG);
                if (!variables.containsKey(name)) {
                    // set to default only if not set yet
                    variables.put(name, value);
                }
            }
        } else {
            configureComponent(elem);
        }
    }
}

From source file:de.tud.kom.p2psim.impl.scenario.DOMScenarioFactory.java

License:Open Source License

public void parse(Element elem, Configurator config) {
    // create the scenario wright now.
    ExtendedScenario scenario = newScenario();
    // List<OperationBasedScenarioAction> actions = new
    // LinkedList<OperationBasedScenarioAction>();
    try {/*from  www.  jav a  2  s  .c  o m*/
        int actionCounter = 0;
        for (Iterator it = elem.elementIterator(Configurator.ACTION_TAG); it.hasNext();) {
            Element actionElem = (Element) it.next();
            String hostId = actionElem.attributeValue("hostID");
            String time = actionElem.attributeValue("time");
            String line = actionElem.getTextTrim();
            String[] tokens = line.split(paramsDelimiter);
            assert tokens.length >= 1 : Arrays.asList(tokens);

            String method = tokens[0];
            String[] params = new String[tokens.length - 1];
            System.arraycopy(tokens, 1, params, 0, params.length);

            scenario.createActions(hostId, time, method, params);
            actionCounter++;
        }
        log.debug("Created " + actionCounter + " actions");
    } catch (Exception e) {
        throw new ConfigurationException("Failed to parse DOM element " + elem.asXML() + " reason: ", e);
    }
}

From source file:de.tudarmstadt.ukp.dkpro.wsd.io.reader.SemCorXMLReader.java

License:Apache License

@Override
@SuppressWarnings("unchecked")
public void getNext(JCas jCas) throws IOException, CollectionException {
    mappingProvider.configure(jCas.getCas());

    // Open the next file
    Document document;//from  w ww  .  jav  a  2 s . c o m
    SAXReader reader = new SAXReader();
    NullEntityResolver resolver = new NullEntityResolver();
    reader.setEntityResolver(resolver);
    InputStream is = new BufferedInputStream(nextFile().getInputStream());
    try {
        document = reader.read(is);
    } catch (DocumentException e) {
        throw new CollectionException(e);
    }

    // Get metadata from the top two elements
    Element contextFile = document.getRootElement();
    if (contextFile.getName().equals(ELEMENT_CONTEXTFILE) == false) {
        throw new CollectionException("unknown_element", new Object[] { contextFile.getName() });
    }
    Iterator<Element> contextIterator = contextFile.elementIterator(ELEMENT_CONTEXT);
    if (contextIterator.hasNext() == false) {
        throw new CollectionException("element_not_found",
                new Object[] { ELEMENT_CONTEXT, ELEMENT_CONTEXTFILE });
    }
    Element context = contextIterator.next();
    setDocumentMetadata(jCas, contextFile, context);
    String documentId = context.attributeValue(ATTR_FILENAME);
    logger.debug("Found context filename: " + documentId);

    // Process document text
    StringBuffer documentText = processParagraphs(jCas, context, documentId);
    if (documentText.length() == 0) {
        documentText = processSentences(jCas, context, 0, documentId);
    }
    jCas.setDocumentText(documentText.toString());
    logger.info("Read " + validWordFormCount + " valid word forms; skipped "
            + (totalWordFormCount - validWordFormCount));
}

From source file:de.tudarmstadt.ukp.dkpro.wsd.io.reader.SemCorXMLReader.java

License:Apache License

@SuppressWarnings("unchecked")
private StringBuffer processParagraphs(JCas jCas, Element element, String idPrefix) throws CollectionException {
    StringBuffer paragraphText = new StringBuffer();
    for (Iterator<Element> paragraphIterator = element.elementIterator(ELEMENT_PARAGRAPH); paragraphIterator
            .hasNext();) {//  w w w. j  a v a 2 s.  co m
        Element paragraph = paragraphIterator.next();
        String paragraphId = paragraph.attributeValue(ATTR_PNUM);
        Paragraph paragraphAnnotation = new Paragraph(jCas);
        paragraphAnnotation.setBegin(paragraphText.length());

        paragraphText.append(
                processSentences(jCas, paragraph, paragraphText.length(), idPrefix + ".p" + paragraphId));

        paragraphAnnotation.setEnd(paragraphText.length());
        paragraphAnnotation.addToIndexes();
    }
    return paragraphText;
}

From source file:de.tudarmstadt.ukp.dkpro.wsd.io.reader.SemCorXMLReader.java

License:Apache License

@SuppressWarnings("unchecked")
private StringBuffer processSentences(JCas jCas, Element element, int offset, String idPrefix)
        throws CollectionException {
    StringBuffer sentenceText = new StringBuffer();
    for (Iterator<Element> sentenceIterator = element.elementIterator(ELEMENT_SENTENCE); sentenceIterator
            .hasNext();) {//from   w w w  . j  av a2  s .  c o  m
        Element sentence = sentenceIterator.next();
        Sentence sentenceAnnotation = new Sentence(jCas);
        sentenceAnnotation.setBegin(offset);
        String sentenceId = sentence.attributeValue(ATTR_SNUM);
        int wordFormCount = 0;

        for (Iterator<Node> nodeIterator = sentence.nodeIterator(); nodeIterator.hasNext();) {
            Node node = nodeIterator.next();
            String nodeText = node.getText().replace('\n', ' ');
            int oldOffset = offset;
            offset += nodeText.length();
            sentenceText.append(nodeText);

            if (node.getName() == null) {
                continue;
            }

            if (node.getName().equals(ELEMENT_PUNCTUATION)) {
                logger.trace("Found punctuation " + node.getText());
                continue;
            }

            if (node.getName().equals(ELEMENT_WORDFORM) == false) {
                throw new CollectionException("unknown_element", new Object[] { node.getName() });
            }

            // Find or construct a unique ID for this word form
            wordFormCount++;
            totalWordFormCount++;
            Element wordForm = (Element) node;
            String wordFormId = wordForm.attributeValue(ATTR_ID);
            if (wordFormId == null) {
                wordFormId = idPrefix + ".s" + sentenceId + ".w" + wordFormCount;
            }
            logger.trace("Found wf id: " + wordFormId);

            String lemma = wordForm.attributeValue(ATTR_LEMMA);
            String pos = wordForm.attributeValue(ATTR_POS);

            // write DKPro Core annotations Token, Lemma, and POS
            if (shouldWriteCoreAnnotations) {
                Lemma lemmaAnno = null;
                if (lemma != null) {
                    lemmaAnno = new Lemma(jCas, offset, oldOffset + nodeText.length());
                    lemmaAnno.setValue(lemma);
                    lemmaAnno.addToIndexes();
                }

                de.tudarmstadt.ukp.dkpro.core.api.lexmorph.type.pos.POS posAnno = null;
                if (pos != null) {
                    Type posTag = mappingProvider.getTagType(pos);
                    posAnno = (de.tudarmstadt.ukp.dkpro.core.api.lexmorph.type.pos.POS) jCas.getCas()
                            .createAnnotation(posTag, oldOffset, oldOffset + nodeText.length());
                    posAnno.setPosValue(pos);
                    posAnno.addToIndexes();
                }

                Token tokenAnno = new Token(jCas, oldOffset, oldOffset + nodeText.length());
                tokenAnno.setLemma(lemmaAnno);
                tokenAnno.setPos(posAnno);
                tokenAnno.addToIndexes();
            }

            // Skip <wf> elements which are not marked as "done"
            if (skipUndone == true && wordForm.attributeValue(ATTR_CMD).equals(VAL_DONE) == false) {
                logger.debug("Skipping wf " + wordFormId + ": not marked as 'done'");
                continue;
            }

            // Skip <wf> elements for which semantic tags could not be
            // assigned
            if (skipUnassignable == true && wordForm.attributeValue(ATTR_OT) != null) {
                logger.debug("Skipping wf " + wordFormId + ": ot=" + wordForm.attributeValue(ATTR_OT));
                continue;
            }

            // Find the number of valid sense tags for this word form.
            // Tags with a wnsn attribute value of "0"
            // (or "-1" according to some specifications) could not be
            // mapped and so are skipped.
            String wnsn = wordForm.attributeValue(ATTR_WNSN);
            if (skipWithoutWnsn == true && wnsn == null) {
                logger.debug("Skipping wf " + wordFormId + ": no wnsn");
                continue;
            }
            int totalValidWf = 0;
            String wnsns[] = wnsn.split(";");
            for (String s : wnsns) {
                if (isValidWnsn(s)) {
                    totalValidWf++;
                }
            }
            if (skipWithoutWnsn == true && totalValidWf == 0) {
                logger.debug("Skipping wf " + wordFormId + ": wnsn=" + wordForm.attributeValue(ATTR_WNSN));
                continue;
            }

            // Skip word forms without a lemma
            if (skipWithoutLemma == true && lemma == null) {
                logger.warn("Sipping wf " + wordFormId + ": no lemma");
                continue;
            }

            // Skip word forms without a POS
            if (skipWithoutPos == true && pos == null) {
                logger.warn("Skipping " + wordFormId + ": no pos");
                continue;
            }
            try {
                pos = semCorPosToPOS(pos).toString();
            } catch (IllegalArgumentException e) {
                logger.warn("Skipping wf " + wordFormId + ": unrecognized pos=" + pos);
                continue;
            }

            // Create the necessary WSDItem and LexicalItemConstituent
            // annotations for this word form
            LexicalItemConstituent c = newLexicalItemConstituent(jCas, wordFormId, ELEMENT_WORDFORM, oldOffset,
                    nodeText.length());
            WSDItem w = newWsdItem(jCas, wordFormId, oldOffset, nodeText.length(), pos, lemma);
            w.setConstituents(new FSArray(jCas, 1));
            w.setConstituents(0, c);

            // Get an array of sense tags. Sense tags are found
            // in the lexsn attribute and are separated with
            // semicolons. Sometimes the head_word field contains
            // a superfluous character in parentheses which must
            // be removed. (These quirks are not documented in
            // the SemCor file format specification.)
            String lexsns[] = wordForm.attributeValue(ATTR_LEXSN).replaceAll("\\(.\\)", "").split(";");
            FSArray senseArray = new FSArray(jCas, totalValidWf);
            int validWfCount = 0;
            for (int i = 0; i < lexsns.length; i++) {
                if (isValidWnsn(wnsns[i])) {
                    Sense sense = new Sense(jCas);
                    sense.setId(lemma + "%" + lexsns[i]);
                    sense.setConfidence(1.0);
                    sense.addToIndexes();
                    senseArray.set(validWfCount++, sense);
                }
            }

            WSDResult wsdResult = new WSDResult(jCas, oldOffset, oldOffset + nodeText.length());
            wsdResult.setWsdItem(w);
            wsdResult.setSenses(senseArray);
            wsdResult.setSenseInventory(senseInventory);
            wsdResult.setDisambiguationMethod(DISAMBIGUATION_METHOD_NAME);
            wsdResult.addToIndexes();
        }

        sentenceAnnotation.setEnd(offset);
        sentenceAnnotation.addToIndexes();
    }
    return sentenceText;
}

From source file:de.tudarmstadt.ukp.dkpro.wsd.senseval.reader.Semeval1AWReader.java

License:Apache License

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

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

        Element sentence = sentenceIterator.next();
        Sentence sentenceAnnotation = new Sentence(jCas);
        sentenceAnnotation.setBegin(offset);

        for (Iterator<Node> nodeIterator = sentence.nodeIterator(); nodeIterator.hasNext();) {

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

            // If the node is a head, create a LexicalItemConstituent and a
            // WSDItem
            if (node.getName() != null && node.getName().equals(HEAD_ELEMENT_NAME)) {
                Element head = (Element) node;
                String id = head.attributeValue(ID_ATTRIBUTE_NAME);

                LexicalItemConstituent c = newLexicalItemConstituent(jCas, id, LIC_TYPE_HEAD, offset,
                        nodeText.length());
                WSDItem w = newWsdItem(jCas, id, LIC_TYPE_HEAD, offset, nodeText.length(),
                        head.attributeValue(POS_ATTRIBUTE_NAME), head.attributeValue(LEMMA_ATTRIBUTE_NAME));
                w.setConstituents(new FSArray(jCas, 1));
                w.setConstituents(0, c);
            } else if (node.getName() != null) {
                throw new CollectionException("unknown_element", new Object[] { node.getName() });
            }

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

        sentenceAnnotation.setEnd(offset);
        sentenceAnnotation.addToIndexes();
        numSentences++;
    }

    // The Semeval-1 DTD requires each text to have at least one sentence
    if (numSentences == 0) {
        throw new CollectionException("element_not_found",
                new Object[] { SENTENCE_ELEMENT_NAME, TEXT_ELEMENT_NAME });
    }

    jCas.setDocumentText(s);

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

    textCount++;
}