Example usage for org.dom4j.io OutputFormat createPrettyPrint

List of usage examples for org.dom4j.io OutputFormat createPrettyPrint

Introduction

In this page you can find the example usage for org.dom4j.io OutputFormat createPrettyPrint.

Prototype

public static OutputFormat createPrettyPrint() 

Source Link

Document

A static helper method to create the default pretty printing format.

Usage

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 a  2s . c om
    }

    // 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 // w ww.  java 2s. c om
 * @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:GnuCash.GnuCashDocument.java

License:Open Source License

public void writeToXML(String filename)
        throws FileNotFoundException, UnsupportedEncodingException, IOException, DocumentException {
    String suffix = "";
    OutputStream out = null;//from w  ww  .j a  va 2s  .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

/**
 * //from w w  w .  ja v  a  2  s .c om
 * 
 * @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/*ww w .j a  v  a2 s.  c om*/
 * @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
 * /*from   w w w  .  jav a  2s.c o  m*/
 * @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./*from ww w. ja  va  2  s. c  o  m*/
 *  
 * @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);
    }
}

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

License:BSD License

/**
 * Render report with paging params/*w  w w  .jav  a 2s  .  com*/
 * @param request
 * @param reportXMLParam
 * @param xsltFilename
 * @param out
 * @param params
 */
public static void renderReportWithParams(HttpServletRequest request, Document reportXMLParam,
        String xsltFilename, JspWriter out, HashMap<String, String> params) {
    File styleSheet = new File(RembrandtContextListener.getContextPath() + "/XSL/" + xsltFilename);
    // load the transformer using JAX
    logger.debug("Applying XSLT with paging " + xsltFilename);
    Transformer transformer;
    Document reportXML;
    try {
        if (reportXMLParam != null)
            reportXML = reportXMLParam;
        else
            reportXML = (Document) request.getSession()
                    .getAttribute(RembrandtConstants.SESSION_ATTR_PATHWAY_XML);

        transformer = new Transformer(styleSheet, params);
        Document transformedDoc = transformer.transform(reportXML);

        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter writer;
        writer = new XMLWriter(out, format);
        writer.write(transformedDoc);

    } catch (UnsupportedEncodingException uee) {
        logger.error("UnsupportedEncodingException");
        logger.error(uee);
    } catch (IOException ioe) {
        logger.error("IOException");
        logger.error(ioe);
    }
}

From source file:gtu._work.etc.HotnoteMakerUI.java

License:Open Source License

private void initGUI() {
    try {//w  w  w. j a v  a  2 s  .c o  m
        ToolTipManager.sharedInstance().setInitialDelay(0);
        BorderLayout thisLayout = new BorderLayout();
        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        getContentPane().setLayout(thisLayout);
        {
            jTabbedPane1 = new JTabbedPane();
            getContentPane().add(jTabbedPane1, BorderLayout.CENTER);
            {
                jPanel1 = new JPanel();
                BorderLayout jPanel1Layout = new BorderLayout();
                jPanel1.setLayout(jPanel1Layout);
                jTabbedPane1.addTab("hott notes - checklist", null, jPanel1, null);
                {
                    jScrollPane1 = new JScrollPane();
                    jPanel1.add(jScrollPane1, BorderLayout.CENTER);
                    jScrollPane1.setPreferredSize(new java.awt.Dimension(612, 348));
                    {
                        checkListArea = new JTextArea();
                        jScrollPane1.setViewportView(checkListArea);
                        checkListArea.addMouseListener(new MouseAdapter() {

                            String randomColor() {
                                StringBuilder sb = new StringBuilder().append("#");
                                for (int ii = 0; ii < 6; ii++) {
                                    sb.append(RandomUtil.randomChar('a', 'b', 'c', 'd', 'f', '0', '1', '2', '3',
                                            '4', '5', '6', '7', '8', '9'));
                                }
                                return sb.toString();
                            }

                            void saveXml(Document document, File file) {
                                OutputFormat format = OutputFormat.createPrettyPrint();
                                format.setEncoding("utf-16");
                                XMLWriter writer = null;
                                try {
                                    writer = new XMLWriter(new FileWriter(file), format);
                                    writer.write(document);
                                } catch (IOException e) {
                                    JCommonUtil.handleException(e);
                                } finally {
                                    if (writer != null) {
                                        try {
                                            writer.close();
                                        } catch (IOException e) {
                                            JCommonUtil.handleException(e);
                                        }
                                    }
                                }
                            }

                            public void mouseClicked(MouseEvent evt) {
                                if (!JMouseEventUtil.buttonLeftClick(2, evt)) {
                                    return;
                                }

                                if (StringUtils.isEmpty(checkListArea.getText())) {
                                    JCommonUtil
                                            ._jOptionPane_showMessageDialog_error("checklist area is empty!");
                                    return;
                                }

                                File file = JCommonUtil._jFileChooser_selectFileOnly_saveFile();
                                if (file == null) {
                                    JCommonUtil._jOptionPane_showMessageDialog_error("file is not correct!");
                                    return;
                                }

                                //XXX
                                StringTokenizer tok = new StringTokenizer(checkListArea.getText(), "\t\n\r\f");
                                List<String> list = new ArrayList<String>();
                                String tmp = null;
                                for (; tok.hasMoreElements();) {
                                    tmp = ((String) tok.nextElement()).trim();
                                    System.out.println(tmp);
                                    list.add(tmp);
                                }
                                //XXX

                                Document document = DocumentHelper.createDocument();
                                Element rootHot = document.addElement("hottnote");
                                rootHot.addAttribute("creationtime",
                                        new Timestamp(System.currentTimeMillis()).toString());
                                rootHot.addAttribute("lastmodified",
                                        new Timestamp(System.currentTimeMillis()).toString());
                                rootHot.addAttribute("type", "checklist");
                                //appearence
                                Element appearenceE = rootHot.addElement("appearence");
                                appearenceE.addAttribute("alpha", "204");
                                Element fontE = appearenceE.addElement("font");
                                fontE.addAttribute("face", "Default");
                                fontE.addAttribute("size", "0");
                                Element styleE = appearenceE.addElement("style");
                                styleE.addElement("bg2color").addAttribute("color", randomColor());
                                styleE.addElement("bgcolor").addAttribute("color", randomColor());
                                styleE.addElement("textcolor").addAttribute("color", randomColor());
                                styleE.addElement("titlecolor").addAttribute("color", randomColor());
                                //behavior
                                rootHot.addElement("behavior");
                                //content
                                Element contentE = rootHot.addElement("content");
                                Element checklistE = contentE.addElement("checklist");
                                for (String val : list) {
                                    checklistE.addElement("item").addCDATA(val);
                                }
                                //desktop
                                Element desktopE = rootHot.addElement("desktop");
                                desktopE.addElement("position").addAttribute("x", RandomUtil.numberStr(3))
                                        .addAttribute("y", RandomUtil.numberStr(3));
                                desktopE.addElement("size").addAttribute("height", "200").addAttribute("width",
                                        "200");
                                //title
                                Element titleE = rootHot.addElement("title");
                                titleE.addCDATA(StringUtils.defaultIfEmpty(checkListTitle.getText(),
                                        DateFormatUtils.format(System.currentTimeMillis(), "dd/MM/yyyy")));

                                if (!file.getName().toLowerCase().endsWith(".hottnote")) {
                                    file = new File(file.getParentFile(), file.getName() + ".hottnote");
                                }

                                saveXml(document, file);
                                JCommonUtil._jOptionPane_showMessageDialog_info("completed!\n" + file);
                            }
                        });
                    }
                }
                {
                    checkListTitle = new JTextField();
                    checkListTitle.setToolTipText("title");
                    jPanel1.add(checkListTitle, BorderLayout.NORTH);
                }
            }
        }
        pack();
        this.setSize(633, 415);
    } catch (Exception e) {
        //add your error handling code here
        e.printStackTrace();
    }
}

From source file:hebbNet.HebbNet.java

License:Open Source License

@Override
public void exportToFile(File saveFile) {
    String extension = FrevoMain.getExtension(saveFile);
    if (extension.equals("net")) {
        System.out.println("Exporting Pajek network file to " + saveFile.getName());
        try {/* www  .ja v a  2 s .com*/
            // Create file
            FileWriter fstream = new FileWriter(saveFile);
            BufferedWriter out = new BufferedWriter(fstream);
            out.write("*Vertices " + this.nodes);
            out.newLine();
            // input neurons
            for (int i = 1; i < input_nodes + 1; i++) {
                out.write(i + " \"I" + i + "\"");
                out.newLine();
            }
            for (int h = input_nodes + 1; h < nodes - output_nodes + 1; h++) {
                out.write(h + " \"H" + (h - input_nodes) + "\"");
                out.newLine();
            }
            int a = 1;
            for (int o = nodes - output_nodes + 1; o < nodes + 1; o++) {
                out.write(o + " \"O" + a + "\"");
                out.newLine();
                a++;
            }

            // Edges
            out.write("*Edges");
            out.newLine();
            for (int n = 0; n < input_nodes - 1; n++) {
                for (int p = n + 1; p < input_nodes; p++) {
                    if (n != p) {
                        out.write((n + 1) + " " + (p + 1) + " " + 0);
                        out.newLine();
                    }
                }
            }

            for (int n = input_nodes; n < nodes; n++) {
                for (int from = 0; from < nodes; from++) {
                    out.write((n + 1) + " " + (from + 1) + " " + weight[from][n]);
                    // out.write((n+1)+" "+(from+1)+" "+plasticity[from][n]);
                    out.newLine();
                }
            }

            // Close the output stream
            out.close();
        } catch (Exception e) {
            System.err.println("Error: " + e.getMessage());
        }
    } else if (extension.equals("xml")) {
        System.out.println("Saving to XML");

        Document doc = DocumentHelper.createDocument();
        doc.addDocType("HebbNet", null,
                System.getProperty("user.dir") + "//Components//Representations//HebbNet//src//HebbNet.dtd");
        Element cnetwork = doc.addElement("HebbNet");
        this.exportToXmlElement(cnetwork);

        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setLineSeparator(System.getProperty("line.separator"));

        try {
            saveFile.createNewFile();
            FileWriter out = new FileWriter(saveFile);
            BufferedWriter bw = new BufferedWriter(out);
            XMLWriter wr = new XMLWriter(bw, format);
            wr.write(doc);
            wr.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}