Example usage for org.dom4j.io XMLWriter close

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

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes the underlying Writer

Usage

From source file:org.nuclos.server.transfer.ejb3.XmlExportFacadeBean.java

License:Open Source License

/**
 *
 * @param exportEntities//from  w w w  . j a  v  a2 s .co  m
 *            map of ids and entitynames to export
 * @return Zip File with Xml output and Document files
 * @throws IOException
 * @throws CommonPermissionException
 * @throws CommonFinderException
 * @throws CreateException
 * @throws CommonCreateException
 * @throws NuclosBusinessRuleException
 * @throws Exception
 * @jboss.method-attributes read-only = "true"
 */
public org.nuclos.common2.File xmlExport(Map<Integer, String> exportEntities, boolean deepexport,
        boolean withDependants, String sFileName) throws CommonFinderException, CommonPermissionException,
        IOException, CommonCreateException, NuclosBusinessRuleException {

    today = new Date();
    dateFormat = new SimpleDateFormat("dd.MM.yyy HH:mm:ss");
    iActionNumber = 1;

    // List of exported Ids
    exportedIds = new ArrayList<Pair<String, Integer>>();

    // map of subforms with their foreign keys of the entities
    mpGoSubFormsWithForeignKeys = new HashMap<Integer, Map<EntityAndFieldName, String>>();
    mpMdSubFormsWithForeignKeys = new HashMap<String, Map<EntityAndFieldName, String>>();

    // create and clear export dirs
    File expimpDir = NuclosSystemParameters.getDirectory(NuclosSystemParameters.EXPORT_IMPORT_PATH);
    if (!expimpDir.exists()) {
        expimpDir.mkdir();
    }
    File expimpTimestampDir = new File(expimpDir, "" + today.getTime());
    expimpTimestampDir.mkdir();
    try {
        File expimpTsResourceDir = new File(expimpTimestampDir, "ressource");
        expimpTsResourceDir.mkdir();

        Set<Integer> stExportId = exportEntities.keySet();

        // create XML Document and Header
        Document document = DocumentHelper.createDocument();
        Element header = document.addElement("nucleusXmlExport");
        header.addAttribute("version",
                ApplicationProperties.getInstance().getNuclosVersion().getVersionNumber());
        header.addAttribute("date", dateFormat.format(today));
        String sRootEntity = "";
        if (!stExportId.isEmpty()) {
            sRootEntity = exportEntities.get(stExportId.toArray()[0]);
        }
        header.addAttribute("rootentity", sRootEntity);
        header.addAttribute("deepexport", Boolean.toString(deepexport));

        info("Begin Export: user [" + getCurrentUserName() + "] date [" + today + "] entity [" + sRootEntity
                + "]");
        iProtocolId = getProtocolFacade().writeExportImportLogHeader(XmlExportImportHelper.EXPIMP_TYPE_EXPORT,
                getCurrentUserName(), today, sRootEntity, sFileName);

        //         // special handling for elisa, that means the following:
        //         // deep export = main data + subform data will be exported
        //         // no deep export = only main data will be exported
        //         if (deepexport) {
        //            bElisaDeepExport = true;
        //            deepexport = false;
        //         }
        //         else {
        //            bElisaDeepExport = false;
        //         }

        for (Integer iExportId : stExportId) {
            // call recursive XML Helper Method
            xmlExportHelper(exportEntities.get(iExportId), iExportId, header, deepexport, withDependants, true);
        }

        try {
            // write XML File
            final OutputFormat format = OutputFormat.createPrettyPrint();
            format.setTrimText(false);
            format.setEncoding("UTF-8");

            final File fExport = new File(expimpTimestampDir.getPath() + "/export.xml");
            final Writer osr = new BufferedWriter(
                    new OutputStreamWriter(new FileOutputStream(fExport), "UTF-8"));
            final XMLWriter writer = new XMLWriter(osr, format);
            try {
                writer.write(document);
            } finally {
                writer.close();
            }
            // activate the following code, if you want to save the exported file in the database
            // NOTE: it is recommended to compress the stored data
            //xmlExportImportProtocol.addXmlFile(iProtocolId, IOUtils.readFromTextFile(fExport, "UTF-8"));
        } catch (IOException e) {
            throw new IOException("xmlexport.error.creating.file", e);
            //"Fehler beim erstellen der XML-Export-Datei aufgetreten: "+e);
        }

        try {
            // Zip Export Files
            XmlExportImportHelper.zipFolder(expimpTimestampDir, "nucleus_export.zip");
        } catch (Exception e) {
            throw new NuclosFatalException("xmlexport.error.creating.zipfile", e);
            //"Fehler beim erstellen der ZIP-Export-Datei aufgetreten: "+e);
        }

        // create serializeable File from Zip
        org.nuclos.common2.File transfile = XmlExportImportHelper
                .createFile(expimpTimestampDir.getAbsolutePath(), "nucleus_export.zip");

        getProtocolFacade().addFile(iProtocolId, transfile.getContents());

        info("END Export");

        return transfile;
    } finally {
        // delete export dir
        XmlExportImportHelper.deleteDir(expimpTimestampDir);
    }
}

From source file:org.nuxeo.ecm.core.io.impl.plugins.XMLDirectoryWriter.java

License:Apache License

@Override
public DocumentTranslationMap write(ExportedDocument doc) throws IOException {

    File file = new File(getDestination() + File.separator + doc.getPath().toString());
    if (!file.mkdirs()) {
        throw new IOException("Cannot create target directory: " + file.getAbsolutePath());
    }//from   w w w . j a  va2 s  . c o m
    OutputFormat format = AbstractDocumentWriter.createPrettyPrint();
    XMLWriter writer = null;
    try {
        writer = new XMLWriter(new FileOutputStream(file.getAbsolutePath() + File.separator + "document.xml"),
                format);
        writer.write(doc.getDocument());
    } finally {
        if (writer != null) {
            writer.close();
        }
    }

    if (!skipBlobs) {
        Map<String, Blob> blobs = doc.getBlobs();
        for (Map.Entry<String, Blob> entry : blobs.entrySet()) {
            String blobPath = file.getAbsolutePath() + File.separator + entry.getKey();
            entry.getValue().transferTo(new File(blobPath));
        }
    }

    // write external documents
    for (Map.Entry<String, Document> entry : doc.getDocuments().entrySet()) {
        writer = null;
        try {
            writer = new XMLWriter(
                    new FileOutputStream(file.getAbsolutePath() + File.separator + entry.getKey() + ".xml"),
                    format);
            writer.write(entry.getValue());
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }

    return null;
}

From source file:org.olat.core.gui.control.generic.textmarker.TextMarkerManagerImpl.java

License:Apache License

/**
 * @see org.olat.core.gui.control.generic.textmarker.TextMarkerManager#saveToFile(org.olat.core.util.vfs.VFSLeaf, java.util.List)
 *///from   w  ww . j a v  a2  s .  c  o  m
@Override
public void saveToFile(VFSLeaf textMarkerFile, List textMarkerList) {
    DocumentFactory df = DocumentFactory.getInstance();
    Document doc = df.createDocument();
    // create root element with version information
    Element root = df.createElement(XML_ROOT_ELEMENT);
    root.addAttribute(XML_VERSION_ATTRIBUTE, String.valueOf(VERSION));
    doc.setRootElement(root);
    // add TextMarker elements
    Iterator iter = textMarkerList.iterator();
    while (iter.hasNext()) {
        TextMarker textMarker = (TextMarker) iter.next();
        textMarker.addToElement(root);
    }
    OutputStream stream = textMarkerFile.getOutputStream(false);
    try {
        XMLWriter writer = new XMLWriter(stream);
        writer.write(doc);
        writer.close();
        stream.close();
    } catch (UnsupportedEncodingException e) {
        Tracing.logError("Error while saving text marker file", e, TextMarkerManagerImpl.class);
    } catch (IOException e) {
        Tracing.logError("Error while saving text marker file", e, TextMarkerManagerImpl.class);
    }
}

From source file:org.olat.ims.qti.editor.QTIEditorPackage.java

License:Apache License

/**
 * SaveQTIDocument in temporary folder.//from   w  ww  .j  a  v a2  s.  co m
 * 
 * @param doc
 * @return true: save was successful, false otherwhise
 */
private boolean saveQTIDocument(final Document doc) {
    File fOut = null;
    OutputStream out = null;
    try {
        fOut = new File(packageDir, ImsRepositoryResolver.QTI_FILE);
        out = new FileOutputStream(fOut);
        final XMLWriter writer = new XMLWriter(out, outformat);
        writer.write(doc);
        writer.close();
    } catch (final Exception e) {
        throw new OLATRuntimeException(this.getClass(),
                "Exception when saving QTI document to " + fOut != null ? fOut.getAbsolutePath() : "qti.xml",
                e);
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (final IOException e1) {
                throw new OLATRuntimeException(this.getClass(), "Could not close output file stream ", e1);
            }
        }
    }
    return true;
}

From source file:org.olat.ims.qti.editor.QTIEditorPackageImpl.java

License:Apache License

/**
 * SaveQTIDocument in temporary folder./* w ww  .  jav a 2 s.c om*/
 * 
 * @param doc
 * @return true: save was successful, false otherwhise
 */
private boolean saveQTIDocument(Document doc) {
    File fOut = null;
    OutputStream out = null;
    try {
        fOut = new File(packageDir, ImsRepositoryResolver.QTI_FILE);
        out = new FileOutputStream(fOut);
        XMLWriter writer = new XMLWriter(out, outformat);
        writer.write(doc);
        writer.close();
    } catch (Exception e) {
        throw new OLATRuntimeException(this.getClass(),
                "Exception when saving QTI document to " + fOut != null ? fOut.getAbsolutePath() : "qti.xml",
                e);
    } finally {
        if (out != null)
            try {
                out.close();
            } catch (IOException e1) {
                throw new OLATRuntimeException(this.getClass(), "Could not close output file stream ", e1);
            }
    }
    return true;
}

From source file:org.olat.ims.qti.process.FilePersister.java

License:Apache License

/**
 * Persist results for this user/aiid as an XML document. dlPointer is aiid in this case.
 * //  w  w w .  j  a  v a2s. c o  m
 * @param doc
 * @param type
 * @param info
 */
public static void createResultsReporting(final Document doc, final Identity subj, final String type,
        final long aiid) {
    final File fUserdataRoot = new File(WebappHelper.getUserDataRoot());
    final String path = RES_REPORTING + File.separator + subj.getName() + File.separator + type;
    final File fReportingDir = new File(fUserdataRoot, path);
    try {
        fReportingDir.mkdirs();
        final OutputStream os = new FileOutputStream(new File(fReportingDir, aiid + ".xml"));
        final Element element = doc.getRootElement();
        final XMLWriter xw = new XMLWriter(os, new OutputFormat("  ", true));
        xw.write(element);
        // closing steams
        xw.close();
        os.close();
    } catch (final Exception e) {
        throw new OLATRuntimeException(FilePersister.class, "Error persisting results reporting for subject: '"
                + subj.getName() + "'; assessment id: '" + aiid + "'", e);
    }
}

From source file:org.olat.ims.qti.qpool.QTIImportProcessor.java

License:Apache License

protected void processAssessmentFiles(QuestionItemImpl item, ItemInfos itemInfos) {
    //a package with an item
    String dir = item.getDirectory();
    String rootFilename = item.getRootFilename();
    VFSContainer container = qpoolFileStorage.getContainer(dir);
    VFSLeaf endFile = container.createChildLeaf(rootFilename);

    //embed in <questestinterop>
    DocumentFactory df = DocumentFactory.getInstance();
    Document itemDoc = df.createDocument();
    Element questestinteropEl = df.createElement(QTIDocument.DOCUMENT_ROOT);
    itemDoc.setRootElement(questestinteropEl);
    Element deepClone = (Element) itemInfos.getItemEl().clone();
    questestinteropEl.add(deepClone);/*from   www  . j a v a  2  s.  c o  m*/

    //write
    try {
        OutputStream os = endFile.getOutputStream(false);
        ;
        XMLWriter xw = new XMLWriter(os, new OutputFormat("  ", true));
        xw.write(itemDoc.getRootElement());
        xw.close();
        os.close();
    } catch (IOException e) {
        log.error("", e);
    }

    //there perhaps some other materials
    if (importedFilename.toLowerCase().endsWith(".zip")) {
        processAssessmentMaterials(deepClone, container);
    }
}

From source file:org.openadaptor.util.XmlUtils.java

License:Open Source License

/**
 * Uses a Dom4j SAXReader to apply formatting to the supplied XML fragment. In this case we use a prettyprinter to
 * indent the tags./*from  w  w w.j a  va2 s  .  c  o m*/
 * 
 * @param xml
 *          The XML to be formatted (can be just a fragment)
 * @param isFragment
 *          If you supplied a XML fragment then this must be set to true so that the writer doesn't output an XML
 *          declaration
 * 
 * @return the formatted XML
 * 
 * @throws IOException
 *           if there was a problem applying the formatting
 * @throws DocumentException
 *           if there was a problem with the XML
 */
public static String format(String xml, boolean isFragment) throws IOException, DocumentException {

    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setSuppressDeclaration(isFragment);
    format.setIndent("\t");

    SAXReader reader = new SAXReader();
    Reader r = new StringReader(xml);
    org.dom4j.Document document = reader.read(r);

    Writer w = new StringWriter();
    XMLWriter out = new XMLWriter(w, format);
    out.write(document);
    out.close();

    return w.toString();
}

From source file:org.openbravo.dal.xml.XMLUtil.java

License:Open Source License

/**
 * Converts a Dom4j document to a string. A number of specific settings: 1) output encoding is
 * UTF-8, 2) text nodes are not trimmed//  w  w  w.ja  v  a  2s  . c  o  m
 * 
 * @param document
 *          the Dom4j to convert to a XML string
 * @return the XML representation
 */
public String toString(Document document) {
    try {
        final OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("UTF-8");
        format.setTrimText(false);
        final StringWriter out = new StringWriter();
        final XMLWriter writer = new XMLWriter(out, format);
        writer.write(document);
        writer.close();
        return out.toString();
    } catch (final Exception e) {
        throw new OBException(e);
    }
}

From source file:org.opencms.configuration.CmsConfigurationManager.java

License:Open Source License

/**
 * Writes the XML configuration for the provided configuration instance.<p>
 * /*from w  w  w . ja va2s  .c o m*/
 * @param clazz the configuration class to write the XML for
 * @throws IOException in case of I/O errors while writing
 * @throws CmsConfigurationException if the given class is not a valid configuration class
 */
public void writeConfiguration(Class<?> clazz) throws IOException, CmsConfigurationException {

    I_CmsXmlConfiguration configuration = getConfiguration(clazz);
    if (configuration == null) {
        throw new CmsConfigurationException(
                Messages.get().container(Messages.ERR_CONFIG_WITH_UNKNOWN_CLASS_1, clazz.getName()));
    }

    // generate the file URL for the XML input
    File file = new File(m_baseFolder, configuration.getXmlFileName());
    if (LOG.isDebugEnabled()) {
        LOG.debug(Messages.get().getBundle().key(Messages.LOG_WRITE_CONFIG_XMLFILE_1, file.getAbsolutePath()));
    }

    // generate the XML document 
    Document config = generateXml(configuration);

    // output the document
    XMLWriter writer = null;
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setIndentSize(4);
    format.setTrimText(false);
    format.setEncoding(CmsEncoder.ENCODING_UTF_8);

    try {
        OutputStream out = new FileOutputStream(file);
        writer = new XMLWriter(out, format);
        writer.write(config);
        writer.flush();
    } finally {
        if (writer != null) {
            writer.close();
        }
    }

    if (LOG.isInfoEnabled()) {
        LOG.info(Messages.get().getBundle().key(Messages.LOG_WRITE_CONFIG_SUCCESS_2, file.getAbsolutePath(),
                configuration.getClass().getName()));
    }
}