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:com.dtolabs.client.services.JobDefinitionSerializer.java

License:Apache License

private static void serializeDocToFile(final File file, final Document doc) throws IOException {
    final OutputFormat format = OutputFormat.createPrettyPrint();
    final XMLWriter writer = new XMLWriter(new FileOutputStream(file), format);
    writer.write(doc);/*  ww w.java  2 s .co m*/
    writer.flush();
}

From source file:com.dtolabs.client.services.RundeckAPICentralDispatcher.java

License:Apache License

public Collection<IStoredJob> listStoredJobs(final IStoredJobsQuery iStoredJobsQuery, final OutputStream output,
        final JobDefinitionFileFormat fformat) throws CentralDispatcherException {
    final HashMap<String, String> params = new HashMap<String, String>();
    final String nameMatch = iStoredJobsQuery.getNameMatch();
    String groupMatch = iStoredJobsQuery.getGroupMatch();
    final String projectFilter = iStoredJobsQuery.getProjectFilter();
    final String idlistFilter = iStoredJobsQuery.getIdlist();

    final String expectedContentType;
    if (null != fformat) {
        params.put("format", fformat.getName());
        expectedContentType = fformat == JobDefinitionFileFormat.xml ? "text/xml" : "text/yaml";
    } else {/*w w w  .j ava 2s  .c o  m*/
        params.put("format", JobDefinitionFileFormat.xml.getName());
        expectedContentType = "text/xml";
    }
    if (null != nameMatch) {
        params.put("jobFilter", nameMatch);
    }
    if (null != groupMatch) {
        final Matcher matcher = Pattern.compile("^/*(.+?)/*$").matcher(groupMatch);
        if (matcher.matches()) {
            //strip leading and trailing slashes
            groupMatch = matcher.group(1);
        }
        params.put("groupPath", groupMatch);
    }
    if (null != projectFilter) {
        params.put("project", projectFilter);
    }
    if (null != idlistFilter) {
        params.put("idlist", idlistFilter);
    }

    //2. send request via ServerService
    final WebserviceResponse response;
    try {
        response = serverService.makeRundeckRequest(RUNDECK_API_JOBS_EXPORT_PATH, params, null, null,
                expectedContentType, null);
    } catch (MalformedURLException e) {
        throw new CentralDispatcherServerRequestException("Failed to make request", e);
    }
    checkErrorResponse(response);
    //if xml, do local validation and listing
    if (null == fformat || fformat == JobDefinitionFileFormat.xml) {
        validateJobsResponse(response);

        ////////////////////
        //parse result list of queued items, return the collection of QueuedItems
        ///////////////////

        final Document resultDoc = response.getResultDoc();

        final Node node = resultDoc.selectSingleNode("/joblist");
        final ArrayList<IStoredJob> list = new ArrayList<IStoredJob>();
        if (null == node) {
            return list;
        }
        final List items = node.selectNodes("job");
        if (null != items && items.size() > 0) {
            for (final Object o : items) {
                final Node node1 = (Node) o;
                final Node uuid = node1.selectSingleNode("uuid");
                final Node id1 = node1.selectSingleNode("id");
                final String id = null != uuid ? uuid.getStringValue() : id1.getStringValue();
                final String name = node1.selectSingleNode("name").getStringValue();
                final String url = createJobURL(id);

                final Node gnode = node1.selectSingleNode("group");
                final String group = null != gnode ? gnode.getStringValue() : null;
                final String description = node1.selectSingleNode("description").getStringValue();
                list.add(StoredJobImpl.create(id, name, url, group, description, projectFilter));
            }
        }

        if (null != output) {
            //write output doc to the outputstream
            final OutputFormat format = OutputFormat.createPrettyPrint();
            try {
                final XMLWriter writer = new XMLWriter(output, format);
                writer.write(resultDoc);
                writer.flush();
            } catch (IOException e) {
                throw new CentralDispatcherServerRequestException(e);
            }
        }
        return list;
    } else if (fformat == JobDefinitionFileFormat.yaml) {
        //do rough yaml parse

        final Collection<Map> mapCollection;
        //write to temp file

        File temp;
        InputStream tempIn;
        try {
            temp = File.createTempFile("listStoredJobs", ".yaml");
            temp.deleteOnExit();
            OutputStream os = new FileOutputStream(temp);
            try {
                Streams.copyStream(response.getResultStream(), os);
            } finally {
                os.close();
            }
            tempIn = new FileInputStream(temp);
            try {
                mapCollection = validateJobsResponseYAML(response, tempIn);
            } finally {
                tempIn.close();
            }
        } catch (IOException e) {
            throw new CentralDispatcherServerRequestException(e);
        }
        final ArrayList<IStoredJob> list = new ArrayList<IStoredJob>();

        if (null == mapCollection || mapCollection.size() < 1) {
            return list;
        }
        for (final Map map : mapCollection) {
            final Object uuidobj = map.get("uuid");
            final Object idobj = map.get("id");
            final String id = null != uuidobj ? uuidobj.toString() : idobj.toString();
            final String name = (String) map.get("name");
            final String group = map.containsKey("group") ? (String) map.get("group") : null;
            final String desc = map.containsKey("description") ? (String) map.get("description") : "";
            final String url = createJobURL(id);
            list.add(StoredJobImpl.create(id, name, url, group, desc, projectFilter));
        }

        if (null != output) {
            //write output doc to the outputstream
            try {
                tempIn = new FileInputStream(temp);
                try {
                    Streams.copyStream(tempIn, output);
                } finally {
                    tempIn.close();
                }
                temp.delete();
            } catch (IOException e) {
                throw new CentralDispatcherServerRequestException(e);
            }
        }
        return list;
    }
    return null;
}

From source file:com.dtolabs.client.services.RundeckAPICentralDispatcher.java

License:Apache License

/**
 * Utility to serialize Document as a String for debugging
 *
 * @param document document/*from  w w  w .  j  a va  2 s . com*/
 *
 * @return xml string
 *
 * @throws java.io.IOException if error occurs
 */
private static String serialize(final Document document) throws IOException {
    final OutputFormat format = OutputFormat.createPrettyPrint();
    final StringWriter sw = new StringWriter();
    final XMLWriter writer = new XMLWriter(sw, format);
    writer.write(document);
    writer.flush();
    sw.flush();
    return sw.toString();
}

From source file:com.dtolabs.client.services.RundeckAPICentralDispatcher.java

License:Apache License

/**
 * Utility to serialize Document to a stream
 *
 * @param document document//from ww w  .j a va2  s .  c  o m
 *
 *
 * @throws java.io.IOException if error occurs
 */
private static void serialize(final Document document, final OutputStream stream) throws IOException {
    final OutputFormat format = OutputFormat.createPrettyPrint();
    final XMLWriter writer = new XMLWriter(stream, format);
    writer.write(document);
    writer.flush();

}

From source file:com.dtolabs.client.services.RundeckCentralDispatcher.java

License:Apache License

public Collection<IStoredJob> listStoredJobs(final IStoredJobsQuery iStoredJobsQuery, final OutputStream output,
        final JobDefinitionFileFormat fformat) throws CentralDispatcherException {
    final HashMap<String, String> params = new HashMap<String, String>();
    final String nameMatch = iStoredJobsQuery.getNameMatch();
    String groupMatch = iStoredJobsQuery.getGroupMatch();
    final String projectFilter = iStoredJobsQuery.getProjectFilter();
    final String idlistFilter = iStoredJobsQuery.getIdlist();

    if (null != output && null != fformat) {
        params.put("format", fformat.getName());
    } else {//from  w ww. ja v a  2 s . c  om
        params.put("format", JobDefinitionFileFormat.xml.getName());
    }
    if (null != nameMatch) {
        params.put("jobFilter", nameMatch);
    }
    if (null != groupMatch) {
        final Matcher matcher = Pattern.compile("^/*(.+?)/*$").matcher(groupMatch);
        if (matcher.matches()) {
            //strip leading and trailing slashes
            groupMatch = matcher.group(1);
        }
        params.put("groupPath", groupMatch);
    }
    if (null != projectFilter) {
        params.put("projFilter", projectFilter);
    }
    if (null != idlistFilter) {
        params.put("idlist", idlistFilter);
    }

    //2. send request via ServerService
    final WebserviceResponse response;
    try {
        response = serverService.makeRundeckRequest(RUNDECK_LIST_STORED_JOBS_PATH, params, null, null);
    } catch (MalformedURLException e) {
        throw new CentralDispatcherServerRequestException("Failed to make request", e);
    }

    //if xml, do local validation and listing
    if (null == fformat || fformat == JobDefinitionFileFormat.xml) {
        validateJobsResponse(response);

        ////////////////////
        //parse result list of queued items, return the collection of QueuedItems
        ///////////////////

        final Document resultDoc = response.getResultDoc();

        final Node node = resultDoc.selectSingleNode("/joblist");
        final ArrayList<IStoredJob> list = new ArrayList<IStoredJob>();
        if (null == node) {
            return list;
        }
        final List items = node.selectNodes("job");
        if (null != items && items.size() > 0) {
            for (final Object o : items) {
                final Node node1 = (Node) o;
                final String id = node1.selectSingleNode("id").getStringValue();
                final String name = node1.selectSingleNode("name").getStringValue();
                final String url = createJobURL(id);

                final Node gnode = node1.selectSingleNode("group");
                final String group = null != gnode ? gnode.getStringValue() : null;
                final String description = node1.selectSingleNode("description").getStringValue();
                list.add(StoredJobImpl.create(id, name, url, group, description, projectFilter));
            }
        }

        if (null != output) {
            //write output doc to the outputstream
            final OutputFormat format = OutputFormat.createPrettyPrint();
            try {
                final XMLWriter writer = new XMLWriter(output, format);
                writer.write(resultDoc);
                writer.flush();
            } catch (IOException e) {
                throw new CentralDispatcherServerRequestException(e);
            }
        }
        return list;
    } else if (fformat == JobDefinitionFileFormat.yaml) {
        //do rought yaml parse
        final Collection<Map> mapCollection = validateJobsResponseYAML(response);
        final ArrayList<IStoredJob> list = new ArrayList<IStoredJob>();

        if (null == mapCollection || mapCollection.size() < 1) {
            return list;
        }
        for (final Map map : mapCollection) {
            final String id = map.get("id").toString();
            final String name = (String) map.get("name");
            final String group = map.containsKey("group") ? (String) map.get("group") : null;
            final String desc = map.containsKey("description") ? (String) map.get("description") : "";
            final String url = createJobURL(id);
            list.add(StoredJobImpl.create(id, name, url, group, desc, projectFilter));
        }

        if (null != output) {
            //write output doc to the outputstream
            try {
                final Writer writer = new OutputStreamWriter(output);
                writer.write(response.getResults());
                writer.flush();
            } catch (IOException e) {
                throw new CentralDispatcherServerRequestException(e);
            }
        }
        return list;
    }
    return null;
}

From source file:com.dtolabs.shared.resources.ResourceXMLGenerator.java

License:Apache License

/**
 * Write Document to a file// w  ww  .  j ava2  s.com
 *
 * @param output stream
 * @param doc document
 *
 * @throws IOException on error
 */
private static void serializeDocToStream(final OutputStream output, final Document doc) throws IOException {
    final OutputFormat format = OutputFormat.createPrettyPrint();
    final XMLWriter writer = new XMLWriter(output, format);
    writer.write(doc);
    writer.flush();
}

From source file:com.eurelis.opencms.workflows.workflows.A_OSWorkflowManager.java

License:Open Source License

/**
 * Get the OpenCMS RFS OSWorkflow configuration file and update it with the given filepath.
 * //  w  w  w  . j  av a  2 s .c  om
 * @param listOfWorkflowsFilepath
 *            the path of the file containing the list of available workflow descriptions
 * @return the path in RFS of the updated file
 * @throws DocumentException
 *             this exception is thrown if an error occurs during the parsing of the document
 * @throws IOException
 *             this exception is thrown if a problem occurs during overwriting of the config file
 */
private String updateOSWorkflowConfigFile(String listOfWorkflowsFilepath)
        throws CmsException, DocumentException, IOException {

    // get file path
    String configFilePath = this.getWebINFPath() + ModuleSharedVariables.SYSTEM_FILE_SEPARATOR
            + OSWORKFLOWCONFIGFILE_RFSFILEPATH;

    File listOfWorkflowsFile = new File(listOfWorkflowsFilepath);
    // Load Jdom parser
    SAXReader reader = new SAXReader();
    Document document = reader.read(configFilePath);
    Node propertyNode = document.selectSingleNode(OSWORKFLOWCONFIGFILE_PROPERTYTOUPDATE_XPATH);
    if (propertyNode != null) {
        if (propertyNode.getNodeType() == Node.ELEMENT_NODE) {
            // convert Node into element
            Element propertyElement = (Element) propertyNode;

            // update the Attribute
            Attribute valueAttribute = propertyElement
                    .attribute(OSWORKFLOWCONFIGFILE_PROPERTYTOUPDATE_ATTRIBUTNAME);

            valueAttribute.setValue(listOfWorkflowsFile.toURI().toString());

        } else {
            LOGGER.debug("the node with Xpath " + OSWORKFLOWCONFIGFILE_PROPERTYTOUPDATE_XPATH + " in the file "
                    + configFilePath + " doesn't correspond to an element");
        }

    } else {
        Node parentNode = document.selectSingleNode(OSWORKFLOWCONFIGFILE_PROPERTYTOUPDATE_PARENT_XPATH);
        if (parentNode != null) {

            if (parentNode.getNodeType() == Node.ELEMENT_NODE) {
                // convert Node into element
                Element parentElement = (Element) parentNode;

                // add new property
                Element propertyElement = parentElement.addElement("property");

                // add attributs
                propertyElement.addAttribute("key", "resource");
                propertyElement.addAttribute("value", listOfWorkflowsFile.toURI().toString());

            } else {
                LOGGER.debug("the node with Xpath " + OSWORKFLOWCONFIGFILE_PROPERTYTOUPDATE_XPATH
                        + " in the file " + configFilePath + " doesn't correspond to an element");
            }

        } else {
            LOGGER.debug("the node with Xpath " + OSWORKFLOWCONFIGFILE_PROPERTYTOUPDATE_PARENT_XPATH
                    + " in the file " + configFilePath + " has not been found.");
        }
    }

    /*
     * Get a string of the resulting file
     */

    // creating of a buffer that will collect result
    ByteArrayOutputStream xmlContent = new ByteArrayOutputStream();

    // Pretty print the document to xmlContent
    OutputFormat format = OutputFormat.createPrettyPrint();
    XMLWriter writer = new XMLWriter(xmlContent, format);
    writer.write(document);
    writer.flush();
    writer.close();

    // get the config file content as a String
    String documentContent = new String(xmlContent.toByteArray());

    /*
     * Overwrite the config file
     */
    FileWriter.writeFile(configFilePath, documentContent);

    return configFilePath;
}

From source file:com.eurelis.tools.xml.transformation.local.LocalDocumentSource.java

License:Open Source License

/**
 * Write a dom4j document to the location specified by a File object
 *
 * @param file the location where to write the document
 * @param document the dom4j document to write
 *//*from   ww  w  . j a  va  2 s .  c  o  m*/
public static void writeDocument(File file, Document document) {
    XMLWriter xmlWriter = null;

    OutputStream os = null;
    OutputStreamWriter osw = null;

    try {

        os = new FileOutputStream(file);
        osw = new OutputStreamWriter(os, "UTF-8");

        xmlWriter = new XMLWriter(osw, new OutputFormat("  ", true, "UTF-8"));
        xmlWriter.write(document);

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (xmlWriter != null) {
            try {
                xmlWriter.flush();
                xmlWriter.close();

                osw.close();
                os.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

From source file:com.ewcms.content.particular.web.ProjectBasicAction.java

License:Open Source License

public void exportXML() {
    if (getSelections() != null && getSelections().size() > 0) {
        ServletOutputStream out = null;//from w  ww.  jav a 2 s.c  o m
        try {
            Document document = particularFac.exportXml(getSelections());

            StringWriter stringWriter = new StringWriter();

            OutputFormat xmlFormat = new OutputFormat();
            xmlFormat.setEncoding("UTF-8");
            XMLWriter xmlWriter = new XMLWriter(stringWriter, xmlFormat);
            xmlWriter.write(document);
            xmlWriter.flush();
            xmlWriter.close();

            HttpServletResponse resp = Struts2Util.getResponse();
            out = resp.getOutputStream();
            resp.setCharacterEncoding("UTF-8");
            resp.setContentType("text/xml; charset=UTF-8");
            resp.addHeader("Content-Disposition", "attachment; filename=xmjbxx.xml");
            out.write(stringWriter.toString().getBytes("UTF-8"));
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                }
                out = null;
            }
        }
    }
}

From source file:com.globalsight.cxe.util.Dom4jUtil.java

License:Apache License

public static String formatXML(Document document, String charset) {
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setEncoding(charset);/* ww w .jav  a2  s .  co  m*/
    StringWriter sw = new StringWriter();
    XMLWriter xw = new XMLWriter(sw, format);
    try {
        xw.write(document);
        xw.flush();
        xw.close();
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        return document.asXML();
    }

    return sw.toString();
}