Example usage for org.dom4j Document getRootElement

List of usage examples for org.dom4j Document getRootElement

Introduction

In this page you can find the example usage for org.dom4j Document getRootElement.

Prototype

Element getRootElement();

Source Link

Document

Returns the root Element for this document.

Usage

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?");
    }// w  ww  .  j  a  v a  2 s  .c om

    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

private static byte[] loadCert(Document cert) {
    if (null == cert)
        throw new RuntimeException("??");
    Element root = cert.getRootElement();
    if (null == root)
        throw new RuntimeException("???");
    String content = root.elementTextTrim("content");
    if (null == content)
        throw new RuntimeException("???");
    return content.getBytes();
}

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 {//from  w  w w.j  av  a2s . co m
        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:Main2.java

License:Open Source License

public static void main(String[] args) throws IOException {
    boolean printTokens = false;
    boolean showTree = false;
    boolean produceXml = false;
    boolean produceSource = false;
    for (int i = 2; i < args.length; i++) {
        if (args[i].length() == 2) {
            switch (args[i].charAt(1)) {
            case 't':
                printTokens = true;/* ww w  . ja  v a2  s.co m*/
                break;
            case 'v':
                showTree = true;
                break;
            case 'x':
                produceXml = true;
                break;
            case 's':
                produceSource = true;
                break;
            }
        }
    }
    ASTWindow window = showTree ? new ASTWindow("AST") : null;
    Document doc = null;
    if (produceXml) {
        doc = DocumentHelper.createDocument(DocumentHelper.createElement("asp"));
    }
    try {
        File f = new File(args[0]);
        File base = new File(args[1]);
        if (printTokens) {
            AspStreamSelector selector = new AspStreamSelector(f, base);
            printApsTokens(selector);
            if (!(showTree || produceXml)) {
                return;
            }
        }
        AspParser asp = new AspParser(base, new File("out"));
        asp.setGenerateCode(produceSource);
        Map vbTokens = null;
        Map jsTokens = null;
        Map tokens = null;
        List astList = asp.parseFile(f, true);
        for (Iterator it = astList.iterator(); it.hasNext();) {
            Object[] val = (Object[]) it.next();
            boolean isVb = ((Boolean) val[0]).booleanValue();
            if (showTree) {
                if (isVb) {
                    window.addAST("Original VB", createRoot("VB ASP", (AST) val[1]));
                    if (val.length > 2) {
                        window.addAST("VB Generated", createRoot("VB", (AST) val[2]));
                    }
                } else {
                    window.addAST("ASP JS", createRoot("JS", (AST) val[1]));
                    window.addAST("JS Generated", createRoot("JS", (AST) val[2]));
                }
            }
            if (produceXml) {
                String rootName;
                if (isVb) {
                    rootName = "vb";
                    if (vbTokens == null) {
                        vbTokens = new HashMap();
                        putTokens(new VbsTree(), vbTokens);
                    }
                    tokens = vbTokens;
                } else {
                    rootName = "js";
                    if (jsTokens == null) {
                        jsTokens = new HashMap();
                        putTokens(new JsTree(), jsTokens);
                    }
                    tokens = jsTokens;
                }
                Element nodeEl = doc.getRootElement().addElement(rootName);
                Element orig = nodeEl.addElement("original");
                new XmlTestBuilder(orig, tokens).visit((AST) val[1]);
                Element trans = nodeEl.addElement("translated");
                new XmlTestBuilder(trans, tokens).visit((AST) val[2]);
            }
        }
        if (produceXml) {
            OutputFormat of = OutputFormat.createPrettyPrint();
            of.setEncoding("ISO-8859-7");
            XMLWriter xwriter = new XMLWriter(new FileWriter("asp.xml"), of);
            xwriter.write(doc);
            xwriter.close();
        }
        if (showTree && window.hasAST()) {
            window.pack();
            window.setVisible(true);
            window.setExtendedState(Frame.MAXIMIZED_BOTH);
        }
    } catch (Exception ex) {
        ex.printStackTrace(System.out);
        System.err.println("Error");
    }
}

From source file:Addons.CepWebService.java

private static void criarEndereco(Endereco endereco) {
    try {// w  ww. j  a  va  2 s. c om
        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 /* www  .ja  va2s .  c  o  m*/
 * @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();//  w ww  .  j ava  2 s.  c o m
    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();// www . ja v a 2  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").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();/* www.j a  v a2s.c o m*/
    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);
        }

    }
}

From source file:aml.util.MeSHParser.java

License:Apache License

public static void main(String[] args) throws Exception {
    Vector<String> concepts = new Vector<String>();
    Lexicon lexicon = new Lexicon();

    SAXReader reader = new SAXReader();
    File f = new File("store/knowledge/mesh.xml");
    Document doc = reader.read(f);
    Element root = doc.getRootElement();

    Iterator<?> records = root.elementIterator("DescriptorRecord");
    int index = 0;
    while (records.hasNext()) {
        Element concList = ((Element) records.next()).element("ConceptList");
        Iterator<?> conc = concList.elementIterator("Concept");
        while (conc.hasNext()) {
            Element c = (Element) conc.next();
            String conceptName = c.element("ConceptName").elementText("String");
            concepts.add(conceptName);//from   w  ww . ja v a 2  s  . com
            lexicon.add(index, conceptName, LexicalType.LABEL, "", 0.90);

            String casN1Name = c.elementText("CASN1Name");
            if (casN1Name != null)
                lexicon.add(index, casN1Name, LexicalType.FORMULA, "", 0.85);

            Element termList = c.element("TermList");
            Iterator<?> terms = termList.elementIterator("Term");
            while (terms.hasNext()) {
                Element t = (Element) terms.next();
                String termName = t.elementText("String");
                if (!conceptName.equals(termName))
                    lexicon.add(index, termName, LexicalType.EXACT_SYNONYM, "", 0.85);
            }
            index++;
        }
    }
    lexicon.save("store/knowledge/mesh.lexicon");
}