Example usage for org.jdom2.input SAXBuilder build

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

Introduction

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

Prototype

@Override
public Document build(final String systemId) throws JDOMException, IOException 

Source Link

Document

This builds a document from the supplied URI.

Usage

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  ww.  jav  a  2 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 {/*ww  w .ja  v a2  s.c  om*/
        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;//  ww w  .  j a va  2  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 o m
            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.search.services.cores.SolrCoreServiceImpl.java

License:Apache License

/**
 * Create/update the schema.xml file for the given core according to the core definition.
 *
 * @param engine the engine configuration
 *//*  w  ww  .  j  a  v a 2s .  c  o m*/
private void createSchemaXml(SolrCoreConfiguration engine) throws MarmottaException {
    log.info("generating schema.xml for search program {}", engine.getName());

    SAXBuilder parser = new SAXBuilder(XMLReaders.NONVALIDATING);
    File schemaTemplate = new File(getCoreDirectory(engine.getName()),
            "conf" + File.separator + "schema-template.xml");
    File schemaFile = new File(getCoreDirectory(engine.getName()), "conf" + File.separator + "schema.xml");
    try {
        Document doc = parser.build(schemaTemplate);

        Element schemaNode = doc.getRootElement();
        Element fieldsNode = schemaNode.getChild("fields");
        if (!schemaNode.getName().equals("schema") || fieldsNode == null)
            throw new MarmottaException(schemaTemplate + " is an invalid SOLR schema file");

        schemaNode.setAttribute("name", engine.getName());

        Program<Value> program = engine.getProgram();

        for (FieldMapping<?, Value> fieldMapping : program.getFields()) {
            String fieldName = fieldMapping.getFieldName();
            String solrType = null;
            try {
                solrType = solrProgramService.getSolrFieldType(fieldMapping.getFieldType().toString());
            } catch (MarmottaException e) {
                solrType = null;
            }
            if (solrType == null) {
                log.error("field {} has an invalid field type; ignoring field definition", fieldName);
                continue;
            }

            Element fieldElement = new Element("field");
            fieldElement.setAttribute("name", fieldName);
            fieldElement.setAttribute("type", solrType);
            // Set the default properties
            fieldElement.setAttribute("stored", "true");
            fieldElement.setAttribute("indexed", "true");
            fieldElement.setAttribute("multiValued", "true");

            // FIXME: Hardcoded Stuff!
            if (solrType.equals("location")) {
                fieldElement.setAttribute("indexed", "true");
                fieldElement.setAttribute("multiValued", "false");
            }

            // Handle extra field configuration
            final Map<String, String> fieldConfig = fieldMapping.getFieldConfig();
            if (fieldConfig != null) {
                for (Map.Entry<String, String> attr : fieldConfig.entrySet()) {
                    if (SOLR_FIELD_OPTIONS.contains(attr.getKey())) {
                        fieldElement.setAttribute(attr.getKey(), attr.getValue());
                    }
                }
            }
            fieldsNode.addContent(fieldElement);

            if (fieldConfig != null && fieldConfig.keySet().contains(SOLR_COPY_FIELD_OPTION)) {
                String[] copyFields = fieldConfig.get(SOLR_COPY_FIELD_OPTION).split("\\s*,\\s*");
                for (String copyField : copyFields) {
                    if (copyField.trim().length() > 0) { // ignore 'empty' fields
                        Element copyElement = new Element("copyField");
                        copyElement.setAttribute("source", fieldName);
                        copyElement.setAttribute("dest", copyField.trim());
                        schemaNode.addContent(copyElement);
                    }
                }
            } else {
                Element copyElement = new Element("copyField");
                copyElement.setAttribute("source", fieldName);
                copyElement.setAttribute("dest", "lmf.text_all");
                schemaNode.addContent(copyElement);
            }

            //for suggestions, copy all fields to lmf.spellcheck (used for spellcheck and querying);
            //only facet is a supported type at the moment
            if (fieldConfig != null && fieldConfig.keySet().contains(SOLR_SUGGESTION_FIELD_OPTION)) {
                String suggestionType = fieldConfig.get(SOLR_SUGGESTION_FIELD_OPTION);
                if (suggestionType.equals("facet")) {
                    Element copyElement = new Element("copyField");
                    copyElement.setAttribute("source", fieldName);
                    copyElement.setAttribute("dest", "lmf.spellcheck");
                    schemaNode.addContent(copyElement);
                } else {
                    log.error("suggestionType " + suggestionType + " not supported");
                }
            }
        }

        if (!schemaFile.exists() || schemaFile.canWrite()) {
            FileOutputStream out = new FileOutputStream(schemaFile);

            XMLOutputter xo = new XMLOutputter(Format.getPrettyFormat().setIndent("    "));
            xo.output(doc, out);
            out.close();
        } else {
            log.error("schema file {} is not writable", schemaFile);
        }

    } catch (JDOMException e) {
        throw new MarmottaException("parse error while parsing SOLR schema template file " + schemaTemplate, e);
    } catch (IOException e) {
        throw new MarmottaException("I/O error while parsing SOLR schema template file " + schemaTemplate, e);
    }

}

From source file:at.newmedialab.lmf.search.services.cores.SolrCoreServiceImpl.java

License:Apache License

/**
 * Create/update the solrconfig.xml file for the given core according to the core configuration.
 *
 * @param engine the solr core configuration
 *//*  w  w w  . j av a 2s.  c  o m*/
private void createSolrConfigXml(SolrCoreConfiguration engine) throws MarmottaException {
    File configTemplate = new File(getCoreDirectory(engine.getName()),
            "conf" + File.separator + "solrconfig-template.xml");
    File configFile = new File(getCoreDirectory(engine.getName()), "conf" + File.separator + "solrconfig.xml");

    try {
        SAXBuilder parser = new SAXBuilder(XMLReaders.NONVALIDATING);
        Document solrConfig = parser.build(configTemplate);

        FileOutputStream out = new FileOutputStream(configFile);

        // Configure suggestion service: add fields to suggestion handler
        Program<Value> program = engine.getProgram();
        for (Element handler : solrConfig.getRootElement().getChildren("requestHandler")) {
            if (handler.getAttribute("class").getValue().equals(SuggestionRequestHandler.class.getName())) {
                for (Element lst : handler.getChildren("lst")) {
                    if (lst.getAttribute("name").getValue().equals("defaults")) {
                        //set suggestion fields
                        for (FieldMapping<?, Value> fieldMapping : program.getFields()) {

                            String fieldName = fieldMapping.getFieldName();
                            final Map<String, String> fieldConfig = fieldMapping.getFieldConfig();

                            if (fieldConfig != null
                                    && fieldConfig.keySet().contains(SOLR_SUGGESTION_FIELD_OPTION)) {
                                String suggestionType = fieldConfig.get(SOLR_SUGGESTION_FIELD_OPTION);
                                if (suggestionType.equals("facet")) {
                                    Element field_elem = new Element("str");
                                    field_elem.setAttribute("name", SuggestionRequestParams.SUGGESTION_FIELD);
                                    field_elem.setText(fieldName);
                                    lst.addContent(field_elem);
                                } else {
                                    log.error("suggestionType " + suggestionType + " not supported");
                                }
                            }
                        }
                    }
                }
            }
        }

        XMLOutputter xo = new XMLOutputter(Format.getPrettyFormat().setIndent("    "));
        xo.output(solrConfig, out);
        out.close();
    } catch (JDOMException e) {
        throw new MarmottaException("parse error while parsing SOLR schema template file " + configTemplate, e);
    } catch (IOException e) {
        throw new MarmottaException("I/O error while parsing SOLR schema template file " + configTemplate, e);
    }
}

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.
 *///w w w .j  a v  a  2 s  .co m
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:ataraxis.passwordmanager.XMLHandler.java

License:Open Source License

/**
 * Load the Passwords from a XML File./*  w  w w .  ja v a  2  s .com*/
 *
 * @throws StorageException if an error occurs
 */
public void loadPasswords() throws StorageException {
    try {
        // Build document with on-the-fly decryption
        SAXBuilder xmlReader = new SAXBuilder(XMLReaders.NONVALIDATING);

        InputStream inStream = getAccountFileInputStream();
        s_doc = xmlReader.build(inStream);
        inStream.close();

        // set root Element of Document
        s_rootElement = s_doc.getRootElement();
    } catch (JDOMException e) {
        logger.fatal(e);
        throw new StorageException(e);
    } catch (IOException e) {
        logger.fatal(e);
        throw new StorageException(e);
    }
}

From source file:backtesting.BackTesterNinety.java

public static boolean CheckBacktestSettingsInCache(LocalDate startDate, LocalDate endDate) {
    try {//  ww  w.  ja v  a2s.  c o  m
        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 {/*from  ww w. j a  v  a2  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;
}