Example usage for org.jdom2.output XMLOutputter XMLOutputter

List of usage examples for org.jdom2.output XMLOutputter XMLOutputter

Introduction

In this page you can find the example usage for org.jdom2.output XMLOutputter XMLOutputter.

Prototype

public XMLOutputter(XMLOutputProcessor processor) 

Source Link

Document

This will create an XMLOutputter with the specified XMLOutputProcessor.

Usage

From source file:net.instantcom.mm7.MM7Message.java

License:Open Source License

@Override
public String toString() {
    XMLOutputter out = new XMLOutputter(Format.getPrettyFormat());
    Document doc = new Document(toSOAP(new MM7Context()));
    StringWriter w = new StringWriter();
    try {/*w  w  w  .j  a  va  2 s  . c  om*/
        out.output(doc, w);
        return w.toString();
    } catch (IOException e) {
        return super.toString();
    }
}

From source file:net.osgiliath.helpers.cxf.exception.handling.jaxrs.mapper.ExceptionXmlMapper.java

License:Apache License

/**
 * Map the catched Exception to the response body (xml format).
 *//*w w w.  java 2 s. c o  m*/
@Override
public Response toResponse(Exception arg0) {
    // On cree une instance de SAXBuilder
    final Element root = new Element("Exception");
    final Document doc = new Document(root);
    this.populateXML(arg0, root);
    final String res = new XMLOutputter(Format.getPrettyFormat()).outputString(doc);
    LOG.info("CXF exception thrown: " + res, arg0);
    return Response.status(Response.Status.FORBIDDEN).type(MediaType.APPLICATION_XML)
            .header(ExceptionMappingConstants.EXCEPTION_BODY_HEADER, res).build();

}

From source file:nl.colorize.util.xml.XMLHelper.java

License:Apache License

private static XMLOutputter getOutputter() {
    Format formatter = Format.getPrettyFormat();
    formatter.setEncoding(Charsets.UTF_8.displayName());
    formatter.setIndent("    ");
    formatter.setLineSeparator(Platform.getLineSeparator());
    formatter.setExpandEmptyElements(false);
    formatter.setOmitDeclaration(false);
    formatter.setOmitEncoding(false);/*from w  w  w. j  a  v a 2 s.c o  m*/

    XMLOutputter outputter = new XMLOutputter(formatter);
    outputter.setFormat(formatter);
    return outputter;
}

From source file:object2xml.JDOMXMLWriter.java

public void writeFileUsingJDOM(List<Pessoa> pessoaList, String fileName) throws IOException {
    Document doc = new Document();
    doc.setRootElement(new Element("Pessoas", ""));
    for (Pessoa p : pessoaList) {
        System.out.println(p);/* www  .j a v  a2  s.com*/
        Element pessoa = new Element("Pessoa");
        pessoa.setAttribute("id", "" + p.getIdentidade());
        pessoa.addContent(new Element("nome").setText(p.getNome()));
        pessoa.addContent(new Element("idade").setText("" + p.getIdade()));
        pessoa.addContent(new Element("peso").setText("" + p.getPeso()));
        Element celulares = new Element("Celulares");
        for (Celular c : p.getCelulares()) {
            Element celular = new Element("Celular");
            celular.setAttribute("id", "" + c.getIdCel());
            celular.addContent(new Element("numero").setText("" + c.getNumero()));
            celular.addContent(new Element("operadora").setText("" + c.getOperadora()));
            celulares.addContent(celular);
        }

        pessoa.addContent(celulares);
        doc.getRootElement().addContent(pessoa);
    }
    //JDOM document is ready now, lets write it to file now
    XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat());
    //output xml to console for debugging
    //xmlOutputter.output(doc, System.out);
    xmlOutputter.output(doc, new FileOutputStream(fileName));
}

From source file:org.apache.marmotta.maven.plugins.refpack.RefPackMojo.java

License:Apache License

private void writeModuleXML(Artifact module, OutputStream out) throws IOException {
    Element installation = new Element("installation");
    installation.setAttribute("version", "1.0");

    Element packs = new Element("packs");
    installation.addContent(packs);//  ww w . j  a v  a  2  s .c om

    Element pack = new Element("pack");
    packs.addContent(pack);

    // get the model for the artifact, we read name and description from it

    Model pom = getArtifactModel(module);

    // set name of pack from artifact
    if (pom != null && pom.getName() != null) {
        pack.setAttribute("name", pom.getName());
    } else {
        pack.setAttribute("name", module.getArtifactId());
    }

    if (pom != null && pom.getDescription() != null) {
        Element description = new Element("description");
        description.setText(Text.normalizeString(pom.getDescription()));
        pack.addContent(description);
    }

    // add a file entry for the module itself
    if (!module.getExtension().equals("war")) {
        Element mainFile = new Element("file");
        pack.addContent(mainFile);
        mainFile.setAttribute("src", module.getFile().getAbsolutePath());
        mainFile.setAttribute("targetdir",
                "$INSTALL_PATH/apache-tomcat-$TOMCAT_VERSION/webapps/marmotta/WEB-INF/lib");
    }

    // add a file entry for each library of the artifact
    for (Artifact library : moduleLibraries.get(module)) {
        Element file = new Element("file");
        pack.addContent(file);
        file.setAttribute("src", library.getFile().getAbsolutePath());
        file.setAttribute("targetdir",
                "$INSTALL_PATH/apache-tomcat-$TOMCAT_VERSION/webapps/marmotta/WEB-INF/lib");
    }

    // add a depends name for each module the current one depends on  (in case the project is not the webapp)
    if (!module.getExtension().equals("war")) {
        if (requiredModules.contains(module.getArtifactId())) {
            pack.setAttribute("required", "yes");
        } else {
            pack.setAttribute("required", "no");
        }

        for (Artifact dependency : moduleDependencies.get(module)) {
            Element depends = new Element("depends");
            pack.addContent(depends);

            // get the model for the artifact, we read name and description from it
            Model pom2 = getArtifactModel(dependency);

            // set name of pack from artifact
            if (pom2 != null && pom2.getName() != null) {
                depends.setAttribute("packname", pom2.getName());
            } else {
                depends.setAttribute("packname", module.getArtifactId());
            }
        }
    } else {
        pack.setAttribute("required", "yes");

        // add webapp directory from installer configuration
        Element appDir = new Element("fileset");
        appDir.setAttribute("dir", outputDirectory + "/../webapp/");
        appDir.setAttribute("targetdir", "$INSTALL_PATH/apache-tomcat-$TOMCAT_VERSION/webapps/marmotta/");
        appDir.setAttribute("includes", "**");

        pack.addContent(appDir);

        Element logDir = new Element("fileset");
        logDir.setAttribute("dir", outputDirectory + "/../log/");

        logDir.setAttribute("targetdir", "$INSTALL_PATH/apache-tomcat-$TOMCAT_VERSION/logs/");
        logDir.setAttribute("includes", "**");

        pack.addContent(logDir);
    }

    XMLOutputter writer = new XMLOutputter(Format.getPrettyFormat());
    writer.output(installation, out);

}

From source file:org.apache.marmotta.platform.sparql.services.sparqlio.sparqlhtml.SPARQLBooleanHTMLWriter.java

License:Apache License

@Override
public void handleBoolean(boolean value) throws QueryResultHandlerException {
    try {/*  w w w .  j a v a2s  . c o m*/
        // Create a SPARQL/XML representation that will be transformed to HTML using a stylesheet
        ByteArrayOutputStream xmlOut = new ByteArrayOutputStream();
        QueryResultIO.writeBoolean(value, BooleanQueryResultFormat.SPARQL, xmlOut);
        byte[] queryResult = xmlOut.toByteArray();

        // get server uri
        String server_uri = CDIContext.getInstance(ConfigurationService.class).getServerUri();

        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out));

        Source input = new StreamSource(new ByteArrayInputStream(queryResult));

        Source s_stylesheet = new StreamSource(SPARQLBooleanHTMLWriter.class.getResourceAsStream("style.xsl"));
        Templates stylesheet = TransformerFactory.newInstance().newTemplates(s_stylesheet);
        Transformer transformer = stylesheet.newTransformer();
        transformer.setParameter("serverurl", server_uri);

        JDOMResult result = new JDOMResult();
        transformer.transform(input, result);
        Document output = result.getDocument();

        XMLOutputter printer = new XMLOutputter(Format.getPrettyFormat());
        printer.output(output, writer);
        writer.flush();
    } catch (TransformerConfigurationException e) {
        log.error("could not compile stylesheet for rendering SPARQL results; result display not available!");
        throw new QueryResultHandlerException(
                "could not compile stylesheet for rendering SPARQL results; result display not available!", e);
    } catch (Exception ex) {
        throw new QueryResultHandlerException("error while transforming XML results to HTML", ex);
    } finally {
        // writer.close();
    }
}

From source file:org.apache.marmotta.platform.sparql.services.sparqlio.sparqlhtml.SPARQLResultsHTMLWriterXSL.java

License:Apache License

/**
 * Indicates the end of a sequence of solutions.
 *///from w w  w  .  j a v a  2s .com
@Override
public void endQueryResult() throws TupleQueryResultHandlerException {
    writer.endQueryResult();

    // get server uri
    String server_uri = CDIContext.getInstance(ConfigurationService.class).getServerUri();

    byte[] queryResult = xmlOut.toByteArray();

    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out));
    try {
        Source input = new StreamSource(new ByteArrayInputStream(queryResult));

        Transformer transformer = stylesheet.newTransformer();
        transformer.setParameter("serverurl", server_uri);

        JDOMResult result = new JDOMResult();
        transformer.transform(input, result);
        Document output = result.getDocument();

        XMLOutputter printer = new XMLOutputter(Format.getPrettyFormat());
        printer.output(output, writer);
        writer.flush();

    } catch (Exception ex) {
        throw new TupleQueryResultHandlerException("error while transforming XML results to HTML", ex);
    } finally {
        try {
            writer.close();
        } catch (IOException e) {
        }
    }

}

From source file:org.apache.maven.io.util.AbstractJDOMWriter.java

License:Apache License

public final void write(final T source, final Document document, final Writer writer, final Format jdomFormat,
        final DocumentModifier modifier) throws java.io.IOException {
    if (modifier != null) {
        modifier.preProcess(document);//  w w  w.  ja  va2  s  .  c o m
    }
    update(source, new IndentationCounter(0), document.getRootElement());
    if (modifier != null) {
        modifier.postProcess(document);
    }
    // Override XMLOutputter to correct initial comment trailing newlines.
    final XMLOutputter outputter = new XMLOutputter(new AbstractXMLOutputProcessor() {
        /**
         * This will handle printing of a {@link Document}.
         *
         * @param out    <code>Writer</code> to use.
         * @param fstack the FormatStack
         * @param nstack the NamespaceStack
         * @param doc    <code>Document</code> to write.
         * @throws IOException if the destination Writer fails
         */
        @Override
        protected void printDocument(Writer out, FormatStack fstack, NamespaceStack nstack, Document doc)
                throws IOException {

            // If there is no root element then we cannot use the normal ways to
            // access the ContentList because Document throws an exception.
            // so we hack it and just access it by index.
            List<Content> list = doc.hasRootElement() ? doc.getContent()
                    : new ArrayList<Content>(doc.getContentSize());
            if (list.isEmpty()) {
                final int sz = doc.getContentSize();
                for (int i = 0; i < sz; i++) {
                    list.add(doc.getContent(i));
                }
            }

            printDeclaration(out, fstack);

            Walker walker = buildWalker(fstack, list, true);
            if (walker.hasNext()) {
                while (walker.hasNext()) {

                    final Content c = walker.next();
                    // we do not ignore Text-like things in the Document.
                    // the walker creates the indenting for us.
                    if (c == null) {
                        // but, what we do is ensure it is all whitespace, and not CDATA
                        final String padding = walker.text();
                        if (padding != null && Verifier.isAllXMLWhitespace(padding) && !walker.isCDATA()) {
                            // we do not use the escaping or text* method because this
                            // content is outside of the root element, and thus is not
                            // strict text.
                            write(out, padding);
                        }
                    } else {
                        switch (c.getCType()) {
                        case Comment:
                            printComment(out, fstack, (Comment) c);
                            // This modification we have made to the overridden method in order
                            // to correct newline declarations.
                            write(out, fstack.getLineSeparator());
                            break;
                        case DocType:
                            printDocType(out, fstack, (DocType) c);
                            break;
                        case Element:
                            printElement(out, fstack, nstack, (Element) c);
                            if (walker.hasNext()) {
                                // This modification we have made to the overridden method in order
                                // to correct newline declarations.
                                write(out, fstack.getLineSeparator());
                            }
                            break;
                        case ProcessingInstruction:
                            printProcessingInstruction(out, fstack, (ProcessingInstruction) c);
                            break;
                        case Text:
                            final String padding = ((Text) c).getText();
                            if (padding != null && Verifier.isAllXMLWhitespace(padding)) {
                                // we do not use the escaping or text* method because this
                                // content is outside of the root element, and thus is not
                                // strict text.
                                write(out, padding);
                            }
                        default:
                            // do nothing.
                        }
                    }

                }

                if (fstack.getLineSeparator() != null) {
                    write(out, fstack.getLineSeparator());
                }
            }
        }
    });

    outputter.setFormat(jdomFormat);
    outputter.output(document, writer);
}

From source file:org.apache.wiki.plugin.IndexPlugin.java

License:Apache License

/**
 * {@inheritDoc}//from   w ww .  jav  a2  s . c o  m
 */
public String execute(WikiContext context, Map<String, String> params) throws PluginException {
    String include = params.get(PARAM_INCLUDE);
    String exclude = params.get(PARAM_EXCLUDE);

    Element masterDiv = getElement("div", "index");
    Element indexDiv = getElement("div", "header");
    masterDiv.addContent(indexDiv);
    try {
        List<String> pages = listPages(context, include, exclude);
        context.getEngine().getPageSorter().sort(pages);
        char initialChar = ' ';
        Element currentDiv = new Element("div", xmlns_XHTML);
        for (String name : pages) {
            if (name.charAt(0) != initialChar) {
                if (initialChar != ' ') {
                    indexDiv.addContent(" - ");
                }
                initialChar = name.charAt(0);
                masterDiv.addContent(makeHeader(String.valueOf(initialChar)));
                currentDiv = getElement("div", "body");
                masterDiv.addContent(currentDiv);
                indexDiv.addContent(getLink("#" + initialChar, String.valueOf(initialChar)));
            } else {
                currentDiv.addContent(", ");
            }
            currentDiv.addContent(getLink(context.getURL(WikiContext.VIEW, name), name));
        }

    } catch (ProviderException e) {
        log.warn("could not load page index", e);
        throw new PluginException(e.getMessage());
    }
    // serialize to raw format string (no changes to whitespace)
    XMLOutputter out = new XMLOutputter(Format.getRawFormat());
    return out.outputString(masterDiv);
}

From source file:org.apache.wiki.util.XhtmlUtil.java

License:Apache License

/**
 *  Serializes the Element to a String. Allows to use a custom <tt>format</tt>.
 *  // ww w  .j a  v a  2  s .  co  m
 * @param element  the element to serialize.
 * @param format   custom <tt>format</tt> used to serialize the Element.
 * @return the serialized Element.
 */
public static String serialize(Element element, Format format) {
    XMLOutputter out = new XMLOutputter(format);
    return out.outputString(element);
}