Example usage for org.w3c.dom.ls LSOutput setCharacterStream

List of usage examples for org.w3c.dom.ls LSOutput setCharacterStream

Introduction

In this page you can find the example usage for org.w3c.dom.ls LSOutput setCharacterStream.

Prototype

public void setCharacterStream(java.io.Writer characterStream);

Source Link

Document

An attribute of a language and binding dependent type that represents a writable stream to which 16-bit units can be output.

Usage

From source file:Main.java

public static String prettyPrint(Document document) {
    // Pretty-prints a DOM document to XML using DOM Load and Save's
    // LSSerializer.
    // Note that the "format-pretty-print" DOM configuration parameter can
    // only be set in JDK 1.6+.

    DOMImplementationRegistry domImplementationRegistry;
    try {/*from   ww w. j av  a  2 s .c  o m*/
        domImplementationRegistry = DOMImplementationRegistry.newInstance();
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | ClassCastException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        throw new RuntimeException(e);
    }
    DOMImplementation domImplementation = document.getImplementation();
    if (domImplementation.hasFeature("LS", "3.0") && domImplementation.hasFeature("Core", "2.0")) {
        /*DOMImplementationLS domImplementationLS = (DOMImplementationLS) domImplementation
          .getFeature("LS", "3.0");*/
        DOMImplementationLS domImplementationLS = (DOMImplementationLS) domImplementationRegistry
                .getDOMImplementation("LS");

        LSSerializer lsSerializer = domImplementationLS.createLSSerializer();
        DOMConfiguration domConfiguration = lsSerializer.getDomConfig();
        if (domConfiguration.canSetParameter("format-pretty-print", Boolean.TRUE)) {
            lsSerializer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);
            LSOutput lsOutput = domImplementationLS.createLSOutput();
            lsOutput.setEncoding("UTF-8");
            StringWriter stringWriter = new StringWriter();
            lsOutput.setCharacterStream(stringWriter);
            lsSerializer.write(document, lsOutput);
            return stringWriter.toString();
        } else {
            throw new RuntimeException("DOMConfiguration 'format-pretty-print' parameter isn't settable.");
        }
    } else {
        throw new RuntimeException("DOM 3.0 LS and/or DOM 2.0 Core not supported.");
    }
}

From source file:Main.java

/**
 * Converts a dom element to a String/*from ww w  .j  av a2  s  .co m*/
 * 
 * @param node
 * @return the dom as a String
 */
public static String writeDomToString(Element node) {
    DOMImplementation domImplementation = node.getOwnerDocument().getImplementation();
    if (domImplementation.hasFeature("LS", "3.0") && domImplementation.hasFeature("Core", "2.0")) {
        DOMImplementationLS domImplementationLS = (DOMImplementationLS) domImplementation.getFeature("LS",
                "3.0");
        LSSerializer lsSerializer = domImplementationLS.createLSSerializer();

        LSOutput lsOutput = domImplementationLS.createLSOutput();
        lsOutput.setEncoding("UTF-8");

        StringWriter stringWriter = new StringWriter();
        lsOutput.setCharacterStream(stringWriter);
        lsSerializer.write(node, lsOutput);
        return stringWriter.toString();
    } else {
        throw new RuntimeException("DOM 3.0 LS and/or DOM 2.0 Core not supported.");
    }
}

From source file:eu.semaine.util.XMLTool.java

/**
 * Document type to String format conversion 
 * @param document//from  ww  w.ja v a  2  s  .c o  m
 * @return
 * @throws Exception
 * @throws FileNotFoundException
 */
public static String document2String(Document document) throws SystemConfigurationException {
    LSSerializer serializer;
    DOMImplementationLS domImplLS;
    try {
        DOMImplementation implementation = DOMImplementationRegistry.newInstance()
                .getDOMImplementation("XML 3.0");
        domImplLS = (DOMImplementationLS) implementation.getFeature("LS", "3.0");
        serializer = domImplLS.createLSSerializer();
        DOMConfiguration config = serializer.getDomConfig();
        config.setParameter("format-pretty-print", Boolean.TRUE);
        //config.setParameter("canonical-form", Boolean.TRUE);
    } catch (Exception e) {
        throw new SystemConfigurationException("Problem instantiating XML serializer code", e);
    }
    LSOutput output = domImplLS.createLSOutput();
    output.setEncoding("UTF-8");
    StringWriter buf = new StringWriter();
    output.setCharacterStream(buf);
    serializer.write(document, output);
    return buf.toString();
}

From source file:edu.wfu.inotado.helper.MarshalHelper.java

/**
 * Pretty-Prints the XML//from  www  .  j a  v a 2s .  c  o m
 * 
 * @param xml
 * @return
 */
@SuppressWarnings("unused")
private String prettyPrintXml(String xml) {
    DocumentBuilder documentBuilder;
    StringWriter stringWriter = new StringWriter();
    try {
        documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        InputStream inputStream = new ByteArrayInputStream(xml.getBytes("UTF8"));
        Document document = documentBuilder.parse(inputStream);
        DOMImplementation domImplementation = document.getImplementation();

        if (domImplementation.hasFeature("LS", "3.0") && domImplementation.hasFeature("Core", "2.0")) {
            DOMImplementationLS domImplementationLS = (DOMImplementationLS) domImplementation.getFeature("LS",
                    "3.0");
            LSSerializer lsSerializer = domImplementationLS.createLSSerializer();
            DOMConfiguration domConfiguration = lsSerializer.getDomConfig();
            if (domConfiguration.canSetParameter("format-pretty-print", Boolean.TRUE)) {
                lsSerializer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);
                LSOutput lsOutput = domImplementationLS.createLSOutput();
                lsOutput.setEncoding("UTF-8");

                lsOutput.setCharacterStream(stringWriter);
                lsSerializer.write(document, lsOutput);
                return stringWriter.toString();
            } else {
                log.warn("DOMConfiguration 'format-pretty-print' parameter isn't settable.");
            }
        } else {
            log.warn("DOM 3.0 LS and/or DOM 2.0 Core not supported.");
        }
    } catch (ParserConfigurationException e) {
        log.error("Unable to parse xml: " + xml, e);
    } catch (UnsupportedEncodingException e) {
        log.error("Encoding unspported for xml: " + xml, e);
    } catch (SAXException e) {
        log.error("SAXException occurred: " + xml, e);
    } catch (IOException e) {
        log.error("IOException occurred:" + xml, e);
    }
    // return the input string if any error occurs
    return xml;
}

From source file:com.msopentech.odatajclient.engine.performance.BasicPerfTest.java

@Test
public void writeAtomViaLowerlevelLibs() throws ParserConfigurationException, ClassNotFoundException,
        InstantiationException, IllegalAccessException {

    final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    final DocumentBuilder builder = factory.newDocumentBuilder();
    final Document doc = builder.newDocument();

    final Element entry = doc.createElement("entry");
    entry.setAttribute("xmlns", "http://www.w3.org/2005/Atom");
    entry.setAttribute("xmlns:m", "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata");
    entry.setAttribute("xmlns:d", "http://schemas.microsoft.com/ado/2007/08/dataservices");
    entry.setAttribute("xmlns:gml", "http://www.opengis.net/gml");
    entry.setAttribute("xmlns:georss", "http://www.georss.org/georss");
    doc.appendChild(entry);/*from w w  w  . j a v a  2  s .c  o m*/

    final Element category = doc.createElement("category");
    category.setAttribute("term", "Microsoft.Test.OData.Services.AstoriaDefaultService.Customer");
    category.setAttribute("scheme", "http://schemas.microsoft.com/ado/2007/08/dataservices/scheme");
    entry.appendChild(category);

    final Element properties = doc.createElement("m:properties");
    entry.appendChild(properties);

    final Element name = doc.createElement("d:Name");
    name.setAttribute("m:type", "Edm.String");
    name.appendChild(doc.createTextNode("A name"));
    properties.appendChild(name);

    final Element customerId = doc.createElement("d:CustomerId");
    customerId.setAttribute("m:type", "Edm.Int32");
    customerId.appendChild(doc.createTextNode("0"));
    properties.appendChild(customerId);

    final Element bci = doc.createElement("d:BackupContactInfo");
    bci.setAttribute("m:type",
            "Collection(Microsoft.Test.OData.Services.AstoriaDefaultService.ContactDetails)");
    properties.appendChild(bci);

    final Element topelement = doc.createElement("d:element");
    topelement.setAttribute("m:type", "Microsoft.Test.OData.Services.AstoriaDefaultService.ContactDetails");
    bci.appendChild(topelement);

    final Element altNames = doc.createElement("d:AlternativeNames");
    altNames.setAttribute("m:type", "Collection(Edm.String)");
    topelement.appendChild(altNames);

    final Element element1 = doc.createElement("d:element");
    element1.setAttribute("m:type", "Edm.String");
    element1.appendChild(doc.createTextNode("myname"));
    altNames.appendChild(element1);

    final Element emailBag = doc.createElement("d:EmailBag");
    emailBag.setAttribute("m:type", "Collection(Edm.String)");
    topelement.appendChild(emailBag);

    final Element element2 = doc.createElement("d:element");
    element2.setAttribute("m:type", "Edm.String");
    element2.appendChild(doc.createTextNode("myname@mydomain.com"));
    emailBag.appendChild(element2);

    final Element contactAlias = doc.createElement("d:ContactAlias");
    contactAlias.setAttribute("m:type", "Microsoft.Test.OData.Services.AstoriaDefaultService.Aliases");
    topelement.appendChild(contactAlias);

    final Element altNames2 = doc.createElement("d:AlternativeNames");
    altNames2.setAttribute("m:type", "Collection(Edm.String)");
    contactAlias.appendChild(altNames2);

    final Element element3 = doc.createElement("d:element");
    element3.setAttribute("m:type", "Edm.String");
    element3.appendChild(doc.createTextNode("myAlternativeName"));
    altNames2.appendChild(element3);

    final StringWriter writer = new StringWriter();

    final DOMImplementationRegistry reg = DOMImplementationRegistry.newInstance();
    final DOMImplementationLS impl = (DOMImplementationLS) reg.getDOMImplementation("LS");
    final LSSerializer serializer = impl.createLSSerializer();
    final LSOutput lso = impl.createLSOutput();
    lso.setCharacterStream(writer);
    serializer.write(doc, lso);

    assertFalse(writer.toString().isEmpty());
}

From source file:com.redhat.plugin.eap6.AbstractEAP6Mojo.java

/**
 * method to convert Document to String/*  w ww  .ja v a2  s  . c  o  m*/
 *
 * @param doc
 * @return
 */
protected String getStringFromDocument(final Document doc) {
    try {
        final StringWriter writer = new StringWriter();
        final DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation();
        final LSSerializer lsSerializer = domImplementation.createLSSerializer();
        lsSerializer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);

        final LSOutput lsOutput = domImplementation.createLSOutput();
        lsOutput.setCharacterStream(writer);
        lsSerializer.write(doc, lsOutput);

        return writer.toString();
    } catch (final LSException ex) {
        getLog().error(ex);
        return null;
    }
}

From source file:com.xpn.xwiki.pdf.impl.PdfExportImpl.java

/**
 * Cleans up an HTML document, turning it into valid XHTML.
 * /*  w w  w  . j av  a  2 s  . com*/
 * @param input the source HTML to process
 * @return the cleaned up source
 */
private String convertToStrictXHtml(String input) {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Cleaning HTML: " + input);
    }

    try {
        // First step, Tidy the document
        StringWriter tidyOutput = new StringWriter(input.length());
        this.tidy.parse(new StringReader(input), tidyOutput);

        // Tidy can't solve duplicate IDs, so it needs to be done manually
        DocumentBuilder docBuilder = dbFactory.newDocumentBuilder();
        docBuilder.setEntityResolver(Utils.getComponent(EntityResolver.class));
        String tidied = tidyOutput.toString().trim();
        if (StringUtils.isEmpty(tidied)) {
            tidied = input.trim();
        }
        Document doc = docBuilder.parse(new InputSource(new StringReader(tidied)));
        List<String> seenIDs = new ArrayList<String>();
        this.cleanIDs(doc.getDocumentElement(), seenIDs);

        // Write back the fixed document to a String
        LSOutput output = lsImpl.createLSOutput();
        StringWriter result = new StringWriter();
        output.setCharacterStream(result);
        LSSerializer serializer = lsImpl.createLSSerializer();
        serializer.setNewLine("\n");
        output.setEncoding(doc.getXmlEncoding());
        serializer.write(doc, output);
        return result.toString();
    } catch (Exception ex) {
        LOGGER.warn("Failed to tidy document for export: " + ex.getMessage(), ex);
        return input;
    }
}

From source file:edu.ur.ir.ir_export.service.DefaultContributorTypeExportService.java

/** 
 * Create the xml file for the set of collections.
 * //from  ww  w. j  av  a2 s .  c o m
 * @param xmlFile - file to write the xml to
 * @param contributor types - set of contributor types to export
 * 
 * @throws IOException - if writing to the file fails.
 */
public void createXmlFile(File xmlFile, Collection<ContributorType> contributorTypes) throws IOException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder;

    String path = FilenameUtils.getPath(xmlFile.getCanonicalPath());
    if (!path.equals("")) {
        File pathOnly = new File(FilenameUtils.getFullPath(xmlFile.getCanonicalPath()));
        FileUtils.forceMkdir(pathOnly);
    }

    if (!xmlFile.exists()) {
        if (!xmlFile.createNewFile()) {
            throw new IllegalStateException("could not create file");
        }
    }

    try {
        builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        throw new IllegalStateException(e);
    }

    DOMImplementation impl = builder.getDOMImplementation();
    DOMImplementationLS domLs = (DOMImplementationLS) impl.getFeature("LS", "3.0");
    LSSerializer serializer = domLs.createLSSerializer();
    LSOutput lsOut = domLs.createLSOutput();

    Document doc = impl.createDocument(null, "contributor_types", null);
    Element root = doc.getDocumentElement();

    FileOutputStream fos;
    OutputStreamWriter outputStreamWriter;
    BufferedWriter writer;

    try {
        fos = new FileOutputStream(xmlFile);

        try {
            outputStreamWriter = new OutputStreamWriter(fos, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new IllegalStateException(e);
        }
        writer = new BufferedWriter(outputStreamWriter);
        lsOut.setCharacterStream(writer);
    } catch (FileNotFoundException e) {
        throw new IllegalStateException(e);
    }

    // create XML for the child collections
    for (ContributorType ct : contributorTypes) {
        Element contributorType = doc.createElement("contributor_type");

        this.addIdElement(contributorType, ct.getId().toString(), doc);
        this.addNameElement(contributorType, ct.getName(), doc);
        this.addDescription(contributorType, ct.getDescription(), doc);
        this.addSystemCode(contributorType, ct.getUniqueSystemCode(), doc);
    }
    serializer.write(root, lsOut);

    try {
        fos.close();
        writer.close();
        outputStreamWriter.close();
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }

}

From source file:edu.ur.ir.ir_export.service.DefaultCollectionExportService.java

/**
 * Generate an xml file with the specified collections.
 * //w  w w  .j  av a  2  s  . c o m
 * @see edu.ur.dspace.export.CollectionExporter#generateCollectionXMLFile(java.io.File, java.util.Collection)
 */
public Set<FileInfo> createXmlFile(File f, Collection<InstitutionalCollection> collections,
        boolean includeChildren) throws IOException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder;

    Set<FileInfo> allPictures = new HashSet<FileInfo>();
    String path = FilenameUtils.getPath(f.getCanonicalPath());
    if (!path.equals("")) {
        File pathOnly = new File(FilenameUtils.getFullPath(f.getCanonicalPath()));
        FileUtils.forceMkdir(pathOnly);
    }

    if (!f.exists()) {
        if (!f.createNewFile()) {
            throw new IllegalStateException("could not create file");
        }
    }

    try {
        builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        throw new IllegalStateException(e);
    }

    DOMImplementation impl = builder.getDOMImplementation();
    DOMImplementationLS domLs = (DOMImplementationLS) impl.getFeature("LS", "3.0");
    LSSerializer serializer = domLs.createLSSerializer();
    LSOutput lsOut = domLs.createLSOutput();

    Document doc = impl.createDocument(null, "institutionalCollections", null);
    Element root = doc.getDocumentElement();

    FileOutputStream fos;
    OutputStreamWriter outputStreamWriter;
    BufferedWriter writer;

    try {
        fos = new FileOutputStream(f);

        try {
            outputStreamWriter = new OutputStreamWriter(fos, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new IllegalStateException(e);
        }
        writer = new BufferedWriter(outputStreamWriter);
        lsOut.setCharacterStream(writer);
    } catch (FileNotFoundException e) {
        throw new IllegalStateException(e);
    }

    // create XML for the child collections
    for (InstitutionalCollection c : collections) {
        Element collection = doc.createElement("collection");

        this.addIdElement(collection, c.getId().toString(), doc);
        this.addNameElement(collection, c.getName(), doc);
        this.addDescription(collection, c.getDescription(), doc);
        this.addCopyright(collection, c.getCopyright(), doc);

        if (c.getPrimaryPicture() != null) {
            this.addPrimaryImage(collection, c.getPrimaryPicture().getFileInfo().getNameWithExtension(), doc);
            allPictures.add(c.getPrimaryPicture().getFileInfo());
        }
        Set<IrFile> pictures = c.getPictures();

        if (pictures.size() > 0) {
            Element pics = doc.createElement("pictures");
            for (IrFile irFile : pictures) {
                Element picture = doc.createElement("picture");
                this.addImage(picture, irFile.getFileInfo().getNameWithExtension(), doc);
                pics.appendChild(picture);
                allPictures.add(irFile.getFileInfo());
            }
            collection.appendChild(pics);
        }

        if (c.getLinks().size() > 0) {
            Element links = doc.createElement("links");
            for (InstitutionalCollectionLink l : c.getLinks()) {
                this.addLink(links, l, doc);
            }
            collection.appendChild(links);
        }

        if (includeChildren) {
            for (InstitutionalCollection child : c.getChildren()) {
                addChild(child, collection, doc, allPictures);
            }
        }
        root.appendChild(collection);
    }
    serializer.write(root, lsOut);

    try {
        fos.close();
        writer.close();
        outputStreamWriter.close();
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
    return allPictures;
}

From source file:net.svcret.core.util.XMLUtils.java

public static void serialize(Document document, boolean prettyPrint, Writer theWriter) {
    DOMImplementationLS impl = getDOMImpl();
    LSSerializer serializer = impl.createLSSerializer();
    // document.normalizeDocument();
    DOMConfiguration config = serializer.getDomConfig();
    if (prettyPrint && config.canSetParameter("format-pretty-print", Boolean.TRUE)) {
        config.setParameter("format-pretty-print", true);
    }/* w w  w  .j  ava2 s  .c o m*/
    config.setParameter("xml-declaration", true);
    LSOutput output = impl.createLSOutput();
    output.setEncoding("UTF-8");
    output.setCharacterStream(theWriter);
    serializer.write(document, output);
}