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:nl.ru.cmbi.vase.parse.VASEXMLParser.java

License:Apache License

public static void write(VASEDataObject data, OutputStream xmlOut) throws IOException {

    DocumentFactory df = DocumentFactory.getInstance();

    Document doc = df.createDocument();

    Element root = doc.addElement("xml");

    if (data.getTitle() != null) {

        Element title = root.addElement("title");
        title.setText(data.getTitle());//  ww  w.  j ava  2 s.  c  om
    }

    Element fasta = root.addElement("fasta");
    ByteArrayOutputStream fastaStream = new ByteArrayOutputStream();
    FastaParser.toFasta(data.getAlignment().getMap(), fastaStream);

    fasta.add(df.createCDATA(new String(fastaStream.toByteArray(), StandardCharsets.UTF_8)));

    Element pdb = root.addElement("pdb");
    pdb.addAttribute("pdbid", data.getPdbID());

    table2xml(data.getTable(), root);

    if (data.getPlots().size() > 0) {
        Element plots = root.addElement("plots");
        for (PlotDescription pd : data.getPlots()) {

            Element plot = plots.addElement("plot");
            plot.addElement("x").setText(pd.getXAxisColumnID());
            plot.addElement("y").setText(pd.getYAxisColumnID());
            plot.addAttribute("title", pd.getPlotTitle());
        }
    }

    XMLWriter writer = new XMLWriter(xmlOut);
    writer.write(doc);
    writer.close();
}

From source file:noThreads.Playlist.java

License:Open Source License

public void createPlaylist(String filePath)
        throws IOException, DocumentException, SAXException, ParserConfigurationException {
    String xmlObject, title = null;
    boolean flag = true;
    XspfPlaylist playlist = new XspfPlaylist();
    playlist.setTitle("My Playlist");
    playlist.setVersion("1");

    // create track list first
    XspfPlaylistTrackList tracks = new XspfPlaylistTrackList();

    for (int i = 0; i < eradioLinks.size(); i++) {
        if (flag == true) {
            flag = false;//from ww w  .j  a  v  a2s .  c  om
            title = org.apache.commons.lang3.StringEscapeUtils.escapeXml(eradioLinks.get(i));
        } else {
            flag = true;
            //escape the xml characters of the url
            xmlObject = org.apache.commons.lang3.StringEscapeUtils.escapeXml(eradioLinks.get(i));

            // now create track, set title and add to list
            XspfTrack track = new XspfTrack();
            track.setTitle(title);
            track.setLocation(xmlObject);
            tracks.addTrack(track);
        }
    }
    // add tracks to playlist
    playlist.setPlaylistTrackList(tracks);

    //or use Dom4j to output the playlist
    File file = new File(filePath);
    OutputFormat format = OutputFormat.createPrettyPrint();
    XMLWriter writer = new XMLWriter(new FileWriter(file), format);
    Document doc = DocumentHelper.parseText(playlist.makeTextDocument());
    writer.write(doc);
    writer.close();
}

From source file:org.alfresco.repo.admin.patch.util.ImportFileUpdater.java

License:Open Source License

/**
 * Updates the passed import file into the equivalent 1.4 format.
 * /*w w w.j ava2 s . com*/
 * @param source      the source import file
 * @param destination   the destination import file
 */
public void updateImportFile(String source, String destination) {
    XmlPullParser reader = getReader(source);
    XMLWriter writer = getWriter(destination);
    this.shownWarning = false;

    try {
        // Start the documentation
        writer.startDocument();

        // Start reading the document
        int eventType = reader.getEventType();
        while (eventType != XmlPullParser.END_DOCUMENT) {
            if (eventType == XmlPullParser.START_TAG) {
                ImportFileUpdater.this.outputCurrentElement(reader, writer, new OutputChildren());
            }
            eventType = reader.next();
        }

        // End and close the document
        writer.endDocument();
        writer.close();
    } catch (Exception exception) {
        throw new AlfrescoRuntimeException("Unable to update import file.", exception);
    }

}

From source file:org.alfresco.repo.importer.ExportSourceImporter.java

License:Open Source License

@SuppressWarnings("unchecked")
public void doImport() {
    UserTransaction userTransaction = null;
    try {//from   w  ww. j av  a 2  s.  co m
        AuthenticationUtil.pushAuthentication();
        userTransaction = transactionService.getUserTransaction();
        userTransaction.begin();
        AuthenticationUtil.setRunAsUserSystem();
        if (clearAllChildren) {
            logger.debug("clear all children");
            List<NodeRef> refs = searchService.selectNodes(nodeService.getRootNode(storeRef), path, null,
                    namespacePrefixResolver, false);

            for (NodeRef ref : refs) {
                if (logger.isDebugEnabled()) {
                    logger.debug("clear node ref" + ref);
                }
                for (ChildAssociationRef car : nodeService.getChildAssocs(ref)) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("delete child" + car.getChildRef());
                    }
                    nodeService.deleteNode(car.getChildRef());
                }
            }
        }

        if (caches != null) {
            logger.debug("clearing caches");
            for (SimpleCache cache : caches) {

                cache.clear();
            }
        }

        File tempFile = TempFileProvider.createTempFile("ExportSourceImporter-", ".xml");
        Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tempFile), "UTF-8"));
        XMLWriter xmlWriter = createXMLExporter(writer);
        exportSource.generateExport(xmlWriter);
        xmlWriter.close();

        Reader reader = new BufferedReader(new InputStreamReader(new FileInputStream(tempFile), "UTF-8"));

        Location location = new Location(storeRef);
        location.setPath(path);

        importerService.importView(reader, location, REPLACE_BINDING, null);
        reader.close();

        if (caches != null) {
            for (SimpleCache cache : caches) {
                cache.clear();
            }
        }
        logger.debug("about to commit");
        userTransaction.commit();
    } catch (Throwable t) {
        try {
            if (userTransaction != null) {
                logger.debug("rolling back due to exception", t);
                userTransaction.rollback();
            }
        } catch (Exception ex) {
            logger.debug("exception during rollback", ex);
        }
        throw new ExportSourceImporterException("Failed to import", t);
    } finally {
        AuthenticationUtil.popAuthentication();
    }
}

From source file:org.apache.commons.jelly.tags.core.FileTag.java

License:Apache License

/**
 * A Factory method to create a new XMLOutput from the given Writer.
 *///from   ww  w.j  av a2s.com
protected XMLOutput createXMLOutput(Writer writer) {

    OutputFormat format = null;
    if (prettyPrint) {
        format = OutputFormat.createPrettyPrint();
    } else {
        format = new OutputFormat();
    }
    if (encoding != null) {
        format.setEncoding(encoding);
    }
    if (omitXmlDeclaration) {
        format.setSuppressDeclaration(true);
    }

    boolean isHtml = outputMode != null && outputMode.equalsIgnoreCase("html");
    final XMLWriter xmlWriter = (isHtml) ? new HTMLWriter(writer, format) : new XMLWriter(writer, format);

    xmlWriter.setEscapeText(isEscapeText());

    XMLOutput answer = new XMLOutput() {
        public void close() throws IOException {
            xmlWriter.close();
        }
    };
    answer.setContentHandler(xmlWriter);
    answer.setLexicalHandler(xmlWriter);
    return answer;
}

From source file:org.apache.commons.jelly.XMLOutput.java

License:Apache License

/**
 * Factory method to create a new XMLOutput from an XMLWriter
 *//*w w w  . j  a va 2 s.co m*/
protected static XMLOutput createXMLOutput(final XMLWriter xmlWriter) {
    XMLOutput answer = new XMLOutput() {
        public void close() throws IOException {
            xmlWriter.close();
        }
    };
    answer.setContentHandler(xmlWriter);
    answer.setLexicalHandler(xmlWriter);
    return answer;
}

From source file:org.apache.ddlutils.task.DumpMetadataTask.java

License:Apache License

/**
 * {@inheritDoc}//from  w ww .  ja  v  a  2  s .c o  m
 */
public void execute() throws BuildException {
    if (_dataSource == null) {
        log("No data source specified, so there is nothing to do.", Project.MSG_INFO);
        return;
    }

    Connection connection = null;
    try {
        Document document = DocumentFactory.getInstance().createDocument();
        Element root = document.addElement("metadata");

        root.addAttribute("driverClassName", _dataSource.getDriverClassName());

        connection = _dataSource.getConnection();

        dumpMetaData(root, connection.getMetaData());

        OutputFormat outputFormat = OutputFormat.createPrettyPrint();
        XMLWriter xmlWriter = null;

        outputFormat.setEncoding(_outputEncoding);
        if (_outputFile == null) {
            xmlWriter = new XMLWriter(System.out, outputFormat);
        } else {
            xmlWriter = new XMLWriter(new FileOutputStream(_outputFile), outputFormat);
        }
        xmlWriter.write(document);
        xmlWriter.close();
    } catch (Exception ex) {
        throw new BuildException(ex);
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException ex) {
            }
        }
    }
}

From source file:org.apache.directory.studio.schemaeditor.model.io.XMLSchemaFileExporter.java

License:Apache License

/**
 * Converts the given schema to its source code representation
 * in XML file format./*from w w  w  .  j  a  v  a  2  s . c o  m*/
 *
 * @param schema
 *      the schema to convert
 * @return
 *      the corresponding source code representation
 * @throws IOException
 */
public static String toXml(Schema schema) throws IOException {
    // Creating the Document
    Document document = DocumentHelper.createDocument();

    // Adding the schema
    addSchema(schema, document);

    // Creating the output stream we're going to put the XML in
    OutputStream os = new ByteArrayOutputStream();
    OutputFormat outformat = OutputFormat.createPrettyPrint();
    outformat.setEncoding("UTF-8"); //$NON-NLS-1$

    // Writing the XML.
    XMLWriter writer = new XMLWriter(os, outformat);
    writer.write(document);
    writer.flush();
    writer.close();

    return os.toString();
}

From source file:org.apache.directory.studio.schemaeditor.model.io.XMLSchemaFileExporter.java

License:Apache License

/**
 * Converts the given schemas to their source code representation
 * in one XML file format./*from w  w  w.ja va  2s  .  c o  m*/
 *
 * @param schemas
 *      the array of schemas to convert
 * @return
 *      the corresponding source code representation
 * @throws IOException
 */
public static String toXml(Schema[] schemas) throws IOException {
    // Creating the Document and the 'root' Element
    Document document = DocumentHelper.createDocument();

    addSchemas(schemas, document);

    // Creating the output stream we're going to put the XML in
    OutputStream os = new ByteArrayOutputStream();
    OutputFormat outformat = OutputFormat.createPrettyPrint();
    outformat.setEncoding("UTF-8"); //$NON-NLS-1$

    // Writing the XML.
    XMLWriter writer = new XMLWriter(os, outformat);
    writer.write(document);
    writer.flush();
    writer.close();

    return os.toString();
}

From source file:org.apache.directory.studio.templateeditor.model.parser.TemplateIO.java

License:Apache License

/**
 * Saves the template using the writer./*  w ww .j  ava  2s  .  c  o  m*/
 *
 * @param template
 *      the connections
 * @param stream
 *      the OutputStream
 * @throws IOException
 *      if an I/O error occurs
 */
public static void save(Template template, OutputStream stream) throws IOException {
    // Creating the Document
    Document document = DocumentHelper.createDocument();

    writeTemplate(document, template);

    // Writing the file to disk
    OutputFormat outformat = OutputFormat.createPrettyPrint();
    outformat.setEncoding("UTF-8"); //$NON-NLS-1$
    XMLWriter writer = new XMLWriter(stream, outformat);
    writer.write(document);
    writer.flush();
    writer.close();
}