Example usage for org.dom4j.io SAXReader read

List of usage examples for org.dom4j.io SAXReader read

Introduction

In this page you can find the example usage for org.dom4j.io SAXReader read.

Prototype

public Document read(InputSource in) throws DocumentException 

Source Link

Document

Reads a Document from the given InputSource using SAX

Usage

From source file:StreamFlusher.java

License:Apache License

private Document parseXMLPrefs(String filepath) throws Exception {
    SAXReader reader = new SAXReader();
    Document document = null;//from  ww  w  . j  av  a2 s  .  c om
    // Document document = reader.read(filepath) ;

    try {
        // the encoding should be 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"));
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }

    return document;
}

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;/*from  w w w. j a  va2 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:JenkinsHelper.java

License:Apache License

private String generateJobXML(String test, JSONObject repository) throws Exception {
    String templateJob = repository.getString("templateJob").toLowerCase();

    if (!jenkins.getJobs().containsKey(templateJob)) {
        throw new Exception("Template job not found in jenkins jobs, is the name right?");
    }/*from ww w.  j  av  a 2  s .  c  o  m*/

    String jobXML = client.get("/job/" + templateJob.replace(" ", "%20") + "/config.xml");
    SAXReader reader = new SAXReader();
    Document doc = reader.read(new StringReader(jobXML));
    Element root = doc.getRootElement();

    if (repository.has("mvnOptions") || repository.has("mvnCommand")) {
        root = insertMvnGoals(root, repository, test);
    } else if (repository.has("executeShells") || repository.has("executeShell")) {
        root = insertShellCommand(root, repository, test);
    } else {
        System.out.println("WARNING - Did not provide an executeShell or mvnOptions/mvnCommand in repo: "
                + repository.getString("repository"));
    }

    if (repository.has("description")) {
        root = setDescription(root, repository.getString("description"));
    } else {
        root = setDescription(root, "Automatically generated test job");
    }
    root = enableJob(root);

    return doc.asXML();
}

From source file:Tools.java

public static void encryptApp(Object cert, String password, String sourceModelPath, String targetModelPath,
        String app, String isCompile) {
    if (null == password || "".equals(password))
        throw new RuntimeException("???");
    if (null == sourceModelPath || "".equals(sourceModelPath))
        throw new RuntimeException("");
    if (null == targetModelPath || "".equals(targetModelPath))
        throw new RuntimeException("?");
    if (null == app || "".equals(app))
        throw new RuntimeException("??");
    if (sourceModelPath.equalsIgnoreCase(targetModelPath))
        throw new RuntimeException(
                "?????");
    try {//from w w w  .ja  v  a 2  s . co  m
        password = java.net.URLDecoder.decode(password, "UTF8");
    } catch (UnsupportedEncodingException e1) {
        throw new RuntimeException("???", e1);
    }
    SAXReader reader = new SAXReader();
    Document doc = null;
    try {
        doc = reader.read((InputStream) cert);
    } catch (DocumentException e) {
        throw new RuntimeException("???", e);
    }
    byte[] bCert = loadCert(doc);
    EncryptModel eapp = new EncryptModel(bCert, sourceModelPath, targetModelPath);
    try {
        String[] appList = app.split(";");
        for (int i = 0; i < appList.length; i++)
            eapp.encrypt(appList[i], password, !"false".equalsIgnoreCase(isCompile));
    } catch (IOException e) {
        throw new RuntimeException("", e);
    }
}

From source file:Tools.java

public static Map<String, String> regAppLicense(String appLicense) {
    if (null == appLicense || "".equals(appLicense))
        throw new RuntimeException("License");
    BASE64Decoder decoder = new BASE64Decoder();
    try {/*w w w.j ava  2 s .com*/
        Map<String, String> ret = new HashMap<String, String>();
        SAXReader reader = new SAXReader();
        reader.setEncoding("UTF-8");
        Document doc = reader.read(new ByteArrayInputStream(decoder.decodeBuffer(appLicense)));
        Element root = doc.getRootElement();
        String app = root.elementTextTrim("models");
        ret.put("app", app);
        String content = root.elementTextTrim("content");
        String appPath = FileSystemWrapper.instance().getRealPath(app);
        File fApp = new File(appPath);
        if (!fApp.exists())
            throw new RuntimeException("?\"" + app + "\"?");
        File fAppLicenseDir = new File(appPath + "/license");
        fAppLicenseDir.mkdirs();
        FileOutputStream fo = null;
        try {
            fo = new FileOutputStream(appPath + "/license/license");
            fo.write(content.getBytes());
            fo.flush();
        } finally {
            if (null != fo)
                fo.close();
        }
        String developer = root.elementTextTrim("developer");
        ret.put("developer", developer);
        String validDate = root.elementTextTrim("valid-date");
        ret.put("valid-date", !"0".equals(validDate) ? validDate : "??");
        String userCount = root.elementTextTrim("user-count");
        ret.put("user-count", !"0".equals(userCount) ? userCount : "??");

        return ret;
    } catch (IOException e) {
        throw new RuntimeException("License", e);
    } catch (DocumentException e) {
        throw new RuntimeException("License", e);
    }
}

From source file:Addons.CepWebService.java

private static Document getDocumento(URL url) throws DocumentException {
    SAXReader reader = new SAXReader();
    Document document = reader.read(url);
    return document;
}

From source file:adr.main.AlcorAdrSettings.java

/**
 * ?  ?  .xml //from  w ww .  ja v  a 2 s  .  c  om
 * @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:aml.match.Alignment.java

License:Apache License

private void loadMappingsRDF(String file) throws DocumentException {
    AML aml = AML.getInstance();//from  w  w  w. ja  v a2  s .c om
    URIMap uris = aml.getURIMap();

    //Open the alignment file using SAXReader
    SAXReader reader = new SAXReader();
    File f = new File(file);

    Document doc = reader.read(f);
    //Read the root, then go to the "Alignment" element
    Element root = doc.getRootElement();
    Element align = root.element("Alignment");
    //Get an iterator over the mappings
    Iterator<?> map = align.elementIterator("map");
    while (map.hasNext()) {
        //Get the "Cell" in each mapping
        Element e = ((Element) map.next()).element("Cell");

        if (e == null)
            continue;
        //Get the source class
        String sourceURI = e.element("entity1").attributeValue("resource");

        //Get the target class
        String targetURI = e.element("entity2").attributeValue("resource");

        //Get the similarity measure
        String measure = e.elementText("measure");
        //Parse it, assuming 1 if a valid measure is not found
        double similarity = 1;
        if (measure != null) {
            try {
                similarity = Double.parseDouble(measure);
                if (similarity < 0 || similarity > 1)
                    similarity = 1;
            } catch (Exception ex) {
                /*Do nothing - use the default value*/}
            ;
        }
        //Get the relation
        String r = e.elementText("relation");
        if (r == null)
            r = "?";
        MappingRelation rel = MappingRelation.parseRelation(StringEscapeUtils.unescapeXml(r));
        //Check if the URIs are listed in the URI map 
        int sourceIndex = uris.getIndex(sourceURI);
        int targetIndex = uris.getIndex(targetURI);
        //If they are, add the mapping to the maps and proceed to next mapping
        if (sourceIndex > -1 && targetIndex > -1) {
            if (sourceIndex < targetIndex)
                add(sourceIndex, targetIndex, similarity, rel);
            else
                add(targetIndex, sourceIndex, similarity, rel);
        }
    }
}

From source file:aml.match.Alignment.java

License:Apache License

private void loadMappingsRDF2(String file) throws DocumentException {
    AML aml = AML.getInstance();/*from w ww  .j a  va 2s .  c om*/
    URIMap uris = aml.getURIMap();

    //Open the alignment file using SAXReader
    SAXReader reader = new SAXReader();
    File f = new File(file);

    Document doc = reader.read(f);
    //Read the root, then go to the "Alignment" element
    Element root = doc.getRootElement();
    Element align = root.element("Alignment");
    //Get an iterator over the mappings
    Iterator<?> map = align.elementIterator("map");
    while (map.hasNext()) {
        //Get the "Cell" in each mapping
        Element e = ((Element) map.next()).element("Cell");

        if (e == null)
            continue;

        //Get the source class
        String sourceURI = e.element("entity1").element("Class").attributeValue("about");

        //Get the target class
        String targetURI = e.element("entity2").element("Class").element("and").element("Class")
                .attributeValue("about");

        //Get the similarity measure
        String measure = e.elementText("measure");
        //Parse it, assuming 1 if a valid measure is not found
        double similarity = 1;
        if (measure != null) {
            try {
                similarity = Double.parseDouble(measure);
                if (similarity < 0 || similarity > 1)
                    similarity = 1;
            } catch (Exception ex) {
                /*Do nothing - use the default value*/}
            ;
        }

        //Get the relation
        String r = e.elementText("relation");
        if (r == null)
            r = "?";

        MappingRelation rel = MappingRelation.parseRelation(StringEscapeUtils.unescapeXml(r));
        //Check if the URIs are listed in the URI map 

        int sourceIndex = uris.getIndex(sourceURI);

        int targetIndex = uris.getIndex(targetURI);

        //If they are, add the mapping to the maps and proceed to next mapping

        if (sourceIndex > -1 && targetIndex > -1) {
            if (sourceIndex < targetIndex)
                add(sourceIndex, targetIndex, similarity, rel);
            else
                add(targetIndex, sourceIndex, similarity, rel);
        }

    }
}

From source file:aml.match.CompoundAlignment.java

License:Apache License

private void loadMappingsRDF(String file) throws DocumentException {
    AML aml = AML.getInstance();/*from w ww. j a v a2s  .c  om*/
    URIMap uris = aml.getURIMap();

    //Open the alignment file using SAXReader
    SAXReader reader = new SAXReader();

    File f = new File(file);

    Document doc = reader.read(f);
    //Read the root, then go to the "Alignment" element
    Element root = doc.getRootElement();

    Element align = root.element("Alignment");
    //Get an iterator over the mappings
    Iterator<?> map = align.elementIterator("map");

    while (map.hasNext()) {

        //Get the "Cell" in each mapping
        Element e = ((Element) map.next()).element("Cell");
        if (e == null) {
            continue;
        }
        //Get the source class
        String sourceURI = e.element("entity1").element("Class").attributeValue("about");
        uris.addURI(sourceURI);
        //Get the target class

        //Get the both target classes
        List<Element> elements = e.element("entity2").element("Class").element("and").elements("Class");

        //Get the target 1
        String targetURI = elements.get(0).attributeValue("about");
        uris.addURI(targetURI);
        //Get the target 2
        String target2URI = elements.get(1).attributeValue("about");

        uris.addURI(target2URI);
        //Get the similarity measure
        String measure = e.elementText("measure");

        //Parse it, assuming 1 if a valid measure is not found
        double similarity = 1;
        if (measure != null) {
            try {
                similarity = Double.parseDouble(measure);
                if (similarity < 0 || similarity > 1)
                    similarity = 1;
            } catch (Exception ex) {
                /*Do nothing - use the default value*/}
            ;
        }

        //Get the relation
        String r = e.elementText("relation");
        if (r == null)
            r = "?";
        MappingRelation rel = MappingRelation.parseRelation(StringEscapeUtils.unescapeXml(r));
        //Check if the URIs are listed in the URI map 
        int sourceIndex = uris.getIndex(sourceURI);
        int targetIndex = uris.getIndex(targetURI);
        int targetIndex2 = uris.getIndex(target2URI);
        //If they are, add the mapping to the maps and proceed to next mapping

        if (sourceIndex > -1 && targetIndex > -1 && targetIndex2 > -1) {
            if (sourceIndex < targetIndex)
                add(sourceIndex, targetIndex, targetIndex2, similarity, rel);
            else
                add(targetIndex, sourceIndex, targetIndex2, similarity, rel);
        }

    }
}