Example usage for org.jdom2.input SAXBuilder SAXBuilder

List of usage examples for org.jdom2.input SAXBuilder SAXBuilder

Introduction

In this page you can find the example usage for org.jdom2.input SAXBuilder SAXBuilder.

Prototype

public SAXBuilder() 

Source Link

Document

Creates a new JAXP-based SAXBuilder.

Usage

From source file:arquivo.ArquivoFilme.java

public boolean confirnaSesao(int numeroSala, int horaI, int mimI, int horaF, int mimF) {
    SAXBuilder builder = new SAXBuilder();
    try {/* w  w  w . ja v a2s  .c om*/
        Document doc = builder.build(arquivo);
        Element root = (Element) doc.getRootElement();

        List<Element> filme = root.getChildren("filme");
        for (int i = 0; i < filme.size(); i++) {
            List<Element> salas = filme.get(i).getChildren("sala");
            for (int j = 0; j < salas.size(); j++) {
                if (salas.get(j).getAttribute("numeroSala").equals("" + numeroSala)) {
                    List<Element> secoes = salas.get(j).getChildren("secao");
                    for (int d = 0; d < secoes.size(); d++) {
                        int horaEF = Integer.parseInt(secoes.get(d).getAttributeValue("horaF"));
                        int mimEF = Integer.parseInt(secoes.get(d).getAttributeValue("mimF"));
                        if (horaI >= horaEF && mimI > mimEF + 15) {
                            return true;
                        }
                        int horaIF = Integer.parseInt(secoes.get(d).getAttributeValue("horaI"));
                        int mimIF = Integer.parseInt(secoes.get(d).getAttributeValue("mimI"));
                        if (horaF <= horaIF && mimF < mimIF + 15) {
                            return true;
                        }
                    }
                }
            }
        }
    } catch (Exception e) {

    }
    return false;
}

From source file:arquivo.ArquivoFilme.java

public List buscaSalas(String nome) {
    List<Element> salas = new LinkedList<>();
    SAXBuilder builder = new SAXBuilder();
    try {//  w w  w.  ja v a 2s.  co m
        Document doc = builder.build(arquivo);
        Element root = (Element) doc.getRootElement();

        List<Element> filme = super.buscaInterna(root, true, nome, "filme");
        if (filme.size() != 0)
            salas = filme.get(0).getChildren("sala");
    } catch (Exception e) {

    }
    return salas;
}

From source file:arquivo.ArquivoFilme.java

public String editaSesao(String nome, int numeroSala, int horaI, int mimI, int horaIN, int mimIN, int horaFN,
        int mimFN) {
    String retorno = "erro";
    SAXBuilder builder = new SAXBuilder();
    if (this.confirnaSesao(numeroSala, horaIN, mimIN, horaFN, mimFN))
        try {//from w  w  w. j a  v  a2 s .  c  o  m
            Document doc = builder.build(arquivo);
            Element root = (Element) doc.getRootElement();

            List<Element> filme = super.buscaInterna(root, true, nome, "filme");
            if (filme.size() == 0)
                return "filme n encontrado";
            List<Element> secao = this.buscaSesao(filme.get(0), numeroSala, horaI, mimI);
            if (secao.size() == 0)
                return "sacao n encontrada";
            secao.get(0).setAttribute("horaI", "" + horaIN);
            secao.get(0).setAttribute("mimI", "" + mimIN);
            secao.get(0).setAttribute("horaF", "" + horaFN);
            secao.get(0).setAttribute("mimF", "" + mimFN);

        } catch (Exception e) {

        }
    else
        retorno = "horario indiponivel";
    return retorno;
}

From source file:arquivo.ArquivoFilme.java

public boolean removeSecao(String nome, int numeroSala, int horaI, int mimI) {
    try {/* w w  w .  j  a va2 s .c o m*/
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(arquivo);
        Element root = (Element) doc.getRootElement();

        List<Element> filme = super.buscaInterna(root, true, nome, "filme");
        if (filme.size() == 0)
            return false;
        List<Element> removido = this.buscaSesao(filme.get(0), numeroSala, horaI, mimI);
        if (removido.size() == 0)
            return false;
        filme.get(0).removeContent(removido.get(0));
        return true;
    } catch (Exception e) {

    }
    return false;
}

From source file:at.ac.tuwien.ims.latex2mobiformulaconv.converter.latex2html.PandocLatexToHtmlConverter.java

License:Open Source License

@Override
public Document convert(File tex, String title) {
    logger.debug("Start convert() with file " + tex.toPath().toAbsolutePath().toString() + ", title: " + title);

    CommandLine cmdLine;/*from  w ww  . j  av  a2  s . c o m*/
    if (execPath != null) {
        // Run the configured pandoc executable
        logger.info("Pandoc will be run from: " + execPath.toString());
        cmdLine = new CommandLine(execPath.toFile());
    } else {
        // Run in system PATH environment
        logger.info("Pandoc will be run within the PATH variable.");
        cmdLine = new CommandLine("pandoc");
    }

    cmdLine.addArgument("--from=latex");
    cmdLine.addArgument("--to=html5");
    cmdLine.addArgument("--asciimathml"); // With this option, pandoc does not render latex formulas

    cmdLine.addArgument("${file}");

    HashMap<String, Path> map = new HashMap<String, Path>();
    map.put("file", Paths.get(tex.toURI()));

    cmdLine.setSubstitutionMap(map);

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000); // max execution time 1 minute
    Executor executor = new DefaultExecutor();
    executor.setExitValue(1);
    executor.setWatchdog(watchdog);
    StringWriter writer = new StringWriter();
    WriterOutputStream writerOutputStream = new WriterOutputStream(writer, Charset.forName("UTF-8"));

    ExecuteStreamHandler pandocStreamHandler = new PumpStreamHandler(writerOutputStream, System.err);
    executor.setStreamHandler(pandocStreamHandler);

    logger.debug("Launching pandoc:");
    logger.debug(cmdLine.toString());

    try {
        executor.execute(cmdLine, resultHandler);
    } catch (IOException e) {
        logger.error("Pandoc's execution failed, exiting...");
        logger.error(e.getMessage(), e);
        System.exit(-1);
    }

    try {
        resultHandler.waitFor();
        int exitValue = resultHandler.getExitValue();

        logger.debug("Pandoc execution's exit value: " + exitValue);
        ExecuteException executeException = resultHandler.getException();
        if (executeException != null && executeException.getCause() != null) {

            String exceptionKlass = executeException.getCause().getClass().getCanonicalName();
            String exceptionMessage = executeException.getCause().getMessage();

            if (exceptionKlass.endsWith("IOException")
                    || exceptionMessage.contains("Cannot run program \"pandoc\"")) {
                logger.error("Pandoc could not be found! Exiting...");
                logger.debug(executeException);
                System.exit(1);
            }
            logger.debug(exceptionKlass + ": " + exceptionMessage);
        }

    } catch (InterruptedException e) {
        logger.error("pandoc conversion thread got interrupted, exiting...");
        logger.error(e.getMessage(), e);
        System.exit(1);
    }

    // add html document structure to output
    // pandoc returns no document markup (html, head, body)
    // therefore we have to use a template
    String htmlOutput = "<!DOCTYPE html>\n" + "<html>\n" + "<head>\n" +
    // set title
            "<title>" + title + "</title>\n" +
            // include css
            "<link rel=\"stylesheet\" type=\"text/css\" href=\"main.css\"></link>\n" + "</head>\n" + "<body>";
    try {
        htmlOutput += writer.getBuffer().toString();
        writer.close();

    } catch (IOException e) {
        logger.error("Error reading html result from StringBuffer...");
        logger.error(e.getMessage(), e);
        System.exit(1);
    }

    // Close tags in template
    htmlOutput += "</body>\n" + "</html>";

    // output loading as JDOM Document
    SAXBuilder sax = new SAXBuilder();
    Document document = null;
    try {
        document = sax.build(new StringReader(htmlOutput));
    } catch (JDOMException e) {
        logger.error("JDOM Parsing error");
        logger.error(e.getMessage(), e);
        System.exit(1);
    } catch (IOException e) {
        logger.error("Error reading from String...");
        logger.error(e.getMessage(), e);
        System.exit(1);
    }
    return document;
}

From source file:at.ac.tuwien.ims.latex2mobiformulaconv.converter.mathml2html.DOMFormulaConverter.java

License:Open Source License

@Override
public Formula parse(int id, String latexFormula) {
    Formula formula = super.parseToMathML(id, latexFormula);

    // Generate output
    Element div = new Element("div");

    Element html = new Element("div");
    html.setAttribute("class", "math");

    if (formula.isInvalid() == false) {
        SAXBuilder builder = new SAXBuilder();

        try {/* w  w  w  .j av a  2  s  . c om*/
            Document mathml = builder.build(new StringReader(formula.getMathMl()));

            Element root = mathml.getRootElement();
            if (root.getChildren().isEmpty()) {
                return null;
            }

            Iterator<Element> it = root.getChildren().iterator();

            while (it.hasNext()) {
                Element cur = it.next();
                FormulaElement formulaElement = renderElement(cur);
                if (formulaElement != null) {
                    Element resultHtml = formulaElement.render(null, null);
                    if (resultHtml != null) {
                        html.addContent(resultHtml);
                    } else {
                        logger.debug("HTML is NULL: " + cur.getName());
                    }
                }
            }

        } catch (JDOMException e) {
            logger.error("Error parsing generated MathML:");
            logger.error(formula.getMathMl());
            logger.error(e.getMessage(), e);

        } catch (IOException e) {
            logger.error("Error reading generated MathML:");
            logger.error(formula.getMathMl());
            logger.error(e.getMessage(), e);
        }
    } else {
        html.addContent(renderInvalidFormulaSource(formula));
    }
    div.addContent(html);
    formula.setHtml(div);

    return formula;
}

From source file:at.newmedialab.lmf.util.geonames.builder.GeoLookupImpl.java

License:Apache License

/**
 * Query the geonames-api for a place with the provided name.
 * @param name the name of the place to lookup at geonames
 * @return the URI of the resolved place, or null if no such place exists.
 *///from  w ww  . j  a  v a2s  . c om
private String queryPlace(String name) {
    if (StringUtils.isBlank(name))
        return null;

    StringBuilder querySB = new StringBuilder();
    queryStringAppend(querySB, "q", name);

    queryStringAppend(querySB, "countryBias", countryBias);
    for (char fc : featureClasses) {
        queryStringAppend(querySB, "featureClass", String.valueOf(fc));
    }
    for (String fc : featureCodes) {
        queryStringAppend(querySB, "featureCode", fc);
    }
    for (String c : countries) {
        queryStringAppend(querySB, "country", c);
    }
    for (String cc : continentCodes) {
        queryStringAppend(querySB, "continentCode", cc);
    }
    if (fuzzy < 1) {
        queryStringAppend(querySB, "fuzzy", String.valueOf(fuzzy));
    }

    queryStringAppend(querySB, "maxRows", "1");
    queryStringAppend(querySB, "type", "xml");
    queryStringAppend(querySB, "isNameRequired", "true");
    queryStringAppend(querySB, "style", "short");

    if (StringUtils.isNotBlank(geoNamesUser))
        queryStringAppend(querySB, "username", geoNamesUser);
    if (StringUtils.isNotBlank(geoNamesPasswd))
        queryStringAppend(querySB, "password", geoNamesPasswd);

    final String url = geoNamesUrl + "search?" + querySB.toString();
    HttpGet get = new HttpGet(url);

    try {
        return http.execute(get, new ResponseHandler<String>() {
            /**
             * Parses the xml-response from the geonames webservice and build the uri for the result
             * @return the URI of the resolved place, or null if no place was found.
             */
            @Override
            public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                final int statusCode = response.getStatusLine().getStatusCode();
                if (!(statusCode >= 200 && statusCode < 300)) {
                    return null;
                }
                try {
                    SAXBuilder builder = new SAXBuilder();
                    final HttpEntity entity = response.getEntity();
                    if (entity == null)
                        throw new ClientProtocolException("Body Required");
                    final Document doc = builder.build(entity.getContent());

                    final Element root = doc.getRootElement();
                    final Element status = root.getChild("status");
                    if (status != null) {
                        final int errCode = Integer.parseInt(status.getAttributeValue("value"));
                        if (errCode == 15) {
                            // NO RESULT should not be an exception
                            return null;
                        }

                        throw new GeoNamesException(errCode, status.getAttributeValue("message"));
                    }
                    final Element gName = root.getChild("geoname");
                    if (gName == null)
                        return null;

                    final String geoId = gName.getChildTextTrim("geonameId");
                    if (geoId == null)
                        return null;

                    return String.format(GEONAMES_URI_PATTERN, geoId);
                } catch (NumberFormatException e) {
                    throw new ClientProtocolException(e);
                } catch (IllegalStateException e) {
                    throw new ClientProtocolException(e);
                } catch (JDOMException e) {
                    throw new IOException(e);
                }
            }
        });
    } catch (GeoNamesException e) {
        log.debug("Lookup at GeoNames failed: {} ({})", e.getMessage(), e.getErrCode());
    } catch (ClientProtocolException e) {
        log.error("Could not query geoNames: " + e.getLocalizedMessage(), e);
    } catch (IOException e) {
        log.error("Could not query geoNames: " + e.getLocalizedMessage(), e);
    }
    return null;
}

From source file:backtesting.BackTesterNinety.java

public static boolean CheckBacktestSettingsInCache(LocalDate startDate, LocalDate endDate) {
    try {//from ww w.  jav  a 2 s  .com
        File inputFile = new File("backtest/cache/_settings.xml");

        if (!inputFile.exists()) {
            return false;
        }

        SAXBuilder saxBuilder = new SAXBuilder();
        Document document = saxBuilder.build(inputFile);

        Element rootElement = document.getRootElement();
        Attribute attStart = rootElement.getAttribute("start");
        LocalDate start = LocalDate.parse(attStart.getValue());
        Attribute attEnd = rootElement.getAttribute("end");
        LocalDate end = LocalDate.parse(attEnd.getValue());

        return startDate.isEqual(start) && endDate.isEqual(end);

    } catch (JDOMException e) {
        e.printStackTrace();
        logger.severe("Error in loading from XML: JDOMException.\r\n" + e);
    } catch (IOException ioe) {
        ioe.printStackTrace();
        logger.severe("Error in loading from XML: IOException.\r\n" + ioe);
    }

    return false;
}

From source file:bg.LanguageManager.java

private HashMap<String, String> readLanguageFile(Language lan) {
    SAXBuilder builder = new SAXBuilder();
    HashMap<String, String> lanTextList = new HashMap<String, String>();
    Document document = new Document();
    try {// w w  w.  ja v a 2  s .  c o  m
        switch (lan) {
        case EN:
            document = (Document) builder.build(new File("src\\resource\\language\\en.xml"));
            break;
        case ZH_TW:
            document = (Document) builder.build(new File("src\\resource\\language\\zh-tw.xml"));
            break;
        }
    } catch (IOException | JDOMException ex) {
        Logger.getLogger(TwTextSpliterGUI.class.getName()).log(Level.SEVERE, null, ex);
        UIMessager.showError("Open language resource file failed");
        return null;
    }

    Element root_node = document.getRootElement();

    Element textfield_node = root_node.getChild(NodeCategory.TEXTFIELD.getText());
    Element msg_node = root_node.getChild(NodeCategory.MESSAGE.getText());
    Element button_node = root_node.getChild(NodeCategory.BUTTONTEXT.getText());

    addTextFieldChildrenText(lanTextList, textfield_node);
    addMsgChildrenText(lanTextList, msg_node);
    addButtonChildrenText(lanTextList, button_node);
    return lanTextList;
}

From source file:bg.LanguageManager.java

private HashMap<String, String> readLanguageFile() {
    SAXBuilder builder = new SAXBuilder();
    HashMap<String, String> lanTextList = new HashMap<String, String>();
    Document document = new Document();
    try {// w w  w.j  a v a 2s .  co  m
        switch (this.lanSet) {
        case EN:
            document = (Document) builder.build(new File("src\\resource\\language\\en.xml"));
            break;
        case ZH_TW:
            document = (Document) builder.build(new File("src\\resource\\language\\zh-tw.xml"));
            break;
        }
    } catch (IOException | JDOMException ex) {
        Logger.getLogger(TwTextSpliterGUI.class.getName()).log(Level.SEVERE, null, ex);
        UIMessager.showError("Open language resource file failed");
        return null;
    }

    Element root_node = document.getRootElement();

    Element textfield_node = root_node.getChild(NodeCategory.TEXTFIELD.getText());
    Element msg_node = root_node.getChild(NodeCategory.MESSAGE.getText());
    Element button_node = root_node.getChild(NodeCategory.BUTTONTEXT.getText());

    addTextFieldChildrenText(lanTextList, textfield_node);
    addMsgChildrenText(lanTextList, msg_node);
    addButtonChildrenText(lanTextList, button_node);
    return lanTextList;
}