Example usage for org.dom4j.io OutputFormat createCompactFormat

List of usage examples for org.dom4j.io OutputFormat createCompactFormat

Introduction

In this page you can find the example usage for org.dom4j.io OutputFormat createCompactFormat.

Prototype

public static OutputFormat createCompactFormat() 

Source Link

Document

A static helper method to create the default compact format.

Usage

From source file:org.infoglue.cms.util.dom.DOMBuilder.java

License:Open Source License

/**
 * This method gets the xml as a string with the correct encoding.
 *//*from w  ww.  ja  va  2s.c o m*/

private String getEncodedString(Element element) throws Exception {
    OutputFormat outFormat = OutputFormat.createCompactFormat();
    outFormat.setEncoding("UTF-8");
    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    XMLWriter out = new XMLWriter(bao, outFormat);
    out.write(element);
    out.flush();
    String s = bao.toString();
    logger.info("OUT: " + s);
    return s;
}

From source file:org.infoglue.cms.util.dom.DOMBuilder.java

License:Open Source License

public String getFormattedDocument(Document doc, boolean compact, boolean supressDecl, String encoding) {
    OutputFormat format = compact ? OutputFormat.createCompactFormat() : OutputFormat.createPrettyPrint();
    format.setSuppressDeclaration(supressDecl);
    format.setEncoding(encoding);/*from   ww w.java  2 s.c o m*/
    format.setExpandEmptyElements(false);
    StringWriter stringWriter = new StringWriter();
    XMLWriter writer = new XMLWriter(stringWriter, format);
    try {
        writer.write(doc);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return stringWriter.toString();
}

From source file:org.infoglue.common.util.dom.DOMBuilder.java

License:Open Source License

/**
 * This method writes a document to file.
 *//*  ww  w  .j a v  a 2  s.  c o m*/

public void write(Document document, String fileName) throws Exception {
    OutputFormat format = OutputFormat.createCompactFormat();
    format.setEncoding("UTF-8");
    XMLWriter writer = new XMLWriter(new FileWriter(fileName), format);
    writer.write(document);
    writer.close();

    /*
    FileHelper.writeToFile(new File(fileName + "2"), document.asXML(), false);
    FileHelper.writeUTF8ToFileSpecial(new File(fileName + "3"), document.asXML(), false);
    FileHelper.writeUTF8(new File(fileName + "4"), document.asXML(), false);
    FileHelper.writeUTF8ToFile(new File(fileName + "5"), document.asXML(), false);
    */
}

From source file:org.itracker.web.util.ImportExportUtilities.java

License:Open Source License

/**
 * export the issues to an XML and write it to the response.
 * @param issues//  ww w . j  a va  2  s  .  c om
 * @param config
 * @param request
 * @param response
 * @return  if <code>true</code> the export was sucessful.
 * @throws ServletException
 * @throws IOException
 */
public static boolean exportIssues(List<Issue> issues, SystemConfiguration config, HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {

    response.setContentType("text/xml; charset=UTF-8");
    response.setHeader("Content-Disposition", "attachment; filename=\"issue_export.xml\"");

    XMLWriter writer = new XMLWriter(response.getOutputStream(), OutputFormat.createCompactFormat());

    try {
        // TODO instead to have a string returned, it should directly serialize the
        // export to the response-writer.
        ImportExportUtilities.exportIssues(writer, issues, config);

    } catch (ImportExportException iee) {
        logger.error("Error exporting issue data. Message: " + iee.getMessage(), iee);
        return false;
    } finally {
        if (null != writer) {
            writer.flush();
            writer.close();
        }
    }

    return true;
}

From source file:org.jbpm.instantiation.Delegation.java

License:Open Source License

public void read(Element delegateElement, JpdlXmlReader jpdlReader) {
    processDefinition = jpdlReader.getProcessDefinition();
    className = delegateElement.attributeValue("class");
    if (className == null) {
        jpdlReader.addWarning("no class specified in " + delegateElement.asXML());
    }//from w ww.  j ava 2s.c  o m

    configType = delegateElement.attributeValue("config-type");
    if (delegateElement.hasContent()) {
        try {
            StringWriter stringWriter = new StringWriter();
            // when parsing, it could be to store the config in the database, so we want to make the configuration compact
            XMLWriter xmlWriter = new XMLWriter(stringWriter, OutputFormat.createCompactFormat());
            Iterator iter = delegateElement.content().iterator();
            while (iter.hasNext()) {
                Object node = iter.next();
                xmlWriter.write(node);
            }
            xmlWriter.flush();
            configuration = stringWriter.toString();
        } catch (IOException e) {
            jpdlReader.addWarning("io problem while parsing the configuration of " + delegateElement.asXML());
        }
    }
}

From source file:org.jin.dic.data.pub.ldoce.v5.Convert2Html.java

License:Open Source License

private static byte[] convert(String data) throws DocumentException, IOException {
    data = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
            + rmES.matcher(rmDummyTag.matcher(data).replaceAll("")).replaceAll("");
    data = data.replaceAll("\\|", ",");
    _ByteArrayOutputStream bos = new _ByteArrayOutputStream();
    _ByteArrayInputStream bis = new _ByteArrayInputStream(data.getBytes("utf-8"));
    SAXReader saxR = null;/*from   www  . j av  a 2 s .  c o  m*/
    Document doc = null, des = null;
    Element root = null, desRoot = null;
    XMLWriter xmlWriter = null;
    OutputFormat fmt = null;
    saxR = new SAXReader();
    doc = saxR.read(bis);
    root = doc.getRootElement();

    des = DocumentHelper.createDocument();
    desRoot = DocumentHelper.createElement("span");
    desRoot.addAttribute("class", getClass(root));
    Element child;
    List children = root.elements();
    for (int i = 0; i < children.size(); i++) {
        child = (Element) children.get(i);
        addChildren(child, desRoot);
    }
    des.setRootElement(desRoot);

    fmt = OutputFormat.createCompactFormat();
    fmt.setEncoding("utf-16le");
    fmt.setTrimText(false);
    xmlWriter = new XMLWriter(bos, fmt);
    xmlWriter.write(des);
    xmlWriter.close();
    return bos.toByteArray();
}

From source file:org.onosproject.xmpp.core.stream.XmppStreamOpen.java

License:Apache License

@Override
public String toXml() {
    StringWriter out = new StringWriter();
    XMLWriter writer = new XMLWriter(out, OutputFormat.createCompactFormat());
    try {/*from ww w  . j a  va  2 s  . c  o m*/
        out.write("<");
        writer.write(element.getQualifiedName());
        for (Attribute attr : (List<Attribute>) element.attributes()) {
            writer.write(attr);
        }
        writer.write(Namespace.get(this.element.getNamespacePrefix(), this.element.getNamespaceURI()));
        writer.write(Namespace.get("jabber:client"));
        out.write(">");
    } catch (IOException ex) {
        log.info("Error writing XML", ex);
    }
    return out.toString();
}

From source file:org.openadaptor.auxil.convertor.xml.AbstractTestXmlConvertor.java

License:Open Source License

protected static String docAsString(Document doc, String encoding) {
    StringWriter sw = new StringWriter();
    OutputFormat outputFormat = OutputFormat.createCompactFormat();
    if (encoding != null) {
        outputFormat.setEncoding(encoding); // This definitely sets it in the header!
    }//from   w ww. j ava 2s  . co m
    XMLWriter writer = new XMLWriter(sw, outputFormat);
    try {
        writer.write(doc);
    } catch (IOException ioe) {
        fail("Failed to write XML as a String. Reason: " + ioe.toString());
    }
    return sw.toString();
}

From source file:org.openadaptor.auxil.convertor.xml.OrderedMapToXmlConvertor.java

License:Open Source License

/**
 * Performs the actual conversion. Will recursively add each element of the map as
 * //w w w  .  j av  a 2  s .c  o  m
 * @param map
 *          the map to be converted
 * @param returnAsString
 *          if true then the Dom4j Document is returned
 * 
 * @return the xml (or Dom4j Document) corresponding to the supplied OrderedMap
 * 
 * @throws RecordException
 *           if the conversion fails
 */
private Object convertOrderedMapToXml(IOrderedMap map, boolean returnAsString) throws RecordException {
    Object result = null;

    // Create a Document to hold the data.
    Document doc = DocumentHelper.createDocument();
    if (encoding != null) {
        // Doesn't seem to have any effect here, so output formatter also sets it
        doc.setXMLEncoding(encoding);
        log.debug("Document encoding now " + doc.getXMLEncoding());
    }

    String rootTag = rootElementTag;

    if (rootTag != null) {
        log.debug("Using Supplied root tag - unset rootElementTag property to disable");
    } else { // Try and derive it. Must have a single entry, whose value is itself an OM.
        log.debug("rootElementTag property is not set. Deriving root tag from data.");
        if (map.size() == 1) { // Might be able to derive root tag.
            Object rootTagObject = map.keys().get(0);
            rootTag = rootTagObject == null ? null : rootTagObject.toString();
            Object value = map.get(rootTag);
            if (value instanceof IOrderedMap) { // Bingo we're in.
                log.debug(
                        "Deriving rootElementTag property from map (set rootElementTag property explicitly to prevent this");
                map = (IOrderedMap) value; // Move down a level as we're adding it here.
            } else {// No go -be safe and add our own root.
                log.warn("Failed to derive root tag. Using default of "
                        + OrderedMapToXmlConvertor.DEFAULT_ROOT_ELEMENT_TAG);
                rootTag = OrderedMapToXmlConvertor.DEFAULT_ROOT_ELEMENT_TAG;
            }
        } else {// More than one top level entry. Give up and default.
            log.warn("Top level has more than one entry. Using default of "
                    + OrderedMapToXmlConvertor.DEFAULT_ROOT_ELEMENT_TAG);
            rootTag = OrderedMapToXmlConvertor.DEFAULT_ROOT_ELEMENT_TAG;
        }
    }
    //Fix for #SC35: OrderedMapToXmlConvertor should, but does not map slashes in the root tag 
    rootTag = generateElementName(rootTag);
    log.debug("Document root tag will be: " + rootTag);

    // Prime the root tag.
    Element root = doc.addElement(rootTag);

    Iterator it = map.keys().iterator();
    while (it.hasNext()) {
        String key = it.next().toString();
        Object value = map.get(key);
        addElement(root, key, value);
    }
    // document done. Phew.
    if (returnAsString) { // Darn, need to output the Document as a String.
        StringWriter sw = new StringWriter();
        OutputFormat outputFormat = OutputFormat.createCompactFormat();
        if (encoding != null) {
            log.debug("Output Format encoding as " + encoding);
            outputFormat.setEncoding(encoding); // This definitely sets it in the header!
        }
        //    outputFormat.setOmitEncoding(true);
        //    outputFormat.setSuppressDeclaration(true);
        XMLWriter writer = new XMLWriter(sw, outputFormat);
        try {
            writer.write(doc);
        } catch (IOException ioe) {
            log.warn("Failed to write the XML as a String");
            throw new RecordFormatException("Failed to write the XML as a String. Reason: " + ioe.toString(),
                    ioe);
        }
        result = sw.toString();
    } else {
        result = doc;
    }
    return result;
}

From source file:org.pentaho.platform.util.xml.dom4j.XmlDom4JHelper.java

License:Open Source License

public static void saveDom(final Document doc, final OutputStream outputStream, String encoding,
        boolean suppressDeclaration, boolean prettyPrint) throws IOException {
    OutputFormat format = prettyPrint ? OutputFormat.createPrettyPrint() : OutputFormat.createCompactFormat();
    format.setSuppressDeclaration(suppressDeclaration);
    if (encoding != null) {
        format.setEncoding(encoding.toLowerCase());
        if (!suppressDeclaration) {
            doc.setXMLEncoding(encoding.toUpperCase());
        }//from  ww w .j a v a2  s  .  c o  m
    }
    XMLWriter writer = new XMLWriter(outputStream, format);
    writer.write(doc);
    writer.flush();
}