Example usage for org.dom4j.io XMLWriter flush

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

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes the underlying Writer

Usage

From source file:fr.gouv.culture.vitam.extract.ExtractInfo.java

License:Open Source License

public static void main(String[] args) {
    if (args.length == 0) {
        System.err.println("need file as target");
        return;// w  w w.java 2  s.  c o  m
    }
    StaticValues.initialize();
    Document document = DocumentFactory.getInstance().createDocument(StaticValues.CURRENT_OUTPUT_ENCODING);
    Element root = DocumentFactory.getInstance().createElement("extractkeywords");
    document.add(root);
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setEncoding(StaticValues.CURRENT_OUTPUT_ENCODING);
    XMLWriter writer = null;
    try {
        writer = new XMLWriter(System.out, format);
    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
        return;
    }
    for (String string : args) {
        File file = new File(string);
        recursive(file, string, root, StaticValues.config, writer);
    }
    if (StaticValues.config.argument.outputModel == VitamOutputModel.OneXML) {
        try {
            writer.write(document);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:gjset.tools.MessageUtils.java

License:Open Source License

/**
 * Useful for debugging, this command pretty prints XML.
 * //from ww w .  j  a va2 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;//from  w  w w.java  2 s  .  c  om

    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.nih.nci.grididloader.Config.java

License:BSD License

/**
 * Serialized the entity mapping to an XML format.
 * @param xmlMappingFile/*from w  ww  .  ja v a  2s  . co 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  av  a 2 s .c om
 * @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:io.mashin.oep.model.Workflow.java

License:Open Source License

@Override
public void write(org.dom4j.Element parent) {
    Document document = parent.getDocument();
    parent.detach();//from w  w w  . j  a  v  a 2s  . c o m

    Element rootElement = document.addElement("workflow-app");
    Element graphicalInfoElement = DocumentHelper.createElement("workflow");

    XMLWriteUtils.writeWorkflowSchemaVersion(getSchemaVersion(), rootElement);
    XMLWriteUtils.writeSLAVersion(this, rootElement);
    XMLWriteUtils.writeTextPropertyAsAttribute(name, rootElement, "name");
    XMLWriteUtils.writePropertiesCollection(parameters, rootElement, "parameters", "property");
    XMLWriteUtils.writeGlobalProperty(global, rootElement);
    XMLWriteUtils.writeCredentialsCollection(credentials, rootElement);

    startNode.write(rootElement);
    for (Node node : nodes) {
        if (!(node.equals(startNode) || node.equals(endNode))) {
            node.write(rootElement);
        }
        graphicalInfoElement.addElement("node").addAttribute("name", node.getName())
                .addAttribute("x", node.getPosition().x + "").addAttribute("y", node.getPosition().y + "");
    }
    endNode.write(rootElement);

    XMLWriteUtils.writeSLAProperty(this, sla, rootElement);

    Comment graphicalInfoNode = null;
    try {
        StringWriter stringWriter = new StringWriter();
        XMLWriter writer = new XMLWriter(stringWriter, OutputFormat.createPrettyPrint());
        writer.write(graphicalInfoElement);
        writer.flush();
        graphicalInfoNode = DocumentHelper.createComment(stringWriter.toString());
    } catch (Exception e) {
        graphicalInfoNode = DocumentHelper.createComment(graphicalInfoElement.asXML());
    }
    document.add(graphicalInfoNode);
}

From source file:io.mashin.oep.parts.WorkflowNodeEditPart.java

License:Open Source License

private void performOpen() {
    if (getCastedModel() instanceof CustomActionNode) {
        CustomActionNode customActionNode = (CustomActionNode) getCastedModel();
        String customActionNodeXML = "";

        try {//from  w w w.  j  a v a2 s  .  co m
            StringWriter stringWriter = new StringWriter();
            XMLWriter writer = new XMLWriter(stringWriter, OutputFormat.createPrettyPrint());
            writer.write(DocumentHelper
                    .parseText((String) customActionNode.getPropertyValue(CustomActionNode.PROP_XML))
                    .getRootElement());
            writer.flush();
            customActionNodeXML = stringWriter.toString();
        } catch (Exception e) {
            e.printStackTrace();
            customActionNodeXML = (String) customActionNode.getPropertyValue(CustomActionNode.PROP_XML);
        }

        XMLEditor.getInstance().open(customActionNode, customActionNodeXML, customActionNode.getName(),
                xml -> getViewer().getEditDomain().getCommandStack()
                        .execute(new CustomActionNodeXMLEditCommand(customActionNode, xml)));
    }
}

From source file:it.eng.qbe.datasource.configuration.dao.fileimpl.CalculatedFieldsDAOFileImpl.java

License:Mozilla Public License

private void guardedWrite(Document document, File file) {
    Writer out;//from  www .  j  av a 2s  .c o  m
    OutputFormat format;
    XMLWriter writer;

    logger.debug("IN");

    out = null;
    writer = null;

    try {

        logger.debug("acquiring lock...");
        getLock();
        logger.debug("Lock acquired");

        out = null;
        try {
            out = new FileWriter(file);
        } catch (IOException e) {
            throw new DAOException("Impossible to open file [" + file + "]", e);
        }
        Assert.assertNotNull(out, "Output stream cannot be null");

        format = OutputFormat.createPrettyPrint();
        format.setEncoding("ISO-8859-1");
        format.setIndent("    ");
        writer = new XMLWriter(out, format);
        try {

            writer.write(document);
            writer.flush();
        } catch (IOException e) {
            throw new DAOException("Impossible to write to file [" + file + "]", e);
        }
    } catch (Throwable t) {
        if (t instanceof DAOException)
            throw (DAOException) t;
        throw new DAOException("An unpredicetd error occurred while writing on file [" + file + "]");
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (IOException e) {
                throw new DAOException("Impossible to properly close stream to file file [" + file + "]", e);
            }
        }
        logger.debug("releasing lock...");
        releaseLock();
        logger.debug("lock released");

        logger.debug("OUT");
    }

}

From source file:it.pdfsam.env.EnvWorker.java

License:Open Source License

/**
 * Saves the environment// w  w w . jav a2 s  .c om
 * 
 */
public void saveJob() {
    try {
        file_chooser.setApproveButtonText(GettextResource.gettext(i18n_messages, "Save job"));
        int return_val = file_chooser.showOpenDialog(null);
        File chosen_file = null;
        if (return_val == JFileChooser.APPROVE_OPTION) {
            chosen_file = file_chooser.getSelectedFile();
            if (chosen_file != null) {
                try {
                    Document document = DocumentHelper.createDocument();
                    Element root = document.addElement("pdfsam_saved_jobs");
                    root.addAttribute("version", MainGUI.NAME);
                    root.addAttribute("savedate", new SimpleDateFormat("dd-MMM-yyyy").format(new Date()));
                    for (int i = 0; i < pl_panel.length; i++) {
                        Element node = (Element) root.addElement("plugin");
                        node.addAttribute("class", pl_panel[i].getClass().getName());
                        node.addAttribute("name", pl_panel[i].getPluginName());
                        pl_panel[i].getJobNode(node);
                        fireLogPropertyChanged(GettextResource.gettext(i18n_messages,
                                pl_panel[i].getPluginName() + " job node loaded."), LogPanel.LOG_DEBUG);
                    }
                    FileWriter file_writer = new FileWriter(chosen_file);
                    OutputFormat format = OutputFormat.createPrettyPrint();
                    XMLWriter xml_file_writer = new XMLWriter(file_writer, format);
                    xml_file_writer.write(document);
                    xml_file_writer.flush();
                    xml_file_writer.close();
                    fireLogPropertyChanged(GettextResource.gettext(i18n_messages, "Job saved."),
                            LogPanel.LOG_INFO);
                } catch (Exception ex) {
                    fireLogPropertyChanged(GettextResource.gettext(i18n_messages, "Error: ") + ex.getMessage(),
                            LogPanel.LOG_ERROR);

                }
            }
        }
    } catch (RuntimeException re) {
        fireLogPropertyChanged(GettextResource.gettext(i18n_messages, "RuntimeError:")
                + " Unable to load environment. " + re.getMessage(), LogPanel.LOG_ERROR);
    } catch (Exception e) {
        fireLogPropertyChanged(GettextResource.gettext(i18n_messages, "Error:")
                + " Unable to load environment. " + e.getMessage(), LogPanel.LOG_ERROR);
    }
}

From source file:it.pdfsam.util.XMLParser.java

License:Open Source License

/**
 * Write the DOM to the xml file//from w w  w  .j  a v  a2  s  .c  o m
 * 
 * @param domDoc Document to write
 * @param full_path Full path to the xml file to write
 * @throws Exception
 */
public static void writeXmlFile(Document domDoc, String full_path) throws Exception {
    FileWriter file_writer = new FileWriter(full_path);
    OutputFormat format = OutputFormat.createPrettyPrint();
    XMLWriter xml_file_writer = new XMLWriter(file_writer, format);
    xml_file_writer.write(domDoc);
    xml_file_writer.flush();
    xml_file_writer.close();
}