Example usage for org.dom4j.io XMLWriter write

List of usage examples for org.dom4j.io XMLWriter write

Introduction

In this page you can find the example usage for org.dom4j.io XMLWriter write.

Prototype

public void write(Object object) throws IOException 

Source Link

Document

Writes the given object which should be a String, a Node or a List of Nodes.

Usage

From source file:gestionecassa.backends.XmlDataBackend.java

License:Open Source License

@Override
public void saveAdminsList(Collection<Admin> lista) throws IOException {

    Document document = DocumentHelper.createDocument();
    Element root = document.addElement("admins");

    for (Admin admin : lista) {
        Element tempAdmin = root.addElement("admin");
        tempAdmin.addElement("id").addText(admin.getId() + "");
        tempAdmin.addElement("username").addText(admin.getUsername());
        tempAdmin.addElement("password").addText(admin.getPassword());
    }// w ww .  java2s  .c o m

    // for debug purposes
    OutputFormat format = OutputFormat.createPrettyPrint();

    // lets write to a file
    XMLWriter writer = new XMLWriter(new FileWriter(AdminListFile), format);
    //XMLWriter writer = new XMLWriter(new FileWriter(fileName));
    writer.write(document);
    writer.close();
}

From source file:gestionecassa.backends.XmlDataBackend.java

License:Open Source License

@Override
public void saveCassiereList(Collection<Cassiere> lista) throws IOException {

    Document document = DocumentHelper.createDocument();
    Element root = document.addElement("cassieri");

    for (Cassiere cassiere : lista) {
        Element tempCassiere = root.addElement("cassiere");
        tempCassiere.addElement("id").addText(cassiere.getId() + "");
        tempCassiere.addElement("username").addText(cassiere.getUsername());
        tempCassiere.addElement("password").addText(cassiere.getPassword());
    }/*from  ww  w  .j  a  v a 2s . co  m*/

    // for debug purposes
    OutputFormat format = OutputFormat.createPrettyPrint();

    // lets write to a file
    XMLWriter writer = new XMLWriter(new FileWriter(CassiereListFile), format);
    //XMLWriter writer = new XMLWriter(new FileWriter(fileName));
    writer.write(document);
    writer.close();
}

From source file:gestionecassa.backends.XmlDataBackend.java

License:Open Source License

@Override
public void saveListOfOrders(String id, Collection<Order> list) throws IOException {

    String fileName = xmlDataPath + id + ".xml";

    Document document = DocumentHelper.createDocument();
    Element root = document.addElement("orders");

    for (Order order : list) {
        addOrderToElement(root, order);//from  w  w  w  . j  a  v a2s  .c o m
    }

    // for debug purposes
    OutputFormat format = OutputFormat.createPrettyPrint();

    // lets write to a file
    XMLWriter writer = new XMLWriter(new FileWriter(fileName), format);
    //XMLWriter writer = new XMLWriter(new FileWriter(fileName));
    writer.write(document);
    writer.close();
}

From source file:gestionecassa.XmlPreferencesHandler.java

License:Open Source License

/**
 * Saves options to a file given by the option type
 * @param preferences /*from   w  ww .ja v a  2s.  c  o  m*/
 * @throws IOException
 */
public void savePrefs(DataType preferences) throws IOException {

    Document document = DocumentHelper.createDocument();
    Element root = document.addElement("config");
    root.addAttribute("version", preferences.getVersion());
    root.addAttribute("application", preferences.getApplication());

    for (Field field : preferences.getClass().getFields()) {
        try {
            root.addElement(field.getName()).addText(field.get(preferences) + "");
        } catch (IllegalArgumentException ex) {
            logger.warn("campo sbagliato", ex);
        } catch (IllegalAccessException ex) {
            logger.warn("campo sbagliato", ex);
        }
    }

    // lets write to a file
    OutputFormat format = OutputFormat.createPrettyPrint();
    XMLWriter writer = new XMLWriter(new FileWriter(preferences.getFileName()), format);
    writer.write(document);
    writer.close();
}

From source file:gjset.tools.MessageUtils.java

License:Open Source License

/**
 * Useful for debugging, this command pretty prints XML.
 * //from w  w w  .j  a v a2  s. c  om
 * @param element
 * @return
 */
public static String prettyPrint(Element element) {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    XMLWriter writer;
    try {
        writer = new XMLWriter(stream);
        writer.write(element);
        writer.flush();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return stream.toString();
}

From source file:GnuCash.GnuCashDocument.java

License:Open Source License

public void writeToXML(String filename)
        throws FileNotFoundException, UnsupportedEncodingException, IOException, DocumentException {
    String suffix = "";
    OutputStream out = null;//www  .ja v a2 s.c  o  m

    OutputFormat outformat = OutputFormat.createPrettyPrint();
    outformat.setEncoding("UTF-8");

    setBook();

    //should we save as copy?
    //expect explicit TRUE for safety
    if (!Settings.getInstance().get("jPortfolioView", "file", "saveAsCopy").equals("false")) {
        suffix = ".copy";
    }

    out = new FileOutputStream(filename.concat(suffix));

    //should we compress the file?
    if (Settings.getInstance().get("jPortfolioView", "file", "compressFile").equals("true")) {
        out = new GZIPOutputStream(out);
    }

    XMLWriter writer = new XMLWriter(out, outformat);
    writer.write(book.getDocument());
    writer.flush();

    if (out instanceof GZIPOutputStream) {
        ((GZIPOutputStream) out).finish();
    }
    modified = false;
}

From source file:gov.guilin.util.SettingUtils.java

License:Open Source License

/**
 * //  ww w . j  av  a  2s  .co m
 * 
 * @param setting
 *            
 */
public static void set(Setting setting) {
    try {
        File guilinXmlFile = new ClassPathResource(CommonAttributes.XML_PATH).getFile();
        Document document = new SAXReader().read(guilinXmlFile);
        List<Element> elements = document.selectNodes("/guilin/setting");
        for (Element element : elements) {
            try {
                String name = element.attributeValue("name");
                String value = beanUtils.getProperty(setting, name);
                Attribute attribute = element.attribute("value");
                attribute.setValue(value);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        }

        FileOutputStream fileOutputStream = null;
        XMLWriter xmlWriter = null;
        try {
            OutputFormat outputFormat = OutputFormat.createPrettyPrint();
            outputFormat.setEncoding("UTF-8");
            outputFormat.setIndent(true);
            outputFormat.setIndent("   ");
            outputFormat.setNewlines(true);
            fileOutputStream = new FileOutputStream(guilinXmlFile);
            xmlWriter = new XMLWriter(fileOutputStream, outputFormat);
            xmlWriter.write(document);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (xmlWriter != null) {
                try {
                    xmlWriter.close();
                } catch (IOException e) {
                }
            }
            IOUtils.closeQuietly(fileOutputStream);
        }

        Ehcache cache = cacheManager.getEhcache(Setting.CACHE_NAME);
        cache.put(new net.sf.ehcache.Element(Setting.CACHE_KEY, setting));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:gov.nih.nci.grididloader.Config.java

License:BSD License

/**
 * Serialized the entity mapping to an XML format.
 * @param xmlMappingFile/*from   ww  w .j  ava  2 s .  c o  m*/
 * @throws Exception
 */
public void saveXMLMapping(String xmlMappingFile) throws Exception {

    Document doc = DocumentFactory.getInstance().createDocument();
    Element mapping = doc.addElement("mapping");
    String mappingPackage = null;

    for (BigEntity entity : entities) {
        String packageName = entity.getPackageName();
        String className = entity.getClassName();

        if (mappingPackage == null) {
            mappingPackage = packageName;
        } else if (!mappingPackage.equals(packageName)) {
            System.err.println("ERROR: inconsistent package, " + mappingPackage + " != " + packageName);
        }

        // create entity
        Element entityElement = mapping.addElement("entity").addAttribute("class", className)
                .addAttribute("table", entity.getTableName());
        entityElement.addElement("primary-key").addText(entity.getPrimaryKey());
        Element logicalElement = entityElement.addElement("logical-key");

        // add joined attributes
        Map<String, String> seenAttrs = new HashMap<String, String>();
        Collection<Join> joins = entity.getJoins();
        for (Join join : joins) {
            if (join instanceof TableJoin) {
                TableJoin tableJoin = (TableJoin) join;
                for (String attr : tableJoin.getAttributes()) {
                    logicalElement.addElement("property").addAttribute("table", tableJoin.getForeignTable())
                            .addAttribute("primary-key", tableJoin.getForeignTablePK())
                            .addAttribute("foreign-key", tableJoin.getForeignKey()).addText(attr);
                    seenAttrs.put(attr, null);
                }
            } else {
                EntityJoin entityJoin = (EntityJoin) join;
                logicalElement.addElement("property")
                        .addAttribute("entity", entityJoin.getEntity().getClassName())
                        .addAttribute("foreign-key", entityJoin.getForeignKey());
            }
        }

        // add all the leftover non-joined attributes
        for (String attr : entity.getAttributes()) {
            if (!seenAttrs.containsKey(attr)) {
                logicalElement.addElement("property").addText(attr);
            }
        }
    }

    mapping.addAttribute("package", mappingPackage);

    // write to file
    OutputFormat outformat = OutputFormat.createPrettyPrint();
    XMLWriter writer = new XMLWriter(new FileWriter(xmlMappingFile), outformat);
    writer.write(doc);
    writer.flush();
}

From source file:gov.nih.nci.rembrandt.web.helper.ReportGeneratorHelper.java

License:BSD License

/**
 * This method will take the class variable ReportBean _reportBean and 
 * create the correct XML representation for the desired view of the results.  When
 * completed it adds the XML to the _reportBean and drops the _reportBean
 * into the sessionCache for later retrieval when needed
 * /*  w w w . j  a  v  a 2s . com*/
 * @throws IllegalStateException this is thrown when there is no resultant
 * found in _reportBean
 */
private void generateReportXML() throws IllegalStateException {

    /*
     * Get the correct report XML generator for the desired view
     * of the results.
     * 
     */
    Document reportXML = null;
    if (_reportBean != null) {
        /*
         * We need to check the resultant to make sure that
         * the database has actually return something for the associated
         * query or filter.
         */
        Resultant resultant = _reportBean.getResultant();
        if (resultant != null) {
            try {
                Viewable oldView = resultant.getAssociatedView();
                //make sure old view is not null, if so, set it to the same as new view.
                if (oldView == null) {
                    oldView = _cQuery.getAssociatedView();
                }
                Viewable newView = _cQuery.getAssociatedView();
                Map filterParams = _reportBean.getFilterParams();
                /*
                 * Make sure that we change the view on the resultSet
                 * if the user changes the desired view from already
                 * stored view of the results
                 */
                if (!oldView.equals(newView) || _reportBean.getReportXML() == null) {
                    //we must generate a new XML document for the
                    //view they want
                    logger.debug("Generating XML");
                    ReportGenerator reportGen = ReportGeneratorFactory.getReportGenerator(newView);
                    resultant.setAssociatedView(newView);
                    reportXML = reportGen.getReportXML(resultant, filterParams);
                    logger.debug("Completed Generating XML");
                } else {
                    //Old view is the current view
                    logger.debug("Fetching report XML from reportBean");
                    reportXML = _reportBean.getReportXML();
                }
            } catch (NullPointerException npe) {
                logger.error("The resultant has a null value for something that was needed");
                logger.error(npe);
            }
        }

        //XML Report Logging
        if (xmlLogging) {
            try {
                StringWriter out = new StringWriter();
                OutputFormat outformat = OutputFormat.createPrettyPrint();
                XMLWriter writer = new XMLWriter(out, outformat);
                writer.write(reportXML);
                writer.flush();
                xmlLogger.debug(out.getBuffer());
            } catch (IOException ioe) {
                logger.error("There was an error writing the XML to log");
                logger.error(ioe);
            } catch (NullPointerException npe) {
                logger.debug("There is no XML to log!");
            }
        }
        _reportBean.setReportXML(reportXML);
        if (newQueryName) {//it's a new report bean
            presentationTierCache.addNonPersistableToSessionCache(_sessionId, "previewResultsBySample",
                    _reportBean);
        } else
            presentationTierCache.addNonPersistableToSessionCache(_sessionId, _queryName, _reportBean);

    } else {
        throw new IllegalStateException("There is no resultant to create report");
    }
}

From source file:gov.nih.nci.rembrandt.web.helper.ReportGeneratorHelper.java

License:BSD License

/**
 * This static method will render a query report of the passed reportXML, in
 * HTML using the XSLT whose name has been passed, to the jsp whose 
 * jspWriter has been passed. The request is used to acquire any filter 
 * params that may have been added to the request and that may be applicable
 * to the XSLT./* ww  w .  ja v  a2 s .  c  om*/
 *  
 * @param request --the request that will contain any parameters you want applied
 * to the XSLT that you specify
 * @param reportXML -- this is the XML that you want transformed to HTML
 * @param xsltFilename --this the XSLT that you want to use
 * @param out --the JSPWriter you want the transformed document to go to...
 */
public static void renderReport(HttpServletRequest request, Document reportXML, String xsltFilename,
        JspWriter out, String isIGV) {
    File styleSheet = new File(RembrandtContextListener.getContextPath() + "/XSL/" + xsltFilename);
    // load the transformer using JAX
    logger.debug("Applying XSLT " + xsltFilename);

    Transformer transformer;
    try {

        // if the xsltFiname is pathway xlst, then do this
        if ((xsltFilename.equals(RembrandtConstants.DEFAULT_PATHWAY_XSLT_FILENAME))
                || (xsltFilename.equals(RembrandtConstants.DEFAULT_PATHWAY_DESC_XSLT_FILENAME))
                || (xsltFilename.equals(RembrandtConstants.DEFAULT_GENE_XSLT_FILENAME))) {
            transformer = new Transformer(styleSheet);
        }
        // otherwise do this

        else {
            transformer = new Transformer(styleSheet,
                    (HashMap) request.getAttribute(RembrandtConstants.FILTER_PARAM_MAP));
        }

        Document transformedDoc = transformer.transform(reportXML);

        /*
         * right now this assumes that we will only have one XSL for CSV
         * and it checks for that as we do not want to "pretty print" the CSV, we
         * only want to spit it out as a string, or formatting gets messed up
         * we will of course want to pretty print the XHTML for the graphical reports
         * later we can change this to handle mult XSL CSVs
         * RCL
         */
        if (!xsltFilename.equals(RembrandtConstants.DEFAULT_XSLT_CSV_FILENAME)) {
            OutputFormat format = OutputFormat.createPrettyPrint();
            XMLWriter writer;
            writer = new XMLWriter(out, format);
            writer.write(transformedDoc);
            if (!xsltFilename.equals(RembrandtConstants.DEFAULT_PATHWAY_DESC_XSLT_FILENAME)) {
                //writer.close();
            }
        } else {
            String csv = transformedDoc.getStringValue();
            csv.trim();
            if (isIGV != null && isIGV.equals("true")) {
                csv = csv.replaceAll(",\\s+", "\t");
            }
            out.println(csv);
        }
    } catch (UnsupportedEncodingException uee) {
        logger.error("UnsupportedEncodingException");
        logger.error(uee);
    } catch (IOException ioe) {
        logger.error("IOException");
        logger.error(ioe);
    }
}