Example usage for org.jdom2 Document getRootElement

List of usage examples for org.jdom2 Document getRootElement

Introduction

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

Prototype

public Element getRootElement() 

Source Link

Document

This will return the root Element for this Document

Usage

From source file:com.eds.Response.XMLProcessor.java

License:Apache License

/**
 * Constructs a result list in response to an EDS API Search Request
 *///from ww w .ja va2s. com
public ResultsList buildResultsList(Response response) {

    ResultsList resultsList = new ResultsList();
    String resultsListXML = "";

    if (null != response.getErrorStream() && !response.getErrorStream().isEmpty()) {
        resultsList.setApierrormessage(ProcessError(response.getErrorNumber(), response.getErrorStream()));
    } else {
        BufferedReader reader = response.getRead();
        if (null != reader) {
            try {
                String line = "";
                while ((line = reader.readLine()) != null) {
                    resultsListXML += line;
                }
            } catch (IOException e) {
                ApiErrorMessage errorMessage = new ApiErrorMessage();
                errorMessage.setErrorDescription("Error processing resultList response");
                errorMessage.setDetailedErrorDescription(e.getMessage());
                resultsList.setApierrormessage(errorMessage);
            }
        }
        try {
            StringReader stringReader = new StringReader(resultsListXML);
            InputSource inputSource = new InputSource(stringReader);
            Document doc = (new SAXBuilder()).build(inputSource);
            // root element (level 1), handle resultsList
            Element searchResponseMessageGet = doc.getRootElement();

            // level 2 elements
            if (null == searchResponseMessageGet)
                return resultsList;

            Element searchRequestGet = searchResponseMessageGet.getChild("SearchRequestGet",
                    searchResponseMessageGet.getNamespace());
            Element searchResult = searchResponseMessageGet.getChild("SearchResult",
                    searchResponseMessageGet.getNamespace());
            // level 3 elements
            if (null != searchRequestGet) {
                Element queryString = searchRequestGet.getChild("QueryString", searchRequestGet.getNamespace());
                // Get Query String
                String querystring = queryString.getContent(0).getValue();
                resultsList.setQueryString(querystring);
            }

            Element statistics = searchResult.getChild("Statistics", searchResult.getNamespace());
            Element data = searchResult.getChild("Data", searchResult.getNamespace());

            /*
             * In next steps, elements will be analyzed separately
             */

            // Get Total Hits and Total Search Time
            String totalHits = "0";
            if (null != statistics) {
                totalHits = statistics.getContent(0).getValue();
                String totalSearchTime = statistics.getContent(1).getValue();
                resultsList.setHits(totalHits);
                resultsList.setSearchTime(totalSearchTime);
            }

            if (Integer.parseInt(totalHits) > 0 && null != data) {
                // Get Results
                Element records = data.getChild("Records", data.getNamespace());
                if (null != records && null != records.getChildren()) {
                    List<Element> recordsList = records.getChildren();
                    for (int i = 0; i < recordsList.size(); i++) {
                        Element xmlRecord = (Element) recordsList.get(i);
                        if (null == xmlRecord)
                            continue;
                        Record record = new Record();
                        record = constructRecord(xmlRecord);
                        resultsList.getResultsList().add(record);
                    }
                }
            }
        } catch (Exception e) {
            ApiErrorMessage errorMessage = new ApiErrorMessage();
            errorMessage.setErrorDescription("Error processing search response");
            errorMessage.setDetailedErrorDescription(e.getMessage());
            resultsList.setApierrormessage(errorMessage);
        }
    }
    return resultsList;

}

From source file:com.eds.Response.XMLProcessor.java

License:Apache License

/**
 * Constructs a retrieve response object from the EDS API response XML
 * message/*from w  ww. j a  v  a  2s  .co  m*/
 */
public RetrieveResult buildRecord(Response response) {

    RetrieveResult retrieveResult = new RetrieveResult();
    BufferedReader reader = response.getRead();
    String RecordXML = "";
    if (null != response.getErrorStream() && !response.getErrorStream().isEmpty()) {
        retrieveResult.setApiErrorMessage(ProcessError(response.getErrorNumber(), response.getErrorStream()));
    } else {
        try {
            String line = "";
            while ((line = reader.readLine()) != null) {
                RecordXML += line;
            }
        } catch (IOException e) {
            ApiErrorMessage errorMessage = new ApiErrorMessage();
            errorMessage.setErrorDescription("Error processing resultList response");
            errorMessage.setDetailedErrorDescription(e.getMessage());
            retrieveResult.setApiErrorMessage(errorMessage);
        }
        try {
            StringReader stringReader = new StringReader(RecordXML);
            InputSource inputSource = new InputSource(stringReader);
            Document doc = (new SAXBuilder()).build(inputSource);

            // ---------------begin to handle record

            // root element (level 1)
            Element data = doc.getRootElement();
            // level 2 elements

            // Get Results
            Element xmlRecord = data.getChild("Record", data.getNamespace());
            Record record = null;
            if (null != xmlRecord)
                record = constructRecord(xmlRecord, true);
            retrieveResult.setRecord(record);
        } catch (Exception e) {
            ApiErrorMessage errorMessage = new ApiErrorMessage();
            errorMessage.setErrorDescription("Error processing search response");
            errorMessage.setDetailedErrorDescription(e.getMessage());
            retrieveResult.setApiErrorMessage(errorMessage);
        }
    }
    return retrieveResult;

}

From source file:com.forum.action.eder.PerfilACT.java

public String execute() throws Exception {
    int c0 = 0, c1 = 0, c2 = 0, c3 = 0, c4 = 0, c5 = 0, c6 = 0, c7 = 0, c8 = 0, c9 = 0, c10 = 0;
    Model modelo = ModelFactory.createDefaultModel();
    FileManager.get().readModel(modelo,//from  w w w .jav  a2s .c om
            ServletActionContext.getServletContext().getRealPath("/") + "/usuarios.rdf");
    Resource perfil = modelo.getResource("http://comunipn.multiaportes.com/rdf/" + nick);

    NodeIterator amigos = modelo.listObjectsOfProperty(
            modelo.getResource("http://comunipn.multiaportes.com/rdf/" + solicitante), FOAF.knows);

    while (amigos.hasNext()) {
        RDFNode amigo = amigos.next();
        Resource amigo1 = (Resource) amigo; // Resource es clase hija de RDFNode

        if (amigo1.getProperty(FOAF.nick).getObject().toString().equals(nick))
            es_conocido = "1";
        else
            es_conocido = "0";
    }

    ServletContext context = ServletActionContext.getServletContext();
    String url = context.getRealPath("/");

    Document document = getDocument(url + "/database.xml");
    Element root = document.getRootElement();
    Element temas = root.getChild("respuestas");
    List<Element> child = temas.getChildren();

    for (Element tema : child) {
        for (Element respuesta : tema.getChildren()) {
            if (respuesta.getAttributeValue("usuario").equals(nick)) {
                switch (Integer.parseInt(respuesta.getAttributeValue("calificacion"))) {
                case 0:
                    c0++;
                    break;
                case 1:
                    c1++;
                    break;
                case 2:
                    c2++;
                    break;
                case 3:
                    c3++;
                    break;
                case 4:
                    c4++;
                    break;
                case 5:
                    c5++;
                    break;
                case 6:
                    c6++;
                    break;
                case 7:
                    c7++;
                    break;
                case 8:
                    c8++;
                    break;
                case 9:
                    c9++;
                    break;
                case 10:
                    c10++;
                    break;
                }
            }
        }
    }

    detalles = new Perfil(perfil.getProperty(FOAF.givenname).getObject().toString(),
            perfil.getProperty(FOAF.family_name).getObject().toString(), "Alumno",
            perfil.getProperty(FOAF.schoolHomepage).getObject().toString());
    calificaciones = new EstadisticasIndiv(c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, c10);
    return SUCCESS;
}

From source file:com.forum.action.eder.TemaACT.java

private Hilo tema(int id, String url) {
    String megacadena = "";
    Hilo h = new Hilo();
    Document document = getDocument(url);
    Element root = document.getRootElement();
    Element temas = root.getChild("temas");
    List<Element> child = temas.getChildren();
    for (Element e : child) {
        try {/*from ww w  . java 2 s.  co  m*/
            if (e.getAttribute("id").getIntValue() == id) {
                h.setTitulo(e.getChildText("titulo"));
                h.setDetalles(e.getChildText("detalles"));
                List<Element> e2 = e.getChildren("tags");
                for (int i = 0; i < e2.size(); i++) {
                    megacadena += e2.get(i).getValue() + ",";
                }

                h.setEtiquetas(megacadena);
                break;
            }
        } catch (DataConversionException ex) {

        }
    }
    return h;
}

From source file:com.forum.action.eder.TemaACT.java

private ArrayList<Respuesta> respuestasTema(int id, String url) {
    ArrayList<Respuesta> arreglo = new ArrayList<>();
    Document document = getDocument(url);
    Element root = document.getRootElement();
    Element temas = root.getChild("respuestas");
    List<Element> child = temas.getChildren();
    for (Element e : child) {
        if (Integer.parseInt(e.getAttributeValue("id")) != id)
            continue;
        List<Element> child2 = e.getChildren();
        for (Element e2 : child2) {
            arreglo.add(new Respuesta(e2.getAttributeValue("usuario"), e2.getValue(),
                    Integer.parseInt(e2.getAttributeValue("id")),
                    Integer.parseInt(e2.getAttributeValue("calificacion"))));
        }/*w w w.  j a v a2s .  c o m*/
    }
    return arreglo;
}

From source file:com.github.lucapino.sheetmaker.renderer.GmTemplateRenderer.java

public JPanel renderTemplate(URL templateXML, Map<String, String> tokenMap, String backgroundFilePath,
        String fanArt1FilePath, String fanArt2FilePath, String fanArt3FilePath, String coverFilePath)
        throws Exception {
    this.tokenMap = tokenMap;
    String templatePath = templateXML.getFile();
    File templateFile = new File(templatePath);

    // set basePath
    basePath = templateFile.getParentFile().getAbsolutePath();

    logger.info("Loading template...");
    // load template
    String templateString = IOUtils.toString(checkForUtf8BOMAndDiscardIfAny(new FileInputStream(templateFile)),
            "ISO-8859-1");
    // filter placeHolder
    logger.info("Parsing template for substitution...");
    templateString = templateString.replaceAll("%PATH%", basePath);
    templateString = templateString.replaceAll("%BACKGROUND%", backgroundFilePath);
    templateString = templateString.replaceAll("%FANART1%", fanArt1FilePath);
    templateString = templateString.replaceAll("%FANART2%", fanArt2FilePath);
    templateString = templateString.replaceAll("%FANART3%", fanArt3FilePath);
    templateString = templateString.replaceAll("%COVER%", coverFilePath);
    StringReader templateReader = new StringReader(templateString);
    System.out.println(templateString);
    logger.info("Template parsed...");
    // parse XML//from www .  ja  v  a2 s.  c  o  m
    // the SAXBuilder is the easiest way to create the JDOM2 objects.
    SAXBuilder jdomBuilder = new SAXBuilder();

    // jdomDocument is the JDOM2 Object
    Document jdomDocument = jdomBuilder.build(templateReader);
    Element rootElement = jdomDocument.getRootElement();
    // process Settings
    logger.info("Caching settings...");
    Element settingsElement = rootElement.getChild(SETTINGS);
    settings = new TemplateSettings(settingsElement);
    // process SoundFormats
    logger.info("Caching soundFormats...");
    Element soundFormatsElement = rootElement.getChild(SOUND_FORMATS);
    cacheElements(soundFormatsElement, soundFormats);
    // process Resolutions
    logger.info("Caching resolutions...");
    Element resolutionsElement = rootElement.getChild(RESOLUTIONS);
    cacheElements(resolutionsElement, resolutions);
    // process MediaFormats
    logger.info("Caching mediaFormats...");
    Element mediaFormatsElement = rootElement.getChild(MEDIA_FORMATS);
    cacheElements(mediaFormatsElement, mediaFormats);
    // process VideoFormats
    logger.info("Caching videoFormats...");
    Element videoFormatsElement = rootElement.getChild(VIDEO_FORMATS);
    cacheElements(videoFormatsElement, videoFormats);
    // process ImageDrawTemplate
    Element drawImageTemplateElement = rootElement.getChild(IMAGE_DRAW_TEMPLATE);
    logger.info("Drawing images...");
    return drawTemplate(drawImageTemplateElement);
}

From source file:com.github.lucapino.sheetmaker.renderer.JavaTemplateRenderer.java

public JPanel renderTemplate(URL templateXML, Map<String, String> tokenMap, String backgroundFilePath,
        String fanArt1FilePath, String fanArt2FilePath, String fanArt3FilePath, String coverFilePath)
        throws Exception {
    this.tokenMap = tokenMap;
    String templatePath = templateXML.getFile();
    File templateFile = new File(templatePath);

    // set basePath
    basePath = templateFile.getParentFile().getAbsolutePath().replaceAll("\\\\", "/");

    logger.info("Loading template...");
    // load template
    String templateString = IOUtils.toString(checkForUtf8BOMAndDiscardIfAny(new FileInputStream(templateFile)),
            "ISO-8859-1");
    // filter placeHolder
    logger.info("Parsing template for substitution...");
    templateString = templateString.replaceAll("%PATH%", basePath);
    templateString = templateString.replaceAll("%BACKGROUND%", backgroundFilePath);
    templateString = templateString.replaceAll("%FANART1%", fanArt1FilePath);
    templateString = templateString.replaceAll("%FANART2%", fanArt2FilePath);
    templateString = templateString.replaceAll("%FANART3%", fanArt3FilePath);
    templateString = templateString.replaceAll("%COVER%", coverFilePath);
    StringReader templateReader = new StringReader(templateString);
    System.out.println(templateString);
    logger.info("Template parsed...");
    // parse XML/*from   w ww .j  ava2 s . c  om*/
    // the SAXBuilder is the easiest way to create the JDOM2 objects.
    SAXBuilder jdomBuilder = new SAXBuilder();

    // jdomDocument is the JDOM2 Object
    Document jdomDocument = jdomBuilder.build(templateReader);
    Element rootElement = jdomDocument.getRootElement();
    // process Settings
    logger.info("Caching settings...");
    Element settingsElement = rootElement.getChild(SETTINGS);
    settings = new TemplateSettings(settingsElement);
    // process SoundFormats
    logger.info("Caching soundFormats...");
    Element soundFormatsElement = rootElement.getChild(SOUND_FORMATS);
    cacheElements(soundFormatsElement, soundFormats);
    // process Resolutions
    logger.info("Caching resolutions...");
    Element resolutionsElement = rootElement.getChild(RESOLUTIONS);
    cacheElements(resolutionsElement, resolutions);
    // process MediaFormats
    logger.info("Caching mediaFormats...");
    Element mediaFormatsElement = rootElement.getChild(MEDIA_FORMATS);
    cacheElements(mediaFormatsElement, mediaFormats);
    // process VideoFormats
    logger.info("Caching videoFormats...");
    Element videoFormatsElement = rootElement.getChild(VIDEO_FORMATS);
    cacheElements(videoFormatsElement, videoFormats);
    // process ImageDrawTemplate
    Element drawImageTemplateElement = rootElement.getChild(IMAGE_DRAW_TEMPLATE);
    logger.info("Drawing images...");
    return drawTemplate(drawImageTemplateElement);
}

From source file:com.github.zdsiyan.maven.plugin.smartconfig.SmartconfigMojo.java

License:Apache License

private Smartconfig buildFastconfig() throws Exception {
    PluginParameterExpressionEvaluator pel = new PluginParameterExpressionEvaluator(session, execution);
    Smartconfig fastconfig = new Smartconfig();

    SAXBuilder builder = new SAXBuilder();
    Document doc = builder.build(config);
    Element root = doc.getRootElement();

    // use scriptEngine, maybe we can extend it, not only javascript 
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("javascript");

    // load profile
    List<Profile> profiles = session.getCurrentProject().getActiveProfiles();
    profiles.forEach(profile -> profile.getProperties().keySet().forEach(key -> {
        Object value = profile.getProperties().get(key);
        engine.put(key.toString(), value);
        //getLog().warn("profile:"+key);
    }));//from w ww .  ja v  a2s  .co  m
    // load user properties
    session.getUserProperties().keySet().forEach(key -> {
        Object value = session.getUserProperties().get(key);
        engine.put(key.toString(), value);
        //getLog().warn("user:"+key);
    });
    /* load sys properties
    session.getSystemProperties().keySet().forEach(key->{
       Object value = session.getSystemProperties().get(key);
       engine.put(key.toString(), value);
       getLog().warn("sys:"+key);
    });
    */

    session.getCurrentProject().getProperties().keySet().forEach(key -> {
        Object value = session.getCurrentProject().getProperties().get(key);
        engine.put(key.toString(), value);
        //getLog().warn("prop:"+key);
    });

    // config-file
    for (Element cf : root.getChildren()) {
        String path = String.valueOf(pel.evaluate(cf.getAttributeValue("path")));
        File file = new File(path);
        if (!file.isAbsolute()) {
            file = new File(outputDirectory, path);
        }

        boolean disable = false;
        //eval the script
        if (StringUtils.isNotEmpty(cf.getAttributeValue("disable"))) {
            Object result = engine.eval(cf.getAttributeValue("disable"));
            if (Boolean.TRUE.equals(result)) {
                disable = true;
            }
        }
        if (disable == true) {
            continue;
        }

        //rename to
        if (StringUtils.isNotEmpty(cf.getAttributeValue("replace"))) {
            String replace = String.valueOf(pel.evaluate(cf.getAttributeValue("replace")));
            //getLog().warn("filepath:"+file.getPath());
            File refile = new File(file.getParent() + File.separator + replace);
            //getLog().warn("refilepath:"+refile.getPath());
            FileUtils.rename(file, refile);
            continue;
        }

        ConfigFile.Mode mode;
        if (StringUtils.isNotEmpty(cf.getAttributeValue("mode"))) {
            mode = ConfigFile.Mode.valueOf(cf.getAttributeValue("mode"));
        } else {
            mode = toConfigMode(path.substring(path.lastIndexOf(".") + 1));
        }

        if (mode == null) {
            throw new SmartconfigException("Not found file[" + path + "] replace mode");
        }

        ConfigFile configFile = new ConfigFile(file, mode);

        for (Element rt : cf.getChildren()) {
            String expression = rt.getAttributeValue("expression");
            String value = String.valueOf(pel.evaluate(rt.getTextTrim()));
            PointHandle.Mode phMode;
            if (StringUtils.isNotEmpty(rt.getAttributeValue("mode"))) {
                phMode = PointHandle.Mode.valueOf(rt.getAttributeValue("mode"));
            } else {
                phMode = PointHandle.Mode.replace;
            }
            if (mode == null) {
                throw new SmartconfigException("Not found pointhandle mode");
            }
            configFile.addPointHandle(new PointHandle(expression, value, phMode));

        }
        fastconfig.addConfigFile(configFile);
    }
    return fastconfig;
}

From source file:com.globalsight.dispatcher.bo.JobTask.java

License:Apache License

private void createTargetFile(JobBO p_job, String[] p_targetSegments) throws IOException {
    OutputStream writer = null;//w  w w  .  j  a  v  a 2  s  .c  om
    File fileStorage = CommonDAO.getFileStorage();
    File srcFile = p_job.getSrcFile();
    Account account = DispatcherDAOFactory.getAccountDAO().getAccount(p_job.getAccountId());
    File trgDir = CommonDAO.getFolder(fileStorage, account.getAccountName() + File.separator + p_job.getJobID()
            + File.separator + AppConstants.XLF_TARGET_FOLDER);
    File trgFile = new File(trgDir, srcFile.getName());
    FileUtils.copyFile(srcFile, trgFile);
    String encoding = FileUtil.getEncodingOfXml(trgFile);

    try {
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(p_job.getSrcFile());
        Element root = doc.getRootElement(); // Get root element
        Namespace namespace = root.getNamespace();
        Element fileElem = root.getChild("file", namespace);
        XPathFactory xFactory = XPathFactory.instance();
        XPathExpression<Element> expr = xFactory.compile("//trans-unit", Filters.element(), null, namespace);
        List<Element> tuList = expr.evaluate(fileElem.getChild("body", namespace));
        for (int tuIndex = 0, trgIndex = 0; tuIndex < tuList.size()
                && trgIndex < p_targetSegments.length; tuIndex++, trgIndex++) {
            if (p_targetSegments[trgIndex] == null) {
                continue;
            }

            Element elem = (Element) tuList.get(tuIndex);
            Element srcElem = elem.getChild("source", namespace);
            Element trgElem = elem.getChild("target", namespace);
            if (srcElem == null || srcElem.getContentSize() == 0) {
                trgIndex--;
                continue;
            }

            if (trgElem != null) {
                setTargetSegment(trgElem, p_targetSegments[trgIndex], encoding);
            } else {
                trgElem = new Element("target", namespace);
                setTargetSegment(trgElem, p_targetSegments[trgIndex], encoding);
                elem.addContent(trgElem);
            }

        }

        XMLOutputter xmlOutput = new XMLOutputter();
        Format format = Format.getRawFormat();
        format.setEncoding(encoding);
        writer = new FileOutputStream(trgFile);
        xmlOutput.setFormat(format);
        writeBOM(writer, format.getEncoding());
        xmlOutput.output(doc, writer);
        p_job.setTrgFile(trgFile);
        logger.info("Create Target File: " + trgFile);
    } catch (JDOMException e1) {
        logger.error("CreateTargetFile Error: ", e1);
    } catch (IOException e1) {
        logger.error("CreateTargetFile Error: ", e1);
    } finally {
        if (writer != null)
            writer.close();
    }
}

From source file:com.globalsight.dispatcher.bo.JobTask.java

License:Apache License

private void setTargetSegment(Element p_trgElement, String p_target, String p_encoding)
        throws UnsupportedEncodingException {
    if (p_target == null || p_target.trim().length() == 0)
        return;/*  w  w w  .j a v  a2  s . c  o m*/

    String target = new String(p_target.getBytes("UTF-8"), p_encoding);
    try {
        StringReader stringReader = new StringReader("<target>" + p_target + "</target>");
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(stringReader);
        Element elem = doc.getRootElement().clone().detach();
        setNamespace(elem, p_trgElement.getNamespace());
        //Delete Original Target Segment.
        p_trgElement.removeContent();
        for (int i = 0; i < elem.getContentSize(); i++) {
            p_trgElement.addContent(elem.getContent(i).clone().detach());
        }
    } catch (Exception e) {
        p_trgElement.setText(target);
    }
}