Example usage for org.dom4j Element attributeValue

List of usage examples for org.dom4j Element attributeValue

Introduction

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

Prototype

String attributeValue(QName qName);

Source Link

Document

This returns the attribute value for the attribute with the given fully qualified name or null if there is no such attribute or the empty string if the attribute value is empty.

Usage

From source file:InitializeDB.java

License:Open Source License

public static void setupDB(int year) {

    try {/*from   ww  w .  ja v  a2  s .  c  o  m*/

        //String filename = "nvdcve-2008.xml";

        Connection con = getConnection();

        Statement sql = con.createStatement();

        sql.execute("drop table if exists nvd"); //,primary key(id)

        sql.execute(
                "create table nvd(id varchar(20) not null,soft varchar(160) not null default 'ndefined',rng varchar(100) not null default 'undefined',lose_types varchar(100) not null default 'undefind',severity varchar(20) not null default 'unefined',access varchar(20) not null default 'unefined');");

        SAXReader saxReader = new SAXReader();

        for (int ct = 2002; ct <= year; ct++) {

            //String fname="/transient/mulval/oval/nvd/nvdcve-"+Integer.toString(ct)+".xml";
            String fname = "nvd_old/nvdcve-" + Integer.toString(ct) + ".xml";

            Document document = saxReader.read(fname);

            List entry = document.selectNodes("/*[local-name(.)='nvd']/*[local-name(.)='entry']");

            Iterator ent = entry.iterator();

            int act = 0;

            while (ent.hasNext()) { // varchar(20) not null default 'name',

                Element id = (Element) ent.next();

                String cveid = id.attributeValue("name");

                String cvss = "";

                String access = "";

                //   System.out.println(cveid + access);

                String sev = "";

                String host = "localhost";

                String sftw = "";

                String rge = "";

                String rge_tmp = "";

                String lose_tmp = "";

                String lose_types = "";

                ArrayList<String> subele = new ArrayList<String>();

                ArrayList<String> attr = new ArrayList<String>();

                Iterator ei = id.elementIterator();

                while (ei.hasNext()) { // put all of the subelements'

                    // names(subelement of entry) to the

                    // array list

                    Element sube = (Element) ei.next();

                    subele.add(sube.getName());

                }

                //System.out.println(id.getText());

                Iterator i = id.attributeIterator();

                while (i.hasNext()) { // put the attributes of the entries to

                    // the arraylist

                    Attribute att = (Attribute) i.next();

                    attr.add(att.getName());

                }

                if (subele.contains("vuln_soft")) {

                    Element vs = (Element) id.element("vuln_soft");

                    Iterator itr = vs.elementIterator("prod");

                    while (itr.hasNext()) { // record all of the softwares

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

                        //sftw = sftw + n.attributeValue("name") + ",";

                        sftw = n.attributeValue("name");

                        if (sftw.contains("'")) {

                            sftw = sftw.replace("'", "''");

                        }

                        break;

                    }

                    //int lsf = sftw.length();

                    //sftw = sftw.substring(0, lsf - 1);// delete the last comma

                }

                if (attr.contains("severity")) {

                    sev = id.attributeValue("severity");

                }

                if (attr.contains("CVSS_vector")) {

                    cvss = id.attributeValue("CVSS_vector");
                    char ac = cvss.charAt(9);
                    if (ac == 'L')
                        access = "l";
                    else if (ac == 'M')
                        access = "m";
                    else if (ac == 'H')
                        access = "h";
                    else
                        ;

                }

                if (subele.contains("range")) { // to get the range as a array

                    Element vs = (Element) id.element("range");

                    Iterator rgi = vs.elementIterator();

                    while (rgi.hasNext()) { // record all of the softwares

                        Element rg = (Element) rgi.next();

                        if (rg.getName().equals("user_init"))

                            rge_tmp = "user_action_req";

                        else if (rg.getName().equals("local_network"))

                            rge_tmp = "lan";

                        else if (rg.getName().equals("network"))

                            rge_tmp = "remoteExploit";

                        else if (rg.getName().equals("local"))

                            rge_tmp = "local";

                        else

                            rge_tmp = "other";

                        rge = rge + "''" + rge_tmp + "'',";

                    }

                    int lr = rge.length();

                    rge = rge.substring(0, lr - 1);// delete the last comma

                }

                if (subele.contains("loss_types")) {

                    Element lt = (Element) id.element("loss_types");

                    Iterator lti = lt.elementIterator();

                    while (lti.hasNext()) {

                        ArrayList<String> isecat = new ArrayList<String>();

                        Element ls = (Element) lti.next();

                        if (ls.getName().equals("avail"))

                            lose_tmp = "availability_loss";

                        else if (ls.getName().equals("conf"))

                            lose_tmp = "data_loss";

                        else if (ls.getName().equals("int"))

                            lose_tmp = "data_modification";

                        else

                            lose_tmp = "other";

                        lose_types = lose_types + "''" + lose_tmp + "'',";

                    }

                    int ltp = lose_types.length();

                    lose_types = lose_types.substring(0, ltp - 1);// delete the

                    // last

                    // comma

                }

                //System.out.println(cveid + lose_types + rge + sftw + sev + access);

                String insert = "insert nvd values('" + cveid + "','"

                        + sftw + "','" + rge + "','" + lose_types + "','" + sev

                        + "','" + access + "')";

                sql.execute(insert);

            }

        }

        sql.close();

        con.close();

    } catch (java.lang.ClassNotFoundException e) {

        System.err.println("ClassNotFoundException:" + e.getMessage());

    } catch (SQLException ex) {

        System.err.println("SQLException:" + ex.getMessage());

    } catch (DocumentException e) {

        e.printStackTrace();

    } catch (IOException e) {

        // TODO Auto-generated catch block

        e.printStackTrace();

    }

}

From source file:GetCVEID.java

License:Open Source License

@SuppressWarnings("unchecked")
public static void getCVEs(String filename) {

    Hashtable ovalIDs = makehashTable(filename);

    String hname = getHostname(filename);

    try {/* ww  w.j  a v a 2 s  . c om*/

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

        fr.write(hname + "\n");

        SAXReader saxReader = new SAXReader();

        Document document = saxReader.read(new File(filename));

        Element definitions = (Element) document.selectSingleNode(
                "/*[local-name(.)='oval_results']/*[local-name(.)='oval_definitions']/*[local-name(.)='definitions']");

        List definition = document.selectNodes(
                "/*[local-name(.)='oval_results']/*[local-name(.)='oval_definitions']/*[local-name(.)='definitions']/*[local-name(.)='definition']");

        Iterator def = definition.iterator();

        while (def.hasNext()) {

            Element deft = (Element) def.next();

            //skip if the element is inventory

            String type = deft.attributeValue("class");

            String id = deft.attributeValue("id");

            if (type.contains("inventory"))

                continue;

            if (ovalIDs.containsKey(id)) {

                String cve = deft.element("metadata").element("reference").attributeValue("ref_id");

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

            }
        }

        fr.close();

    } catch (Exception e) {

        e.printStackTrace();
    }

}

From source file:android.apn.androidpn.server.xmpp.net.StanzaHandler.java

License:Open Source License

private void processMessage(Element doc) {
    log.debug("processMessage()...");
    Message packet;//w  ww.  j a  va  2  s  .  c o m
    try {
        packet = new Message(doc, false);
    } catch (IllegalArgumentException e) {
        log.debug("Rejecting packet. JID malformed", e);
        Message reply = new Message();
        reply.setID(doc.attributeValue("id"));
        reply.setTo(session.getAddress());
        reply.getElement().addAttribute("from", doc.attributeValue("to"));
        reply.setError(PacketError.Condition.jid_malformed);
        session.process(reply);
        return;
    }

    packet.setFrom(session.getAddress());
    router.route(packet);
    session.incrementClientPacketCount();
}

From source file:android.apn.androidpn.server.xmpp.net.StanzaHandler.java

License:Open Source License

private void processPresence(Element doc) {
    log.debug("processPresence()...");
    Presence packet;/*  w  ww  . j  a  v a 2s .  c  o m*/
    try {
        packet = new Presence(doc, false);
    } catch (IllegalArgumentException e) {
        log.debug("Rejecting packet. JID malformed", e);
        Presence reply = new Presence();
        reply.setID(doc.attributeValue("id"));
        reply.setTo(session.getAddress());
        reply.getElement().addAttribute("from", doc.attributeValue("to"));
        reply.setError(PacketError.Condition.jid_malformed);
        session.process(reply);
        return;
    }
    if (session.getStatus() == Session.STATUS_CLOSED && packet.isAvailable()) {
        log.warn("Ignoring available presence packet of closed session: " + packet);
        return;
    }

    packet.setFrom(session.getAddress());
    router.route(packet);
    session.incrementClientPacketCount();
}

From source file:android.apn.androidpn.server.xmpp.net.StanzaHandler.java

License:Open Source License

private void processIQ(Element doc) {
    log.debug("processIQ()...");
    IQ packet;/* w w w .j  a v  a2  s .com*/
    try {
        packet = getIQ(doc);
    } catch (IllegalArgumentException e) {
        log.debug("Rejecting packet. JID malformed", e);
        IQ reply = new IQ();
        if (!doc.elements().isEmpty()) {
            reply.setChildElement(((Element) doc.elements().get(0)).createCopy());
        }
        reply.setID(doc.attributeValue("id"));
        reply.setTo(session.getAddress());
        String to = doc.attributeValue("to");
        if (to != null) {
            reply.getElement().addAttribute("from", to);
        }
        reply.setError(PacketError.Condition.jid_malformed);
        session.process(reply);
        return;
    }

    //        if (packet.getID() == null) {
    //            // IQ packets MUST have an 'id' attribute
    //            StreamError error = new StreamError(
    //                    StreamError.Condition.invalid_xml);
    //            session.deliverRawText(error.toXML());
    //            session.close();
    //            return;
    //        }

    packet.setFrom(session.getAddress());
    router.route(packet);
    session.incrementClientPacketCount();
}

From source file:architecture.common.license.License.java

License:Apache License

public static License fromXML(String xml) {
    try {//from  w w w  .  j  a  v  a 2 s  .  c  o  m
        Document d = DocumentHelper.parseText(xml);
        Element root = d.getRootElement();
        License l = new License();
        String id = root.attributeValue("id");
        if (id == null)
            throw new LicenseException(L10NUtils.format("002105"));
        l.setID(Long.parseLong(id));
        String name0 = root.attributeValue("name");
        if (name0 == null)
            throw new LicenseException(L10NUtils.format("002106"));
        l.setName(name0);
        String edition = root.attributeValue("edition");
        if (edition != null)
            l.setEdition(edition);
        String dateString = root.attributeValue("creationDate");
        if (dateString == null)
            throw new LicenseException(L10NUtils.format("002107"));
        try {
            Date date = parseDate(dateString);
            l.setCreationDate(date);
        } catch (Exception e) {
            throw new LicenseException(L10NUtils.format("002108"));
        }
        String license = root.attributeValue("version");
        if (license == null)
            throw new LicenseException(L10NUtils.format("002109"));
        l.setVersion(Version.parseVersion(license));
        try {
            l.setType(Type.valueOf(root.attributeValue("type")));
        } catch (IllegalArgumentException e) {
            throw new LicenseException(L10NUtils.format("002110"));
        }
        Element clientElement = root.element("client");
        Client client = new Client();
        client.setName(clientElement.attributeValue("name"));
        client.setCompany(clientElement.attributeValue("company"));
        l.setClient(client);

        for (Element e : (List<Element>) root.elements("module")) {
            Module m = new Module();
            m.setName(e.attributeValue("name"));
            l.getModules().add(m);
        }

        Map<String, String> properties = new HashMap<String, String>();
        for (Element e : (List<Element>) root.elements("property")) {
            String name = e.attributeValue("name");
            String value = e.getTextTrim();
            properties.put(name, value);
        }

        l.setProperties(properties);
        Element sig = root.element("signature");
        l.setSignature(sig.getTextTrim());
        return l;
    } catch (DocumentException e) {
        log.fatal(e.getMessage(), e);
        throw new LicenseException(L10NUtils.format("002111"), e);
    }
}

From source file:architecture.common.lifecycle.internal.XmlApplicationPropertiesOld.java

License:Apache License

public String getAttribute(String name, String attribute) {
    if (name == null || attribute == null)
        return null;
    String propName[] = parsePropertyName(name);
    Element element = doc.getRootElement();
    int i = 0;//w w  w.  j a va 2 s .c  om
    do {
        if (i >= propName.length)
            break;
        String child = propName[i];
        element = element.element(child);
        if (element == null)
            break;
        i++;
    } while (true);
    if (element != null)
        return element.attributeValue(attribute);
    else
        return null;
}

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

License:Apache License

/**
 * Returns the value of the attribute of the given property name or
 * <tt>null</tt> if it doesn't exist. Note, this
 *
 * @param name// w  ww .  j a  va2  s  . c  o m
 *            the property name to lookup - ie, "foo.bar"
 * @param attribute
 *            the name of the attribute, ie "id"
 * @return the value of the attribute of the given property or <tt>null</tt>
 *         if it doesn't exist.
 */
public String getAttribute(String name, String attribute) {
    if (name == null || attribute == null) {
        return null;
    }
    String[] propName = parsePropertyName(name);
    // Search for this property by traversing down the XML heirarchy.
    Element element = document.getRootElement();
    for (String child : propName) {
        element = element.element(child);
        if (element == null) {
            // This node doesn't match this part of the property name which
            // indicates this property doesn't exist so return empty array.
            break;
        }
    }
    if (element != null) {
        // Get its attribute values
        return element.attributeValue(attribute);
    }
    return null;
}

From source file:au.gov.ansto.bragg.cicada.core.internal.Algorithm_.java

License:Open Source License

public Document loadAlgorithmTitle(File algorithmFile) throws LoadAlgorithmFileFailedException {
    this.filename = algorithmFile.getPath();
    Document file = null;/*from   w ww  .j  ava2s.c o  m*/
    try {
        file = Parse.readFile(algorithmFile);
    } catch (DocumentException e) {
        throw new LoadAlgorithmFileFailedException("failed to load the algorithm from configuration file "
                + algorithmFile.getName() + ": " + e.getMessage(), e);
    }
    Element rootElement = file.getRootElement();
    classID = rootElement.attributeValue("id");
    try {
        setName(rootElement.attributeValue("name"));
    } catch (IllegalNameSetException e) {
        throw new LoadAlgorithmFileFailedException(e.getMessage() + ": illegal algorithm name");
    }
    version = rootElement.attributeValue("version");
    helpURL = rootElement.attributeValue("help_url");
    shortDescription = rootElement.attributeValue("short_description");
    icon = rootElement.attributeValue("icon");
    try {
        algorithmType = AlgorithmType.valueOf(rootElement.attributeValue("type"));
    } catch (Exception e) {
    }
    String hiddenValue = rootElement.attributeValue("hidden");
    if (hiddenValue != null)
        hidden = Boolean.valueOf(hiddenValue);
    if (classID == null)
        throw new LoadAlgorithmFileFailedException("classID not found in receipe file");
    //      if (icon == null) 
    //         throw new LoadAlgorithmFileFailedException("icon path not found in receipe file");
    hasInPort = checkSourcePortExistence(rootElement);
    return file;
}

From source file:au.gov.ansto.bragg.process.parse.Parse.java

License:Open Source License

public static List<ConfigurationItem> parseConfiguration(File filename) throws DocumentException {
    List<ConfigurationItem> propertyList = new LinkedList<ConfigurationItem>();
    Document document = readFile(filename);
    Element rootElement = document.getRootElement();
    //      List<?> list = rootElement.selectNodes("//extension");
    //      System.out.println(list.toString());
    for (Iterator<?> iter = rootElement.elementIterator("extension"); iter.hasNext();) {
        Element item = (Element) iter.next();
        if (item.getName().equals("extension")
                && item.attributeValue("point").matches("au.gov.ansto.bragg.cicada.configuration")) {
            ConfigurationItem configuration = new ConfigurationItem(Integer.valueOf(getAttribute(item, "id")),
                    getAttribute(item, "name"), getAttribute(item, "version"), getAttribute(item, "class"),
                    getAttribute(item, "default"));
            propertyList.add(configuration);
        }/*from w w  w  .  j  a  v a 2s  .c om*/
    }
    return propertyList;
}