Example usage for org.dom4j Element attribute

List of usage examples for org.dom4j Element attribute

Introduction

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

Prototype

Attribute attribute(QName qName);

Source Link

Document

DOCUMENT ME!

Usage

From source file:NessusXMLParser.java

License:Open Source License

public static void parseNessus(String nessusReport) {

    try {//from  w ww .  java2  s  . c  o m

        SAXReader saxReader = new SAXReader();

        FileWriter fr = new FileWriter("vulInfo.txt");

        Document document = saxReader.read(nessusReport);

        // each entry is indexed by one cve_id
        List reportHost = document.selectNodes(
                "/*[local-name(.)='NessusClientData_v2']/*[local-name(.)='Report']/*[local-name(.)='ReportHost']");
        Iterator reportHostItrt = reportHost.iterator();

        while (reportHostItrt.hasNext()) {

            Element host = (Element) reportHostItrt.next();

            //   System.out.println("host name is: "+host.attribute(0).getText());

            // element iterator of each entry
            Iterator ei = host.elementIterator();

            // put all of the subelements' names(subelement of entry) to
            // an array list(subele)
            while (ei.hasNext()) {

                Element sube = (Element) ei.next();
                //   System.out.println("attribute count is: "+sube.attributeCount());
                if (!sube.getName().equals("ReportItem"))
                    continue;

                // a list of elements for each entry
                ArrayList<String> subele = new ArrayList<String>();

                Iterator reportItemItrt = sube.elementIterator();
                while (reportItemItrt.hasNext()) {

                    Element reportItemElement = (Element) reportItemItrt.next();
                    //      System.out.println(reportItemElement.getName());
                    subele.add(reportItemElement.getName());
                }

                if (subele.size() == 0 || (!subele.contains("cve")))
                    continue;

                Iterator itr = sube.elementIterator("cve");
                while (itr.hasNext()) {

                    System.out.println("host name is: " + host.attribute(0).getText());

                    fr.write(host.attribute(0).getText() + "\n");

                    Element cve = (Element) itr.next();

                    System.out.println(cve.getText());

                    fr.write(cve.getText() + "\n");

                    System.out.println("port number is: " + sube.attribute(0).getText());

                    fr.write(sube.attribute(0).getText() + "\n");

                    System.out.println("protocol is: " + sube.attribute(2).getText());

                    fr.write(sube.attribute(2).getText() + "\n");

                    System.out.println();

                    //   fr.write("\n");

                }

            }
        } // end of each entry's processing

        fr.close();

        // print out the stack trace for each exception(either documentation
        // exception or IO exception).
    } catch (DocumentException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    }

}

From source file:StreamFlusher.java

License:Apache License

private Fst xml2fst(String filepath) throws Exception {

    // read an XML file representing a network, return the network

    final Fst fst = lib.EmptyLanguageFst();

    final HashSet<Integer> sigma = fst.getSigma();

    SAXReader reader = new SAXReader(); // SAXReader from dom4j

    // each SAXReader handler must define onStart() and onEnd() methods

    // when the kleeneFst element is first found
    reader.addHandler("/kleeneFst", new ElementHandler() {
        public void onStart(ElementPath path) {
            Element current = path.getCurrent();

            // semiring is an attribute on the kleeneFst node
            String semiring = current.attribute("semiring").getValue();
        }/*from w ww  .  j  a  v  a  2s  . c  o m*/

        public void onEnd(ElementPath path) {
        }
    });

    reader.addHandler("/kleeneFst/sigma", new ElementHandler() {
        public void onStart(ElementPath path) {
            if (path.getCurrent().attribute("containsOther").getValue().equals("true")) {
                fst.setContainsOther(true);
            } else {
                fst.setContainsOther(false);
            }
            ;
        }

        public void onEnd(ElementPath path) {
        }
    });

    reader.addHandler("/kleeneFst/sigma/sym", new ElementHandler() {
        public void onStart(ElementPath path) {
        }

        public void onEnd(ElementPath path) {
            Element sym = path.getCurrent();
            sigma.add(symmap.putsym(sym.getText()));

            sym.detach();
        }
    });

    // when the arcs element is first found
    reader.addHandler("/kleeneFst/arcs", new ElementHandler() {
        public void onStart(ElementPath path) {
            // grab the two attrs and convert to int
            int startState = Integer.parseInt(path.getCurrent().attribute("start").getValue());
            int numStates = Integer.parseInt(path.getCurrent().attribute("numStates").getValue());
            lib.AddStates(fst, numStates);
            // native function, add this many  
            // states to the new Fst

            lib.SetStart(fst, startState); // set the start state
        }

        public void onEnd(ElementPath path) {
        }
    });

    // handle each whole arc element
    reader.addHandler("/kleeneFst/arcs/arc", new ElementHandler() {

        // in an ElementHandler, need to supply .onStart(),
        // called when the start tag is found, and
        // .onEnd(), which is called when the end tag is found.

        public void onStart(ElementPath path) {
        }

        public void onEnd(ElementPath path) {

            // retrieve the entire arc element
            Element arc = path.getCurrent();

            // these two are always present
            int src_id = Integer.parseInt(arc.attribute("s").getValue());
            int dest_id = Integer.parseInt(arc.attribute("d").getValue());

            // there will be either one io attr xor separate i and o attrs
            // (keep the io option to facilitate hand-written XML files)

            String input;
            String output;
            Attribute io = arc.attribute("io");
            if (io != null) {
                input = io.getValue();
                output = io.getValue();
            } else {
                input = arc.attribute("i").getValue();
                output = arc.attribute("o").getValue();
            }

            if (!symmap.containsKey(input)) {
                // symbol name in XML file not in the 
                //     current internal symtab
                symmap.putsym(input);
            }
            if (!symmap.containsKey(output)) {
                symmap.putsym(output);
            }

            // the w attr is optional in the arc elmt
            Attribute w = arc.attribute("w");
            if (w != null) {
                // call AddArc to add an arc to the fst 
                //      being built from the XML file description
                // semiring generalization point
                lib.AddArc(fst, src_id, symmap.getint(input), symmap.getint(output),
                        Float.parseFloat(w.getValue()), dest_id);

            } else {
                // semiring generalization point
                lib.AddArcNeutralWeight(fst, src_id, symmap.getint(input), symmap.getint(output), dest_id);
            }

            arc.detach();
        }
    });

    // for each full final element
    reader.addHandler("/kleeneFst/arcs/final", new ElementHandler() {
        public void onStart(ElementPath path) {
        }

        public void onEnd(ElementPath path) {
            Element arc = path.getCurrent();

            // s attr is always present
            int src_id = Integer.parseInt(arc.attribute("s").getValue());

            // the w attr is optional
            Attribute w = arc.attribute("w");
            if (w != null) {
                lib.SetFinal(fst, src_id, Float.parseFloat(w.getValue()));
            } else {
                lib.SetFinalNeutralWeight(fst, src_id);
            }

            arc.detach();
        }
    });

    Document document = null;

    // the actual XML reading/parsing is done here
    try {
        // XmlReader detects the encoding of the XML document and
        // handles BOMs, including the UTF-8 BOMs that Java usually
        // chokes on
        document = reader.read(new XmlReader(new FileInputStream(filepath)));

        // Old, pre-XmlReader code
        //if (encoding.equals("UTF-8")) {
        //   // then need to work around SUN's irresponsible decision not to
        //   //  handle the optional UTF-8 BOM correctly
        //   document = reader.read(new InputStreamReader(
        //            new UTF8BOMStripperInputStream(new FileInputStream(filepath)),
        //            "UTF-8")
        //                 ) ;
        //} else {
        //   document = reader.read(new InputStreamReader(
        //                           new FileInputStream(filepath),
        //                           encoding)
        //                 ) ;
        //}
    } catch (DocumentException de) {
        // dom4j DocumentException extends Exception
        de.printStackTrace();
        throw de;
    } catch (FileNotFoundException fnfe) {
        fnfe.printStackTrace();
        throw fnfe;
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }

    correctSigmaOther(fst);

    return fst;
}

From source file:architecture.common.xml.XmlWriter.java

License:Apache License

/**
 * Determines if element is a special case of XML elements where it contains
 * an xml:space attribute of "preserve". If it does, then retain whitespace.
 */// www .j a  va  2s.  co m
protected final boolean isElementSpacePreserved(Element element) {
    final Attribute attr = (Attribute) element.attribute("space");
    boolean preserveFound = preserve; // default to global state
    if (attr != null) {
        if ("xml".equals(attr.getNamespacePrefix()) && "preserve".equals(attr.getText())) {
            preserveFound = true;
        } else {
            preserveFound = false;
        }
    }
    return preserveFound;
}

From source file:architecture.common.xml.XmlWriter.java

License:Apache License

/**
 * Writes the attributes of the given element
 *
 *///from ww w  . j  a va2  s . c  o m
protected void writeAttributes(Element element) throws IOException {

    // I do not yet handle the case where the same prefix maps to
    // two different URIs. For attributes on the same element
    // this is illegal; but as yet we don't throw an exception
    // if someone tries to do this
    for (int i = 0, size = element.attributeCount(); i < size; i++) {
        Attribute attribute = element.attribute(i);
        Namespace ns = attribute.getNamespace();
        if (ns != null && ns != Namespace.NO_NAMESPACE && ns != Namespace.XML_NAMESPACE) {
            String prefix = ns.getPrefix();
            String uri = namespaceStack.getURI(prefix);
            if (!ns.getURI().equals(uri)) { // output a new namespace
                // declaration
                writeNamespace(ns);
                namespaceStack.push(ns);
            }
        }

        // If the attribute is a namespace declaration, check if we have
        // already
        // written that declaration elsewhere (if that's the case, it must
        // be
        // in the namespace stack
        String attName = attribute.getName();
        if (attName.startsWith("xmlns:")) {
            String prefix = attName.substring(6);
            if (namespaceStack.getNamespaceForPrefix(prefix) == null) {
                String uri = attribute.getValue();
                namespaceStack.push(prefix, uri);
                writeNamespace(prefix, uri);
            }
        } else if (attName.equals("xmlns")) {
            if (namespaceStack.getDefaultNamespace() == null) {
                String uri = attribute.getValue();
                namespaceStack.push(null, uri);
                writeNamespace(null, uri);
            }
        } else {
            char quote = format.getAttributeQuoteCharacter();
            writer.write(" ");
            writer.write(attribute.getQualifiedName());
            writer.write("=");
            writer.write(quote);
            writeEscapeAttributeEntities(attribute.getValue());
            writer.write(quote);
        }
    }
}

From source file:architecture.ee.util.xml.XmlWriter.java

License:Apache License

/**
 * Determines if element is a special case of XML elements
 * where it contains an xml:space attribute of "preserve".
 * If it does, then retain whitespace.//from   w  w  w.  java  2s .co m
 */
protected final boolean isElementSpacePreserved(Element element) {
    final Attribute attr = element.attribute("space");
    boolean preserveFound = preserve; //default to global state
    if (attr != null) {
        if ("xml".equals(attr.getNamespacePrefix()) && "preserve".equals(attr.getText())) {
            preserveFound = true;
        } else {
            preserveFound = false;
        }
    }
    return preserveFound;
}

From source file:architecture.ee.util.xml.XmlWriter.java

License:Apache License

/** Writes the attributes of the given element
  */*w  ww. ja  v  a  2 s . co  m*/
  */
protected void writeAttributes(Element element) throws IOException {

    // I do not yet handle the case where the same prefix maps to
    // two different URIs. For attributes on the same element
    // this is illegal; but as yet we don't throw an exception
    // if someone tries to do this
    for (int i = 0, size = element.attributeCount(); i < size; i++) {
        Attribute attribute = element.attribute(i);
        Namespace ns = attribute.getNamespace();
        if (ns != null && ns != Namespace.NO_NAMESPACE && ns != Namespace.XML_NAMESPACE) {
            String prefix = ns.getPrefix();
            String uri = namespaceStack.getURI(prefix);
            if (!ns.getURI().equals(uri)) { // output a new namespace declaration
                writeNamespace(ns);
                namespaceStack.push(ns);
            }
        }

        // If the attribute is a namespace declaration, check if we have already
        // written that declaration elsewhere (if that's the case, it must be
        // in the namespace stack
        String attName = attribute.getName();
        if (attName.startsWith("xmlns:")) {
            String prefix = attName.substring(6);
            if (namespaceStack.getNamespaceForPrefix(prefix) == null) {
                String uri = attribute.getValue();
                namespaceStack.push(prefix, uri);
                writeNamespace(prefix, uri);
            }
        } else if (attName.equals("xmlns")) {
            if (namespaceStack.getDefaultNamespace() == null) {
                String uri = attribute.getValue();
                namespaceStack.push(null, uri);
                writeNamespace(null, uri);
            }
        } else {
            char quote = format.getAttributeQuoteCharacter();
            writer.write(" ");
            writer.write(attribute.getQualifiedName());
            writer.write("=");
            writer.write(quote);
            writeEscapeAttributeEntities(attribute.getValue());
            writer.write(quote);
        }
    }
}

From source file:batch.performance.visualizer.om.Result.java

License:Open Source License

public void parse(Document dom) throws IOException {
    List runs = dom.getRootElement().elements("run");
    for (Iterator itr = runs.iterator(); itr.hasNext();) {
        Element run = (Element) itr.next();
        final String date = run.attributeValue("date");

        List groups = run.elements("group");
        for (Iterator jtr = groups.iterator(); jtr.hasNext();) {
            Element group = (Element) jtr.next();
            final URL testSpec = new URL(group.attributeValue("name"));

            List results = group.elements("result");
            for (Iterator ktr = results.iterator(); ktr.hasNext();) {
                Element result = (Element) ktr.next();

                URL instance = null;
                if (result.attribute("instance") != null)
                    instance = new URL(result.attributeValue("instance"));

                DataSeries ds = createDataSeries(testSpec, result.attributeValue("scenario"),
                        result.attributeValue("mode").equals("speed") ? Profiler.SPEED : Profiler.MEMORY,
                        instance);/*from   w w  w.j a v a 2  s. c  o m*/
                try {
                    ds.addDataPoint(date, new BigInteger(result.getTextTrim()));
                } catch (NumberFormatException e) {
                    ; // throw away this data point
                }
            }
        }
    }
}

From source file:br.gov.jfrj.siga.wf.tag.ProcessImageTag.java

License:Open Source License

/**
 * Extrai os limites da caixa para que seja desenhada a marcao  sua volta.
 * @param root/*from w ww  . ja v  a 2s . com*/
 * @return
 */
private int[] extractBoxConstraint(Element root) {
    int[] result = new int[4];
    String nodeName = currentToken.getNode().getName();
    XPath xPath = new DefaultXPath("//node[@name='" + nodeName + "']");
    Element node = (Element) xPath.selectSingleNode(root);
    result[0] = Integer.valueOf(node.attribute("x").getValue()).intValue();
    result[1] = Integer.valueOf(node.attribute("y").getValue()).intValue();
    result[2] = Integer.valueOf(node.attribute("width").getValue()).intValue();
    result[3] = Integer.valueOf(node.attribute("height").getValue()).intValue();
    return result;
}

From source file:br.gov.jfrj.siga.wf.tag.ProcessImageTag.java

License:Open Source License

/**
 * Extrai os limites da caixa para que seja desenhada a marcao  sua volta.
 * @param root/*from   w w w  .j  av  a 2s.c om*/
 * @param token
 * @return
 */
private int[] extractBoxConstraint(Element root, Token token) {

    int[] result = new int[4];
    String nodeName = "";
    try {
        nodeName = new String(token.getNode().getName().getBytes("ISO-8859-1"));
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    XPath xPath = new DefaultXPath("//node[@name='" + nodeName + "']");
    Element node = (Element) xPath.selectSingleNode(root);
    result[0] = Integer.valueOf(node.attribute("x").getValue()).intValue();
    result[1] = Integer.valueOf(node.attribute("y").getValue()).intValue();
    result[2] = Integer.valueOf(node.attribute("width").getValue()).intValue();
    result[3] = Integer.valueOf(node.attribute("height").getValue()).intValue();
    return result;
}

From source file:br.gov.jfrj.siga.wf.tag.ProcessImageTag.java

License:Open Source License

/**
 * Extrai as dimenses da imagem./*from  w ww.  j av a 2  s  .  co  m*/
 * @param root
 * @return
 */
private int[] extractImageDimension(Element root) {
    int[] result = new int[2];
    result[0] = Integer.valueOf(root.attribute("width").getValue()).intValue();
    result[1] = Integer.valueOf(root.attribute("height").getValue()).intValue();
    return result;
}