Example usage for org.dom4j Element getText

List of usage examples for org.dom4j Element getText

Introduction

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

Prototype

String getText();

Source Link

Document

Returns the text value of this element without recursing through child elements.

Usage

From source file:NessusXMLParser.java

License:Open Source License

public static void parseNessus(String nessusReport) {

    try {/*  w  w w.j  a  v  a 2s. co  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:GetCVEID.java

License:Open Source License

public static String getHostname(String filename) {

    String hname = "";
    try {/*from  w w  w.  j  a va 2 s.  com*/

        SAXReader saxReader = new SAXReader();

        Document document = saxReader.read(filename);

        Element hostname = (Element) document.selectSingleNode(
                "/*[local-name(.)='oval_results']/*[local-name(.)='results']/*[local-name(.)='system']/*[local-name(.)='oval_system_characteristics']/*[local-name(.)='system_info']/*[local-name(.)='primary_host_name']");

        String hname1 = hostname.getText();

        //   System.out.println(hname1);

        int in = hname1.indexOf('.'); //only keep the string before the first dot

        //if no dot, then ignore it
        if (in == -1)
            hname = hname1;
        //else take the machine domain name 
        else
            hname = hname1.substring(0, in);

        System.out.println("host name is: " + hname);
    }

    catch (Exception e) {

        e.printStackTrace();
    }

    return hname;

}

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 . jav a2s  . 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:StreamFlusher.java

License:Apache License

public Object visit(ASTtestTokensXMLFile_statement node, Object data) {
    // Total: 11 regexp arguments, syntactically constrained
    // /*from w  ww  . j  a  v  a 2 s  .c om*/
    // 0.  the Fst to test

    node.jjtGetChild(0).jjtAccept(this, data);
    Fst testFst = (Fst) (stack.pop());

    // 1.  path of the input file

    node.jjtGetChild(1).jjtAccept(this, data);
    Fst tempFst = (Fst) (stack.pop());

    String inputFilePath = lib.GetSingleString(tempFst,
            "Second arg to testTokensXMLFile must denote a language of exactly one string.");

    if (inputFilePath.length() == 0) {
        throw new KleeneArgException(
                "Second arg to testTokensXMLFile must denote exactly one non-empty string");
    }

    // 2. argument supplying the name of the element holding
    //      the input strings, by default, "input", i.e.
    //      <input>...</input>
    // N.B. in testTokensTextFile, this argument specifies the
    // encoding of the input file, which is not needed for XML,
    // which either has an explicit "encoding" specification, or
    // is UTF-8 by default

    node.jjtGetChild(2).jjtAccept(this, data);
    tempFst = (Fst) (stack.pop());

    String srcInputElmtName = lib.GetSingleString(tempFst,
            "Third arg to testTokensXMLFile must denote a language of exactly one string.");

    if (srcInputElmtName.length() == 0) {
        throw new KleeneArgException("Third arg to testTokensXMLFile must denote one non-empty string");
    }

    // 3.  path of the output file

    node.jjtGetChild(3).jjtAccept(this, data);
    tempFst = (Fst) (stack.pop());

    String outputFilePath = lib.GetSingleString(tempFst,
            "Fourth arg to testTokensXMLFile must denote a language of exactly one string.");

    if (outputFilePath.length() == 0) {
        throw new KleeneArgException("Fourth arg to testTokensXMLFile must denote one non-empty string");
    }

    // 4.  encoding of the output file

    node.jjtGetChild(4).jjtAccept(this, data);
    tempFst = (Fst) (stack.pop());

    String outputFileEncoding = lib.GetSingleString(tempFst,
            "Fifth arg to testTokensXMLFile must denote a language of exactly one string.");

    if (outputFileEncoding.length() == 0) {
        throw new KleeneArgException("Fifth arg to testTokensXMLFile must denote one non-empty string");
    }

    //          And for the XML output

    // 5.  name of the root element

    node.jjtGetChild(5).jjtAccept(this, data);
    tempFst = (Fst) (stack.pop());

    String rootElmtName = lib.GetSingleString(tempFst,
            "Sixth arg to testTokensXMLFile must denote a language of exactly one string.");

    if (rootElmtName.length() == 0) {
        throw new KleeneArgException("Sixth arg to testTokensXMLFile must denote one non-empty string");
    }

    // 6.  name of the token element

    node.jjtGetChild(6).jjtAccept(this, data);
    tempFst = (Fst) (stack.pop());

    String tokenElmtName = lib.GetSingleString(tempFst,
            "Seventh arg to testTokensXMLFile must denote a language of exactly one string.");

    if (tokenElmtName.length() == 0) {
        throw new KleeneArgException("Seventh arg to testTokensXMLFile must denote one non-empty string");
    }

    // 7.  name of the input element

    node.jjtGetChild(7).jjtAccept(this, data);
    tempFst = (Fst) (stack.pop());

    String inputElmtName = lib.GetSingleString(tempFst,
            "Eighth arg to testTokensXMLFile must denote a language of exactly one string.");

    if (inputElmtName.length() == 0) {
        throw new KleeneArgException("Eighth arg to testTokensXMLFile must denote one non-empty string");
    }

    // 8.  name of the outputs element (N.B. plural)

    node.jjtGetChild(8).jjtAccept(this, data);
    tempFst = (Fst) (stack.pop());

    String outputsElmtName = lib.GetSingleString(tempFst,
            "Ninth arg to testTokensXMLFile must denote a language of exactly one string.");

    if (outputsElmtName.length() == 0) {
        throw new KleeneArgException("Ninth arg to testTokensXMLFile must denote one non-empty string");
    }

    // 9.  name of the output element  (N.B. singular)

    node.jjtGetChild(9).jjtAccept(this, data);
    tempFst = (Fst) (stack.pop());

    String outputElmtName = lib.GetSingleString(tempFst,
            "Tenth arg to testTokensXMLFile must denote a language of exactly one string.");

    if (outputElmtName.length() == 0) {
        throw new KleeneArgException("Tenth arg to testTokensXMLFile must denote one non-empty string");
    }

    // 10.  name of the weight attr in the output elmt

    node.jjtGetChild(10).jjtAccept(this, data);
    tempFst = (Fst) (stack.pop());

    String weightAttrName = lib.GetSingleString(tempFst,
            "Eleventh arg to testTokensXMLFile must denote a language of exactly one string.");

    if (weightAttrName.length() == 0) {
        throw new KleeneArgException("Eleventh arg to testTokensXMLFile must denote one non-empty string");
    }

    String fullpath = getFullpath(inputFilePath);

    TranslitTokenizerBuilder ttb = new TranslitTokenizerBuilder(symmap, testFst.getSigma(), lib);
    lib.Iterate4mcs(testFst, ttb, symmap.getStartPuaCpv());
    Transliterator trInput = ttb.getTranslitTokenizer(true); // true for input side

    try {
        // try to read/parse the XML input file

        Document doc = null;

        doc = parseXML(fullpath); // dom4j

        // Read all the <input></input> elements into a list
        // N.B. by default, the name of the element is "input",
        // but in general it is specified in arg srcInputElmtName
        List list = doc.selectNodes("//" + srcInputElmtName);

        // now try to open the output file 

        fullpath = getFullpath(outputFilePath);

        BufferedWriter out = null;
        if (outputFileEncoding.equals("default") || outputFileEncoding.equals("-")) {
            // get the current default encoding of the operating system
            outputFileEncoding = System.getProperty("file.encoding");
        }
        out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fullpath), outputFileEncoding));

        out.write("<?xml version=\"1.0\" encoding=\"" + outputFileEncoding + "\"?>");
        out.newLine();
        out.write("<" + rootElmtName + ">");
        out.newLine();

        XMLOutputLister xmlOutputLister = new XMLOutputLister(symmap, out, outputElmtName, weightAttrName);

        // Loop through the <input></input> elements, extracting and
        //   running the text string from each one; write output to
        //   the output file

        String token;

        Fst modifiedTestFst;

        for (Iterator it = list.iterator(); it.hasNext();) {
            Element inputElmt = (Element) it.next();
            token = inputElmt.getText();

            String cpvstr = trInput.transliterate(token);
            // converts cpvstr to a sequence of code pt values, and
            // each one could fill one or two 16-bit code units;
            // this is where multichar symbols are reduced to their
            // code point values

            // get length in Unicode characters (not code units)
            int inputlen = cpvstr.codePointCount(0, cpvstr.length());
            // allocate an int array to hold those code-point values,
            //    one int per code point value
            int[] cpvArray = new int[inputlen];

            // UCharacterIterator knows how to iterate over a 
            //   String and
            // return the Unicode-Character code point values
            UCharacterIterator iter = UCharacterIterator.getInstance(cpvstr);

            // we need to build each input string into a one-path Fst

            // store the codepoints in the int array 
            //      (which will be passed to
            //    oneStringNativeFst(), a native method
            int codepoint;
            int index = 0;
            while ((codepoint = iter.nextCodePoint()) != UCharacterIterator.DONE) {
                // any multichar symbols will already be in the
                // symmap, or they wouldn't have been identified;
                // but BMP characters may not yet be in the symmap
                if (Character.charCount(codepoint) == 1) {
                    symmap.putsym(String.valueOf((char) codepoint));
                }
                cpvArray[index++] = codepoint;
            }

            // 0 arg for generation, apply the inputFst to the "input"
            // side of testFst
            Fst compFst = lib.ApplyToOneString(testFst, cpvArray, 0);

            // prepare to list the output strings (and their weights)
            long stringCount = lib.NumPaths(compFst);

            // XML output for this input token

            out.write("  <" + tokenElmtName + ">");
            out.newLine();

            // be careful to escape XML special chars in line; 
            // N.B. escapeXml also escapes non-ASCII Unicode letters
            //out.write("    <" + inputElmtName + ">" + 
            //          StringEscapeUtils.escapeXml(token) + 
            //          "</" + inputElmtName + ">") ;

            out.write("    <" + inputElmtName + ">" + EscapeXML.escapeXML(token) + "</" + inputElmtName + ">");
            out.newLine();

            out.write("    <" + outputsElmtName + ">");
            out.newLine();

            if (stringCount == 0) {
                // output nothing
            } else if (stringCount == -1) {
                // means that the compFstPtr has loops, 
                //      denotes an infinite language
                out.write("      <infinite/>");
                out.newLine();
            } else {
                // native function listAllStrings will find all 
                //      strings in the Fst
                // and make callbacks to xmlOutputLister, 
                //      which knows how to output
                // them as XML elements
                lib.ListAllStrings(compFst, 1, xmlOutputLister);
            }

            out.write("    </" + outputsElmtName + ">");
            out.newLine();

            out.write("  </" + tokenElmtName + ">");
            out.newLine();
        }

        out.write("</" + rootElmtName + ">");
        out.newLine();
        out.flush();
        out.close();

    } catch (Exception e) {
        // KRB:  review this
        System.out.println("Exception found while testing input from file.");
        e.printStackTrace();
    }
    return data;
}

From source file:SolrUpdate.java

License:Apache License

public void processUrl() throws Exception {

    String jv, jn, ji, jd, jm, jy, jsp, authorfull, doi, epday, epmonth, epyear, epubsum, epubsum2 = "";
    jv = jn = ji = jd = jm = jy = jsp = authorfull = doi = epday = epmonth = epyear = epubsum = epubsum2 = "";

    SAXReader reader = new SAXReader();
    SAXReader reader2 = new SAXReader();
    Document document = null;/* ww  w  .  j ava2 s  . c om*/

    String mytitle, myabstract, myyear, myfullname = "";
    Element journalname, journalyear, journalmonth, journalday, journalvolume, journalissue, journalpagestart,
            epubday, epubmonth, epubyear, pubdoi;
    int mypmid;

    List<String> mylauthors = new ArrayList<String>();
    List<String> myfauthors = new ArrayList<String>();
    List<String> myfnames = new ArrayList<String>();

    //PubMed

    String pubmedlist = "";
    Iterator iditer = publications.iterator();

    while (iditer.hasNext()) {
        int currpmid = ((Publication) iditer.next()).getPmid();
        if (pubmedlist.length() < 1) {
            pubmedlist += currpmid;

        } else {
            pubmedlist += "," + currpmid;
        }
    }

    String url = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&id=" + pubmedlist
            + "&retmax=200&retmode=xml&rettype=abstract";
    Document pubdoc = reader2.read(url);

    @SuppressWarnings("unchecked")
    List<Node> thelist = pubdoc.selectNodes("//PubmedArticle| //PubmedBookArticle");

    Element abstractnode, titlenode, yearsnode, pmidnode;
    @SuppressWarnings("rawtypes")
    List firstnamenode;
    @SuppressWarnings("rawtypes")
    List lastnamenode;

    for (Node currnode : thelist) {
        mylauthors = new ArrayList<String>();
        myfauthors = new ArrayList<String>();
        myfnames = new ArrayList<String>();
        epubsum = epubsum2 = authorfull = "";

        titlenode = (Element) currnode.selectSingleNode(".//ArticleTitle | .//BookTitle");
        yearsnode = (Element) currnode
                .selectSingleNode(".//PubDate/Year | .//DateCompleted/Year | .//DateCreated/Year");
        journalname = (Element) currnode.selectSingleNode(".//Journal/Title");
        journalyear = (Element) currnode.selectSingleNode(".//PubDate/Year");
        journalmonth = (Element) currnode.selectSingleNode(".//PubDate/Month");

        journalday = (Element) currnode.selectSingleNode(".//PubDate/Day");
        journalvolume = (Element) currnode.selectSingleNode(".//JournalIssue/Volume");
        journalissue = (Element) currnode.selectSingleNode(".//JournalIssue/Issue");
        journalpagestart = (Element) currnode.selectSingleNode(".//Pagination/MedlinePgn");

        epubday = (Element) currnode.selectSingleNode(
                ".//PubMedPubDate[@PubStatus='aheadofprint']/Day  | .//PubMedPubDate[@PubStatus='epublish']/Day ");
        epubmonth = (Element) currnode.selectSingleNode(
                ".//PubMedPubDate[@PubStatus='aheadofprint']/Month | .//PubMedPubDate[@PubStatus='epublish']/Month");
        epubyear = (Element) currnode.selectSingleNode(
                ".//PubMedPubDate[@PubStatus='aheadofprint']/Year | .//PubMedPubDate[@PubStatus='epublish']/Year");

        pubdoi = (Element) currnode.selectSingleNode(".//ArticleId[@IdType='doi']");

        firstnamenode = currnode.selectNodes(".//ForeName");
        lastnamenode = currnode.selectNodes(".//LastName");
        abstractnode = (Element) currnode.selectSingleNode(".//Abstract/AbstractText[1]");
        pmidnode = (Element) currnode.selectSingleNode(".//PMID");

        myfnames = new ArrayList<String>();
        @SuppressWarnings("rawtypes")
        Iterator fiter = firstnamenode.iterator();
        @SuppressWarnings("rawtypes")
        Iterator liter = lastnamenode.iterator();

        if (journalname != null) {
            jn = journalname.getText();
        }
        if (journalvolume != null) {
            jv = journalvolume.getText();
        }
        if (journalissue != null) {
            ji = journalissue.getText();
        }
        if (journalmonth != null) {
            jm = journalmonth.getText();
        }
        if (journalyear != null) {
            jy = journalyear.getText();
        }
        if (journalpagestart != null) {
            jsp = journalpagestart.getText();
        }
        if (journalday != null) {
            jd = journalday.getText();
        }
        if (epubday != null) {
            epday = epubday.getText();
        }
        if (epubmonth != null) {
            epmonth = epubmonth.getText();
        }
        if (epubyear != null) {
            epyear = epubyear.getText();
        }
        if (pubdoi != null) {
            doi = "doi: " + pubdoi.getText();
        }
        if (jv.length() > 0) {
            epubsum2 += jv;
        }

        if (ji.length() > 0) {
            epubsum2 += "(" + ji + ")" + ":";
        }

        if (jsp.length() > 0) {
            epubsum2 += jsp + ".";
        }

        if (epmonth.length() < 1 && epyear.length() < 1 && epday.length() < 1) {
            epubsum = "[Epub ahead of print]";
        } else if (epyear.length() > 0) {
            epubsum = "Epub " + epyear + " " + epmonth + " " + epday;
        } else {
            epubsum = "";
        }

        mytitle = titlenode.getText();
        myyear = yearsnode.getText();
        mypmid = Integer.valueOf(pmidnode.getText());

        while (fiter.hasNext()) {
            Element fname = (Element) fiter.next();
            Element lname = (Element) liter.next();

            myfauthors.add(fname.getText());
            mylauthors.add(lname.getText());

            myfullname = fname.getText() + " " + lname.getText();
            myfnames.add(myfullname);

            if (fiter.hasNext()) {
                authorfull = authorfull + myfullname + ", ";
            } else {
                authorfull = authorfull + myfullname;
            }

        }

        if (abstractnode != null) {
            myabstract = abstractnode.getText();
        } else {
            myabstract = "NO ABSTRACT FOUND.";
        }

        publications.add(new Publication(mytitle, myabstract, myyear, myfauthors, mylauthors, myfnames, jv, jn,
                jy, jm, jd, jsp, ji, epday, epmonth, epyear, doi, epubsum, epubsum2, authorfull, mypmid));

    }

}

From source file:Addons.CepWebService.java

private static void criarEndereco(Endereco endereco) {
    try {//from w  w  w .  j a va 2 s.c  o  m
        URL url = new URL(
                "http://cep.republicavirtual.com.br/web_cep.php?cep=" + endereco.getCep() + "&formato=xml");

        Document document = getDocumento(url);

        Element root = document.getRootElement();

        for (Iterator i = root.elementIterator(); i.hasNext();) {
            Element element = (Element) i.next();

            if (element.getQualifiedName().equals("uf"))
                endereco.setUf(element.getText());

            if (element.getQualifiedName().equals("cidade"))
                endereco.setCidade(element.getText());

            if (element.getQualifiedName().equals("bairro"))
                endereco.setBairro(element.getText());

            if (element.getQualifiedName().equals("tipo_logradouro"))
                endereco.setTipo_logradouro(element.getText());

            if (element.getQualifiedName().equals("logradouro"))
                endereco.setLogradouro(element.getText());

            if (element.getQualifiedName().equals("resultado"))
                endereco.setResultado(Integer.parseInt(element.getText()));

            if (element.getQualifiedName().equals("resultado_txt"))
                endereco.setResultado_txt(element.getText());
        }

        endereco.setError(false);
    } catch (MalformedURLException | DocumentException | NumberFormatException ex) {
        endereco.setError(true);
        endereco.setMessage(ex.getMessage());
    }
}

From source file:adr.main.AlcorAdrSettings.java

/**
 * ?  ?  .xml /*from   w  ww .  j av a  2 s  .com*/
 * @return 
 * true  -   ?
 * false -   ? 
 */
public boolean LoadSettings() {
    boolean bResOk = true;
    try {
        SAXReader reader = new SAXReader();

        String strSettingsFilePathName = "alcor.adr.settings.xml";//System.getenv( "AMS_ROOT") + "/etc/settings.ams.xml";
        URL url = (new java.io.File(strSettingsFilePathName)).toURI().toURL();

        Document document = reader.read(url);

        Element root = document.getRootElement();

        // iterate through child elements of root
        for (Iterator i = root.elementIterator(); i.hasNext();) {
            Element element = (Element) i.next();
            String name = element.getName();
            String value = element.getText();

            //logger.debug( "Pairs: [" + name + " : " + value + "]");

            if ("COM_Port".equals(name))
                m_pCOMPortSettings.SetPort(value);

            if ("COM_Baudrate".equals(name))
                m_pCOMPortSettings.SetBaudRate(Integer.parseInt(value));

            if ("COM_DataBits".equals(name)) {
                switch (value) {
                case "5":
                    m_pCOMPortSettings.SetDataBits(SerialPort.DATABITS_5);
                    break;
                case "6":
                    m_pCOMPortSettings.SetDataBits(SerialPort.DATABITS_6);
                    break;
                case "7":
                    m_pCOMPortSettings.SetDataBits(SerialPort.DATABITS_7);
                    break;
                case "8":
                    m_pCOMPortSettings.SetDataBits(SerialPort.DATABITS_8);
                    break;
                default:
                    logger.warn("Unknown COM_DataBits value '" + value + "' in settings.xml! Using default!");
                    bResOk = false;
                    break;
                }
            }

            if ("COM_Parity".equals(name)) {
                switch (value) {
                case "None":
                    m_pCOMPortSettings.SetParity(SerialPort.PARITY_NONE);
                    break;
                case "Odd":
                    m_pCOMPortSettings.SetParity(SerialPort.PARITY_ODD);
                    break;
                case "Even":
                    m_pCOMPortSettings.SetParity(SerialPort.PARITY_EVEN);
                    break;
                case "Mark":
                    m_pCOMPortSettings.SetParity(SerialPort.PARITY_MARK);
                    break;
                case "Space":
                    m_pCOMPortSettings.SetParity(SerialPort.PARITY_SPACE);
                    break;
                default:
                    logger.warn("Unknown COM_Parity value '" + value + "' in settings.xml! Using default!");
                    bResOk = false;
                    break;
                }
            }

            if ("COM_StopBits".equals(name)) {
                switch (value) {
                case "1":
                    m_pCOMPortSettings.SetStopBits(SerialPort.STOPBITS_1);
                    break;
                case "2":
                    m_pCOMPortSettings.SetParity(SerialPort.STOPBITS_2);
                    break;
                default:
                    logger.warn("Unknown COM_StopBits value '" + value + "' in settings.xml! Using default!");
                    bResOk = false;
                    break;
                }
            }
        }

    } catch (MalformedURLException ex) {
        logger.error("MalformedURLException caught while loading settings!", ex);
        bResOk = false;
    } catch (DocumentException ex) {
        logger.error("DocumentException caught while loading settings!", ex);
        bResOk = false;
    }

    return bResOk;
}

From source file:ams.AMSDevSerialNumbers.java

/**
 * Loads tested laser devices numbers from XML<br>
 * So user don't need to enter them one more time
 *//*from  w w  w .  j  a va  2 s .  c om*/
private void LoadDevNumsFromXML() {
    try {
        SAXReader reader = new SAXReader();

        String strSerialsFileName = System.getenv("AMS_ROOT") + "/serials.xml";
        URL url = (new java.io.File(strSerialsFileName)).toURI().toURL();

        Document document = reader.read(url);

        Element root = document.getRootElement();

        // iterate through child elements of root
        for (Iterator i = root.elementIterator(); i.hasNext();) {
            Element element = (Element) i.next();
            String name = element.getName();
            String value = element.getText();

            logger.debug("Pairs: [" + name + " : " + value + "]");

            switch (name) {
            case "Device1":
                m_strDev1SerialNumber = value;
                break;
            case "Device2":
                m_strDev2SerialNumber = value;
                break;
            case "Device3":
                m_strDev3SerialNumber = value;
                break;
            case "Device4":
                m_strDev4SerialNumber = value;
                break;
            case "Device5":
                m_strDev5SerialNumber = value;
                break;
            case "Device6":
                m_strDev6SerialNumber = value;
                break;
            case "Device7":
                m_strDev7SerialNumber = value;
                break;
            case "Device8":
                m_strDev8SerialNumber = value;
                break;
            default:
            }
        }
    } catch (MalformedURLException ex) {
        logger.error("MalformedURLException caught while loading serials!", ex);
    } catch (DocumentException ex) {
        logger.error("DocumentException caught while loading serials!", ex);
    }

}

From source file:ams.AMSSettings.java

/**
 * ?  ?  .xml //from   w w w.  j  ava2  s. c o m
 * @return 
 * true  -   ?
 * false -   ? 
 */
public boolean LoadSettings() {
    boolean bResOk = true;
    try {
        SAXReader reader = new SAXReader();

        String strSettingsFilePathName = System.getenv("AMS_ROOT") + "/settings.xml";
        URL url = (new java.io.File(strSettingsFilePathName)).toURI().toURL();

        Document document = reader.read(url);

        Element root = document.getRootElement();

        // iterate through child elements of root
        for (Iterator i = root.elementIterator(); i.hasNext();) {
            Element element = (Element) i.next();
            String name = element.getName();
            String value = element.getText();

            //logger.debug( "Pairs: [" + name + " : " + value + "]");

            if ("COM_Port".equals(name))
                m_pCOMPortSettings.SetPort(value);

            if ("COM_Baudrate".equals(name))
                m_pCOMPortSettings.SetBaudRate(Integer.parseInt(value));

            if ("COM_DataBits".equals(name)) {
                switch (value) {
                case "5":
                    m_pCOMPortSettings.SetDataBits(SerialPort.DATABITS_5);
                    break;
                case "6":
                    m_pCOMPortSettings.SetDataBits(SerialPort.DATABITS_6);
                    break;
                case "7":
                    m_pCOMPortSettings.SetDataBits(SerialPort.DATABITS_7);
                    break;
                case "8":
                    m_pCOMPortSettings.SetDataBits(SerialPort.DATABITS_8);
                    break;
                default:
                    logger.warn("Unknown COM_DataBits value '" + value + "' in settings.xml! Using default!");
                    bResOk = false;
                    break;
                }
            }

            if ("COM_Parity".equals(name)) {
                switch (value) {
                case "None":
                    m_pCOMPortSettings.SetParity(SerialPort.PARITY_NONE);
                    break;
                case "Odd":
                    m_pCOMPortSettings.SetParity(SerialPort.PARITY_ODD);
                    break;
                case "Even":
                    m_pCOMPortSettings.SetParity(SerialPort.PARITY_EVEN);
                    break;
                case "Mark":
                    m_pCOMPortSettings.SetParity(SerialPort.PARITY_MARK);
                    break;
                case "Space":
                    m_pCOMPortSettings.SetParity(SerialPort.PARITY_SPACE);
                    break;
                default:
                    logger.warn("Unknown COM_Parity value '" + value + "' in settings.xml! Using default!");
                    bResOk = false;
                    break;
                }
            }

            if ("COM_StopBits".equals(name)) {
                switch (value) {
                case "1":
                    m_pCOMPortSettings.SetStopBits(SerialPort.STOPBITS_1);
                    break;
                case "2":
                    m_pCOMPortSettings.SetParity(SerialPort.STOPBITS_2);
                    break;
                default:
                    logger.warn("Unknown COM_StopBits value '" + value + "' in settings.xml! Using default!");
                    bResOk = false;
                    break;
                }
            }

            if ("Devices".equals(name)) {
                for (Iterator andevsparams = element.elementIterator(); andevsparams.hasNext();) {

                    Element elementAnDev = (Element) andevsparams.next();
                    name = elementAnDev.getName();
                    value = elementAnDev.getText();

                    //logger.debug( "Pairs: Devices.[" + name + " : " + value + "]");

                    boolean bOk = true;
                    try {
                        Integer.parseInt(value, 16);
                    } catch (NumberFormatException e) {
                        logger.error("Param Anode_devices." + name + " is not a valid hex-number [" + value
                                + "]! using default!");
                        bOk = false;
                        bResOk = false;
                    }

                    if (bOk) {
                        switch (name) {
                        case "ADC1":
                            m_strADC1Address = value;
                            break;
                        case "ADC2":
                            m_strADC2Address = value;
                            break;
                        case "DAC1":
                            m_strDAC1Address = value;
                            break;
                        case "DAC2":
                            m_strDAC2Address = value;
                            break;
                        case "REL1":
                            m_strREL1Address = value;
                            break;
                        case "ADC3":
                            m_strADC3Address = value;
                            break;
                        case "ADC4":
                            m_strADC4Address = value;
                            break;
                        case "DAC3":
                            m_strDAC3Address = value;
                            break;
                        case "DAC4":
                            m_strDAC4Address = value;
                            break;
                        case "REL2":
                            m_strREL2Address = value;
                            break;
                        default:
                            logger.warn("Unknown param Device.'" + name + "' in settings.xml! Pay attention!");
                            bResOk = false;
                        }
                    }
                }
            }

            if ("Device0_channels".equals(name))
                bResOk = ParseDeviceBlock(AMSConstants.T_DEVICE1, element) & bResOk;
            if ("Device1_channels".equals(name))
                bResOk = ParseDeviceBlock(AMSConstants.T_DEVICE2, element) & bResOk;
            if ("Device2_channels".equals(name))
                bResOk = ParseDeviceBlock(AMSConstants.T_DEVICE3, element) & bResOk;
            if ("Device3_channels".equals(name))
                bResOk = ParseDeviceBlock(AMSConstants.T_DEVICE4, element) & bResOk;
            if ("Device4_channels".equals(name))
                bResOk = ParseDeviceBlock(AMSConstants.T_DEVICE5, element) & bResOk;
            if ("Device5_channels".equals(name))
                bResOk = ParseDeviceBlock(AMSConstants.T_DEVICE6, element) & bResOk;
            if ("Device6_channels".equals(name))
                bResOk = ParseDeviceBlock(AMSConstants.T_DEVICE7, element) & bResOk;
            if ("Device7_channels".equals(name))
                bResOk = ParseDeviceBlock(AMSConstants.T_DEVICE8, element) & bResOk;

        }

        /*
        // iterate through child elements of root with element name "foo"
        for ( Iterator i = root.elementIterator( "foo" ); i.hasNext(); ) {
        Element foo = (Element) i.next();
        // do something
        }
                
        // iterate through attributes of root 
        for ( Iterator i = root.attributeIterator(); i.hasNext(); ) {
        Attribute attribute = (Attribute) i.next();
        // do something
        }
        */

    } catch (MalformedURLException ex) {
        logger.error("MalformedURLException caught while loading settings!", ex);
        bResOk = false;
    } catch (DocumentException ex) {
        logger.error("DocumentException caught while loading settings!", ex);
        bResOk = false;
    }

    return bResOk;
}

From source file:ams.AMSSettings.java

/**
 * ?? ? ? ?  .xml /*ww w.  j  a v  a  2s  .  c o m*/
 *  ? DeviceX_channels ( )
 * @param nDevice         ?
 * @param deviceRoot    .xml-root  ? ? 
 * @return 
 * true  -   ?;
 * false -   ? 
 */
private boolean ParseDeviceBlock(int nDevice, Element deviceRoot) {
    boolean bResOk = true;
    for (Iterator dev = deviceRoot.elementIterator(); dev.hasNext();) {

        Element devElem = (Element) dev.next();
        String name = devElem.getName();

        if (name.equals("anode")) {
            for (Iterator dev_an_chans = devElem.elementIterator(); dev_an_chans.hasNext();) {

                Element elementAnDev = (Element) dev_an_chans.next();
                name = elementAnDev.getName();
                String value = elementAnDev.getText();
                Integer test = new Integer(value);
                logger.debug("Pairs: Device" + nDevice + ".anode.[" + name + " : " + value + "]");

                boolean bOk = true;
                if (name.contains("DAC") == true) {
                    if (test.shortValue() < 1 && test.shortValue() > 4) {
                        logger.warn("Bad value for Device" + nDevice + ".anode.[" + name + "] = '" + value
                                + "'. Using default!");
                        bOk = false;
                        bResOk = false;
                    }
                } else {
                    if (test.shortValue() < 1 && test.shortValue() > 9) {
                        logger.warn("Bad value for Device" + nDevice + ".anode.[" + name + "] = '" + value
                                + "'. Using default!");
                        bOk = false;
                        bResOk = false;
                    }
                }

                if (bOk) {
                    switch (name) {
                    case "ADC_V_DEV":
                        ((AMSSettingsTDev) m_mapDevs.get(nDevice)).SetAnoAdcVoltDev(Integer.parseInt(value));
                        break;
                    case "ADC_V_CHAN":
                        ((AMSSettingsTDev) m_mapDevs.get(nDevice)).SetAnoAdcVoltChan(Integer.parseInt(value));
                        break;
                    case "ADC_C_DEV":
                        ((AMSSettingsTDev) m_mapDevs.get(nDevice)).SetAnoAdcCurrDev(Integer.parseInt(value));
                        break;
                    case "ADC_C_CHAN":
                        ((AMSSettingsTDev) m_mapDevs.get(nDevice)).SetAnoAdcCurrChan(Integer.parseInt(value));
                        break;
                    case "DAC_DEV":
                        ((AMSSettingsTDev) m_mapDevs.get(nDevice)).SetAnoDacDev(Integer.parseInt(value));
                        break;
                    case "DAC_CHAN":
                        ((AMSSettingsTDev) m_mapDevs.get(nDevice)).SetAnoDacChan(Integer.parseInt(value));
                        break;
                    case "REL_DEV":
                        ((AMSSettingsTDev) m_mapDevs.get(nDevice)).SetAnoRelDev(Integer.parseInt(value));
                        break;
                    case "REL_CHAN":
                        ((AMSSettingsTDev) m_mapDevs.get(nDevice)).SetAnoRelChan(Integer.parseInt(value));
                        break;
                    }
                }
            }
        } else if (name.equals("tubulation")) {
            for (Iterator dev_an_chans = devElem.elementIterator(); dev_an_chans.hasNext();) {

                Element elementAnDev = (Element) dev_an_chans.next();
                name = elementAnDev.getName();
                String value = elementAnDev.getText();
                Integer test = new Integer(value);
                logger.debug("Pairs: Device" + nDevice + ".tubulation.[" + name + " : " + value + "]");

                boolean bOk = true;
                if (name.contains("DAC") == true) {
                    if (test.shortValue() < 1 && test.shortValue() > 4) {
                        logger.warn("Bad value for Device" + nDevice + ".tubulation.[" + name + "] = '" + value
                                + "'. Using default!");
                        bOk = false;
                        bResOk = false;
                    }
                } else {
                    if (test.shortValue() < 1 && test.shortValue() > 9) {
                        logger.warn("Bad value for Device" + nDevice + ".tubulation.[" + name + "] = '" + value
                                + "'. Using default!");
                        bOk = false;
                        bResOk = false;
                    }
                }

                if (bOk) {
                    switch (name) {
                    case "ADC_V_DEV":
                        ((AMSSettingsTDev) m_mapDevs.get(nDevice)).SetTubAdcVoltDev(Integer.parseInt(value));
                        break;
                    case "ADC_V_CHAN":
                        ((AMSSettingsTDev) m_mapDevs.get(nDevice)).SetTubAdcVoltChan(Integer.parseInt(value));
                        break;
                    case "ADC_C_DEV":
                        ((AMSSettingsTDev) m_mapDevs.get(nDevice)).SetTubAdcCurrDev(Integer.parseInt(value));
                        break;
                    case "ADC_C_CHAN":
                        ((AMSSettingsTDev) m_mapDevs.get(nDevice)).SetTubAdcCurrChan(Integer.parseInt(value));
                        break;
                    case "DAC_DEV":
                        ((AMSSettingsTDev) m_mapDevs.get(nDevice)).SetTubDacDev(Integer.parseInt(value));
                        break;
                    case "DAC_CHAN":
                        ((AMSSettingsTDev) m_mapDevs.get(nDevice)).SetTubDacChan(Integer.parseInt(value));
                        break;
                    case "REL_DEV":
                        ((AMSSettingsTDev) m_mapDevs.get(nDevice)).SetTubRelDev(Integer.parseInt(value));
                        break;
                    case "REL_CHAN":
                        ((AMSSettingsTDev) m_mapDevs.get(nDevice)).SetTubRelChan(Integer.parseInt(value));
                        break;
                    }
                }
            }
        }
    }
    return bResOk;
}