Search in sources :

Example 16 with XMLWriter

use of org.dom4j.io.XMLWriter in project gradle by gradle.

the class DOM4JSerializer method exportToFile.

/**
     * Call this to save the JDOMSerializable to a file. This handles confirming overwriting an existing file as well as ensuring the extension is correct based on the passed in fileFilter.
     */
public static void exportToFile(String rootElementTag, ExportInteraction exportInteraction, ExtensionFileFilter fileFilter, SettingsSerializable... serializables) {
    File file = promptForFile(exportInteraction, fileFilter);
    if (file == null) {
        //the user canceled.
        return;
    }
    FileOutputStream fileOutputStream = null;
    try {
        fileOutputStream = new FileOutputStream(file);
    } catch (FileNotFoundException e) {
        LOGGER.error("Could not write to file: " + file.getAbsolutePath(), e);
        exportInteraction.reportError("Could not write to file: " + file.getAbsolutePath());
        return;
    }
    try {
        XMLWriter xmlWriter = new XMLWriter(fileOutputStream, OutputFormat.createPrettyPrint());
        Document document = DocumentHelper.createDocument();
        Element rootElement = document.addElement(rootElementTag);
        DOM4JSettingsNode settingsNode = new DOM4JSettingsNode(rootElement);
        for (int index = 0; index < serializables.length; index++) {
            SettingsSerializable serializable = serializables[index];
            try {
                //don't let a single serializer stop the entire thing from being written in.
                serializable.serializeOut(settingsNode);
            } catch (Exception e) {
                LOGGER.error("serializing", e);
            }
        }
        xmlWriter.write(document);
    } catch (Throwable t) {
        LOGGER.error("Failed to save", t);
        exportInteraction.reportError("Internal error. Failed to save.");
    } finally {
        closeQuietly(fileOutputStream);
    }
}
Also used : Element(org.dom4j.Element) SettingsSerializable(org.gradle.gradleplugin.foundation.settings.SettingsSerializable) Document(org.dom4j.Document) XMLWriter(org.dom4j.io.XMLWriter) DOM4JSettingsNode(org.gradle.gradleplugin.foundation.settings.DOM4JSettingsNode)

Example 17 with XMLWriter

use of org.dom4j.io.XMLWriter in project hudson-2.x by hudson.

the class Api method doXml.

/**
     * Exposes the bean as XML.
     */
public void doXml(StaplerRequest req, StaplerResponse rsp, @QueryParameter String xpath, @QueryParameter String wrapper, @QueryParameter int depth) throws IOException, ServletException {
    String[] excludes = req.getParameterValues("exclude");
    if (xpath == null && excludes == null) {
        // serve the whole thing
        rsp.serveExposedBean(req, bean, Flavor.XML);
        return;
    }
    StringWriter sw = new StringWriter();
    // first write to String
    Model p = MODEL_BUILDER.get(bean.getClass());
    p.writeTo(bean, depth, Flavor.XML.createDataWriter(bean, sw));
    // apply XPath
    Object result;
    try {
        Document dom = new SAXReader().read(new StringReader(sw.toString()));
        // apply exclusions
        if (excludes != null) {
            for (String exclude : excludes) {
                List<org.dom4j.Node> list = (List<org.dom4j.Node>) dom.selectNodes(exclude);
                for (org.dom4j.Node n : list) {
                    Element parent = n.getParent();
                    if (parent != null)
                        parent.remove(n);
                }
            }
        }
        if (xpath == null) {
            result = dom;
        } else {
            List list = dom.selectNodes(xpath);
            if (wrapper != null) {
                Element root = DocumentFactory.getInstance().createElement(wrapper);
                for (Object o : list) {
                    if (o instanceof String) {
                        root.addText(o.toString());
                    } else {
                        root.add(((org.dom4j.Node) o).detach());
                    }
                }
                result = root;
            } else if (list.isEmpty()) {
                rsp.setStatus(HttpServletResponse.SC_NOT_FOUND);
                rsp.getWriter().print(Messages.Api_NoXPathMatch(xpath));
                return;
            } else if (list.size() > 1) {
                rsp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                rsp.getWriter().print(Messages.Api_MultipleMatch(xpath, list.size()));
                return;
            } else {
                result = list.get(0);
            }
        }
    } catch (DocumentException e) {
        throw new IOException2(e);
    }
    OutputStream o = rsp.getCompressedOutputStream(req);
    try {
        if (result instanceof CharacterData) {
            rsp.setContentType("text/plain;charset=UTF-8");
            o.write(((CharacterData) result).getText().getBytes("UTF-8"));
            return;
        }
        if (result instanceof String || result instanceof Number || result instanceof Boolean) {
            rsp.setContentType("text/plain;charset=UTF-8");
            o.write(result.toString().getBytes("UTF-8"));
            return;
        }
        // otherwise XML
        rsp.setContentType("application/xml;charset=UTF-8");
        new XMLWriter(o).write(result);
    } finally {
        o.close();
    }
}
Also used : SAXReader(org.dom4j.io.SAXReader) Element(org.dom4j.Element) OutputStream(java.io.OutputStream) Document(org.dom4j.Document) XMLWriter(org.dom4j.io.XMLWriter) StringWriter(java.io.StringWriter) CharacterData(org.dom4j.CharacterData) DocumentException(org.dom4j.DocumentException) StringReader(java.io.StringReader) List(java.util.List) IOException2(hudson.util.IOException2)

Example 18 with XMLWriter

use of org.dom4j.io.XMLWriter in project hibernate-orm by hibernate.

the class AdditionalJaxbMappingProducerImpl method dump.

private static void dump(Document document) {
    if (!log.isTraceEnabled()) {
        return;
    }
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final Writer w = new PrintWriter(baos);
    try {
        final XMLWriter xw = new XMLWriter(w, new OutputFormat(" ", true));
        xw.write(document);
        w.flush();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    log.tracef("Envers-generate entity mapping -----------------------------\n%s", baos.toString());
    log.trace("------------------------------------------------------------");
}
Also used : OutputFormat(org.dom4j.io.OutputFormat) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) XMLWriter(org.dom4j.io.XMLWriter) XMLWriter(org.dom4j.io.XMLWriter) OutputStreamWriter(java.io.OutputStreamWriter) PrintWriter(java.io.PrintWriter) BufferedWriter(java.io.BufferedWriter) Writer(java.io.Writer) PrintWriter(java.io.PrintWriter)

Example 19 with XMLWriter

use of org.dom4j.io.XMLWriter in project Openfire by igniterealtime.

the class ImportExportPlugin method exportUsersToString.

/**
     * Converts the exported user data to a String. If a read-only
     * user store is being used a user's password will be the same as their username.
     *
     * @return a formatted String representation of the user data.
     * @throws IOException if there's a problem writing to the XMLWriter.
     */
public String exportUsersToString(boolean xep227Support) throws IOException {
    StringWriter stringWriter = new StringWriter();
    XMLWriter writer = null;
    try {
        writer = new XMLWriter(stringWriter, OutputFormat.createPrettyPrint());
        writer.write(exportUsers(xep227Support));
    } catch (IOException ioe) {
        Log.error(ioe.getMessage(), ioe);
        throw ioe;
    } finally {
        if (writer != null) {
            writer.close();
        }
    }
    return StringEscapeUtils.escapeHtml(stringWriter.toString());
}
Also used : StringWriter(java.io.StringWriter) IOException(java.io.IOException) XMLWriter(org.dom4j.io.XMLWriter)

Example 20 with XMLWriter

use of org.dom4j.io.XMLWriter in project Openfire by igniterealtime.

the class OpenfireExporterTest method testExportUsers.

/**
   * Test method for {@link org.jivesoftware.openfire.plugin.OpenfireExporter#exportUsers(org.jivesoftware.openfire.user.UserManager)}.
   * @throws UserAlreadyExistsException 
   * @throws IOException 
   */
@Test
public void testExportUsers() throws UserAlreadyExistsException, IOException {
    InExporter testobject = new OpenfireExporter("serverName", userManager, rosterItemProvider);
    for (int i = 0; i < 10; i++) {
        userManager.createUser("username" + i, "pw", "name" + i, "email" + i);
    }
    Document result = testobject.exportUsers();
    assertNotNull(result);
    assertEquals(1, result.nodeCount());
    assertNotNull(result.node(0));
    Element elem = ((Element) result.node(0));
    assertEquals(10, elem.nodeCount());
    assertNotNull(elem.node(0));
    assertEquals(7, ((Element) elem.node(0)).nodeCount());
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    XMLWriter writer = new XMLWriter(out, OutputFormat.createPrettyPrint());
    writer.write(result);
    logger.fine(out.toString());
    assertNotNull(testobject.validate(new ByteArrayInputStream(out.toByteArray())));
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) Element(org.dom4j.Element) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Document(org.dom4j.Document) XMLWriter(org.dom4j.io.XMLWriter) Test(org.junit.Test)

Aggregations

XMLWriter (org.dom4j.io.XMLWriter)42 Document (org.dom4j.Document)21 OutputFormat (org.dom4j.io.OutputFormat)17 IOException (java.io.IOException)15 Element (org.dom4j.Element)15 FileOutputStream (java.io.FileOutputStream)14 File (java.io.File)11 ByteArrayOutputStream (java.io.ByteArrayOutputStream)10 SAXReader (org.dom4j.io.SAXReader)9 FileWriter (java.io.FileWriter)6 StringWriter (java.io.StringWriter)5 BufferedWriter (java.io.BufferedWriter)4 ByteArrayInputStream (java.io.ByteArrayInputStream)4 OutputStreamWriter (java.io.OutputStreamWriter)3 PrintWriter (java.io.PrintWriter)3 Writer (java.io.Writer)3 ArrayList (java.util.ArrayList)3 HashMap (java.util.HashMap)3 Map (java.util.Map)3 TreeSet (java.util.TreeSet)3