Example usage for org.dom4j.io XMLWriter write

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

Introduction

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

Prototype

public void write(Object object) throws IOException 

Source Link

Document

Writes the given object which should be a String, a Node or a List of Nodes.

Usage

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

License:Apache License

/**
 * Utility to serialize Document to a stream
 *
 * @param document document/*from   www.j a v a 2s . co  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. j a  v a  2s  .  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.rundeck.core.cli.util.MvnPomInfoTool.java

License:Apache License

void storeDocument(Document doc) throws IOException {
    OutputFormat format = OutputFormat.createPrettyPrint();
    OutputStream os;/*from  w ww  .  ja  v  a2 s .  co  m*/
    FileOutputStream fos = null;
    if ("-".equals(destfile)) {
        os = System.out;
    } else {
        fos = new FileOutputStream(destfile);
        os = fos;
    }
    XMLWriter writer = new XMLWriter(os, format);
    writer.write(doc);
    if (null != fos) {
        fos.close();
    }
}

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

License:Apache License

/**
 * Write Document to a file/*from  www  . ja  v a 2 s . c  o  m*/
 *
 * @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.easyjf.generator.AllGenerator.java

License:Apache License

private void genXml(AllProcessor processor) {
    for (String templateFile : this.xmlfiles.keySet()) {
        tg.setProcess(processor);/*from  w  w  w . ja  v a 2s  . co  m*/
        String fileName = (String) xmlfiles.get(templateFile);
        File targetFile = new File(fileName);
        tg.setTargetDir("");
        tg.setTemplateDir(templateDir);
        tg.setTemplateName(templateFile);
        if (targetFile.exists()) {
            tg.setTargetName(fileName + "_tmp");
            tg.generator(false);
            try {
                Document doc = this.getDocument(fileName + "_tmp");
                Document document = this.getDocument(fileName);
                String existNode = "/easyjf-web/modules/module[@name='" + this.lowerBeanName + "']";

                Node node = "mvc.xml".equals(templateFile) ? document.selectSingleNode(existNode)
                        : findBean(document,
                                this.lowerBeanName + ("dao.xml".equals(templateFile) ? "Dao" : "Service"));
                if (node == null) {
                    String appendNode = "/easyjf-web/modules", cnode = appendNode + "/module";
                    if (!"mvc.xml".equals(templateFile))
                        appendNode = "/beans";
                    Element moduleE = (Element) document.selectSingleNode(appendNode);
                    Node n = "mvc.xml".equals(templateFile) ? doc.selectSingleNode(cnode)
                            : findBean(doc,
                                    this.lowerBeanName + ("dao.xml".equals(templateFile) ? "Dao" : "Service"));
                    if (moduleE != null && n != null) {
                        n.detach();
                        moduleE.add(n);
                    }
                    OutputFormat format = OutputFormat.createPrettyPrint();
                    XMLWriter output = new XMLWriter(new FileWriter(new File(fileName)), format);
                    output.write(document);
                    output.close();
                }
                new File(fileName + "_tmp").deleteOnExit();
                new File(fileName + "_tmp").delete();
            } catch (Exception e) {
                //               e.printStackTrace();
            }
            System.out.println(
                    I18n.getLocaleMessage("generator.Successfully.add.to.configuration.information.to.a.file")
                            + fileName);
        } else {
            System.out.println(
                    I18n.getLocaleMessage("generator.Successful.configuration.file.generation") + fileName);
            tg.setTargetName(fileName);
            new File(fileName + "_tmp").deleteOnExit();
            new File(fileName + "_tmp").delete();
            tg.generator(false);
        }

    }
}

From source file:com.ethercis.vehr.response.XmlHttpResponse.java

License:Apache License

public void respond(Object data, String path) {

    if (data instanceof String) {
        writer.println((String) data);
        writer.close();// w ww. j a va  2  s. c  om
    } else if (data instanceof Document) {
        Document document = (Document) data;
        String xml = document.asXML().replaceAll(Constants.URI_TAG, path);
        //massaging...
        OutputFormat outputFormat = OutputFormat.createPrettyPrint();
        StringWriter stringWriter = new StringWriter();
        XMLWriter xmlWriter = new XMLWriter(stringWriter, outputFormat);
        try {
            Document document1 = DocumentHelper.parseText(xml);
            xmlWriter.write(document1);
        } catch (Exception e) {
            throw new IllegalArgumentException("Could not encode content:" + e);
        }
        writer.println(stringWriter.toString());
        writer.close();
    }
}

From source file:com.eufar.asmm.server.DownloadFunction.java

License:EUPL

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    System.out.println("DownloadFunction - the function started");
    ServletContext context = getServletConfig().getServletContext();
    request.setCharacterEncoding("UTF-8");
    String dir = context.getRealPath("/tmp");
    ;//from  w  ww.jav a  2  s. c  om
    String filename = "";
    File fileDir = new File(dir);
    try {
        System.out.println("DownloadFunction - create the file on server");
        filename = request.getParameterValues("filename")[0];
        String xmltree = request.getParameterValues("xmltree")[0];

        // format xml code to pretty xml code
        Document doc = DocumentHelper.parseText(xmltree);
        StringWriter sw = new StringWriter();
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setIndent(true);
        format.setIndentSize(4);
        XMLWriter xw = new XMLWriter(sw, format);
        xw.write(doc);

        Writer out = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(dir + "/" + filename), "UTF-8"));
        out.append(sw.toString());
        out.flush();
        out.close();
    } catch (Exception ex) {
        System.out.println("ERROR during rendering: " + ex);
    }
    try {
        System.out.println("DownloadFunction - send file to user");
        ServletOutputStream out = response.getOutputStream();
        File file = new File(dir + "/" + filename);
        String mimetype = context.getMimeType(filename);
        response.setContentType((mimetype != null) ? mimetype : "application/octet-stream");
        response.setContentLength((int) file.length());
        response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
        response.setHeader("Pragma", "private");
        response.setHeader("Cache-Control", "private, must-revalidate");
        DataInputStream in = new DataInputStream(new FileInputStream(file));
        int length;
        while ((in != null) && ((length = in.read(bbuf)) != -1)) {
            out.write(bbuf, 0, length);
        }
        in.close();
        out.flush();
        out.close();
        FileUtils.cleanDirectory(fileDir);
    } catch (Exception ex) {
        System.out.println("ERROR during downloading: " + ex);
    }
    System.out.println("DownloadFunction - file ready to be donwloaded");
}

From source file:com.eurelis.opencms.ant.task.ManifestBuilderTask.java

License:Open Source License

public void write() throws Exception {
    File tmpFile = new File(distfolder + "/manifest.xml");
    FileOutputStream fos = new FileOutputStream(tmpFile);
    XMLWriter writer = new XMLWriter(fos, OutputFormat.createPrettyPrint());
    writer.write(document);
    writer.close();//w  w w .  ja v a  2  s.c  om
}

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 a v  a 2s .  c  o m*/
 * @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
 */// ww  w.  j ava  2 s  . co  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();
            }
        }
    }

}