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:com.forum.action.eder.PerfilACT.java

public Document getDocument(String url) {
    SAXBuilder builder = new SAXBuilder();
    Document document = null;//from  www. java  2s  . c o  m
    try {
        document = builder.build(url);
        return document;
    } catch (IOException | JDOMException ex) {
        ex.printStackTrace();
    }

    return null;
}

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

private Document getDocument(String url) {
    SAXBuilder builder = new SAXBuilder();
    Document document = null;// ww w  .  j av a 2s  .c om
    try {
        document = builder.build(url);
        return document;
    } catch (IOException | JDOMException ex) {
        ex.printStackTrace();
    }

    return null;
}

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  w  ww  .  j a v  a  2  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.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  w w. j  a  v  a 2  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.theholywaffle.lolchatapi.LolStatus.java

License:Open Source License

/**
 * This constructor is not intended for usage.
 * /*from   w  w  w . j ava 2 s. c  om*/
 * @param xml
 *            An XML string
 * @throws JDOMException
 *             Is thrown when the xml string is invalid
 * @throws IOException
 *             Is thrown when the xml string is invalid
 */
public LolStatus(String xml) throws JDOMException, IOException {
    outputter.setFormat(outputter.getFormat().setExpandEmptyElements(false));
    final SAXBuilder saxBuilder = new SAXBuilder();
    doc = saxBuilder.build(new StringReader(xml));
    for (final Element e : doc.getRootElement().getChildren()) {
        boolean found = false;
        for (final XMLProperty p : XMLProperty.values()) {
            if (p.name().equals(e.getName())) {
                found = true;
            }
        }
        if (!found) {
            System.err.println(
                    "XMLProperty \"" + e.getName() + "\" value: \"" + e.getValue() + "\" not implemented yet!");
        }
    }
}

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  w  w .j  av a 2  s.  c om
    // 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  ww  .j av  a 2s .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;/*from w  w w  . j a va 2s .  co  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);
    }
}

From source file:com.globalsight.dispatcher.controller.TranslateXLFController.java

License:Apache License

private String parseXLF(JobBO p_job, File p_srcFile) {
    if (p_srcFile == null || !p_srcFile.exists())
        return "File not exits.";

    String srcLang, trgLang;//from w w  w .j a va2 s.  c om
    List<String> srcSegments = new ArrayList<String>();

    try {
        SAXBuilder builder = new SAXBuilder();
        Document read_doc = builder.build(p_srcFile);
        // Get Root Element
        Element root = read_doc.getRootElement();
        Namespace namespace = root.getNamespace();
        Element fileElem = root.getChild("file", namespace);
        // Get Source/Target Language
        srcLang = fileElem.getAttributeValue(XLF_SOURCE_LANGUAGE);
        trgLang = fileElem.getAttributeValue(XLF_TARGET_LANGUAGE);
        XPathFactory xFactory = XPathFactory.instance();
        XPathExpression<Element> expr = xFactory.compile("//trans-unit", Filters.element(), null, namespace);
        List<Element> list = expr.evaluate(fileElem.getChild("body", namespace));
        for (int i = 0; i < list.size(); i++) {
            Element tuElem = (Element) list.get(i);
            Element srcElem = tuElem.getChild("source", namespace);
            // Get Source Segment 
            if (srcElem != null && srcElem.getContentSize() > 0) {
                String source = getInnerXMLString(srcElem);
                srcSegments.add(source);
            }
        }

        p_job.setSourceLanguage(srcLang);
        p_job.setTargetLanguage(trgLang);
        p_job.setSourceSegments(srcSegments);
    } catch (Exception e) {
        String msg = "Parse XLIFF file error.";
        logger.error(msg, e);
        return msg;
    }

    return null;
}

From source file:com.gmapp.comun.LeerPathFromXML.java

public String cargarXml(String tipoPathBuscado) {
    //System.out.println("Buscando path para \"" + tipoPathBuscado + "\" ...");
    String pathBuscado = "";
    //Se crea un SAXBuilder para poder parsear el archivo
    SAXBuilder builder = new SAXBuilder();

    InputStream xmlFile = getClass().getResourceAsStream("/xml/pathFiles.xml");

    try {//w  w w.ja  v a 2 s  .com

        //Se crea el documento a traves del archivo
        Document document = (Document) builder.build(xmlFile);

        //Se obtiene la raiz 'Sistemas'
        Element rootNode = document.getRootElement();

        //Se obtiene la lista de hijos de la raiz 'Sistemas'
        List list = rootNode.getChildren("Sistema");

        //Se recorre la lista de hijos de 'Sistemas'
        for (int i = 0; i < list.size(); i++) {
            //Se obtiene el elemento 'Sistema'
            Element sistema = (Element) list.get(i);

            //Se obtiene el atributo 'nombre' que esta en el tag 'Sistema'
            String nombreSistema = sistema.getAttributeValue("nombre");
            if (SysOper.contains(nombreSistema)) {
                //System.out.println("Sistema: " + nombreSistema );
                //Se obtiene la lista de hijos del tag 'Sistema~nombre '
                List lista_registros = sistema.getChildren();
                //Se recorre la lista de campos
                for (int j = 0; j < lista_registros.size(); j++) {
                    //Se obtiene el elemento 'campo'
                    Element campo = (Element) lista_registros.get(j);
                    //Se obtienen los valores que estan entre los tags '<campo></campo>'
                    //Se obtiene el valor que esta entre los tags '<nombre></nombre>'
                    String nombre = campo.getChildTextTrim("nombrePath");
                    if (nombre.equals(tipoPathBuscado)) {
                        //Se obtiene el valor que esta entre los tags '<valor></valor>'
                        pathBuscado = campo.getChildTextTrim("path");

                        //System.out.println( "\t"+nombre+"\t"+pathBuscado);
                    }
                }
            }
        }
    } catch (IOException io) {
        System.out.println(io.getMessage());
    } catch (JDOMException jdomex) {
        System.out.println(jdomex.getMessage());
    }

    return pathBuscado;
}