Java Code Examples for org.w3c.dom.ls.LSSerializer#getDomConfig()

The following examples show how to use org.w3c.dom.ls.LSSerializer#getDomConfig() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: XMLHelper.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Obtain a the DOM, level 3, Load/Save serializer {@link LSSerializer} instance from the
 * given {@link DOMImplementationLS} instance.
 * 
 * <p>
 * The serializer instance will be configured with the parameters passed as the <code>serializerParams</code>
 * argument. It will also be configured with an {@link LSSerializerFilter} that shows all nodes to the filter, 
 * and accepts all nodes shown.
 * </p>
 * 
 * @param domImplLS the DOM Level 3 Load/Save implementation to use
 * @param serializerParams parameters to pass to the {@link DOMConfiguration} of the serializer
 *         instance, obtained via {@link LSSerializer#getDomConfig()}. May be null.
 *         
 * @return a new LSSerializer instance
 */
public static LSSerializer getLSSerializer(DOMImplementationLS domImplLS, Map<String, Object> serializerParams) {
    LSSerializer serializer = domImplLS.createLSSerializer();
    
    serializer.setFilter(new LSSerializerFilter() {

        public short acceptNode(Node arg0) {
            return FILTER_ACCEPT;
        }

        public int getWhatToShow() {
            return SHOW_ALL;
        }
    });
    
    
    if (serializerParams != null) {
        DOMConfiguration serializerDOMConfig = serializer.getDomConfig();
        for (String key : serializerParams.keySet()) {
            serializerDOMConfig.setParameter(key, serializerParams.get(key));
        }
    }
    
    return serializer;
}
 
Example 2
Source File: DomHelper.java    From mdw with Apache License 2.0 6 votes vote down vote up
public static String toXml(Document domDoc) throws TransformerException {
    DOMImplementation domImplementation = domDoc.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("xml-declaration", Boolean.TRUE))
            lsSerializer.getDomConfig().setParameter("xml-declaration", Boolean.FALSE);
        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(domDoc, lsOutput);
            return stringWriter.toString();
        }
    }
    return toXml((Node) domDoc);
}
 
Example 3
Source File: Formatter.java    From simplexml with Apache License 2.0 6 votes vote down vote up
private void format(Document document, Writer writer) {
   DOMImplementation implementation = document.getImplementation();

   if(implementation.hasFeature(LS_FEATURE_KEY, LS_FEATURE_VERSION) && implementation.hasFeature(CORE_FEATURE_KEY, CORE_FEATURE_VERSION)) {
      DOMImplementationLS implementationLS = (DOMImplementationLS) implementation.getFeature(LS_FEATURE_KEY, LS_FEATURE_VERSION);
      LSSerializer serializer = implementationLS.createLSSerializer();
      DOMConfiguration configuration = serializer.getDomConfig();
      
      configuration.setParameter("format-pretty-print", Boolean.TRUE);
      configuration.setParameter("comments", preserveComments);
      
      LSOutput output = implementationLS.createLSOutput();
      output.setEncoding("UTF-8");
      output.setCharacterStream(writer);
      serializer.write(document, output);
   }
}
 
Example 4
Source File: XMLHelper.java    From saml-client with MIT License 5 votes vote down vote up
/**
 * Obtain a the DOM, level 3, Load/Save serializer {@link LSSerializer} instance from the
 * given {@link DOMImplementationLS} instance.
 *
 * <p>
 * The serializer instance will be configured with the parameters passed as the <code>serializerParams</code>
 * argument. It will also be configured with an {@link LSSerializerFilter} that shows all nodes to the filter,
 * and accepts all nodes shown.
 * </p>
 *
 * @param domImplLS the DOM Level 3 Load/Save implementation to use
 * @param serializerParams parameters to pass to the {@link DOMConfiguration} of the serializer
 *         instance, obtained via {@link LSSerializer#getDomConfig()}. May be null.
 *
 * @return a new LSSerializer instance
 */
public static LSSerializer getLSSerializer(
    DOMImplementationLS domImplLS, Map<String, Object> serializerParams) {
  LSSerializer serializer = domImplLS.createLSSerializer();

  serializer.setFilter(
      new LSSerializerFilter() {

        @Override
        public short acceptNode(Node arg0) {
          return FILTER_ACCEPT;
        }

        @Override
        public int getWhatToShow() {
          return SHOW_ALL;
        }
      });

  if (serializerParams != null) {
    DOMConfiguration serializerDOMConfig = serializer.getDomConfig();
    for (String key : serializerParams.keySet()) {
      serializerDOMConfig.setParameter(key, serializerParams.get(key));
    }
  }

  return serializer;
}
 
Example 5
Source File: XmlUtils.java    From mrgeo with Apache License 2.0 5 votes vote down vote up
public static void writeDocument(Document doc, Writer out) throws IOException
{
  // happy to replace this code w/ the non-deprecated code, but I couldn't get the transformer
  // approach to work.
//    OutputFormat format = new OutputFormat(doc);
//    format.setIndenting(true);
//    format.setIndent(2);
//    XMLSerializer serializer = new XMLSerializer(out, format);
//    serializer.serialize(doc);

  DOMImplementationLS impl = (DOMImplementationLS) doc.getImplementation();
  LSSerializer writer = impl.createLSSerializer();
  DOMConfiguration config = writer.getDomConfig();

  if (config.canSetParameter("format-pretty-print", Boolean.TRUE))
  {
    config.setParameter("format-pretty-print", Boolean.TRUE);
  }


  // what a crappy way to force the stream to be UTF-8.  yuck!
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  LSOutput output = impl.createLSOutput();
  output.setEncoding("UTF-8");
  output.setByteStream(baos);

  writer.write(doc, output);

  out.write(baos.toString());
  out.flush();
}
 
Example 6
Source File: PrettyPrintTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@Test
public void testLSSerializerFormatPrettyPrint() {

    final String XML_DOCUMENT = "<?xml version=\"1.0\" encoding=\"UTF-16\"?>\n"
            + "<hello>before child element<child><children/><children/></child>after child element</hello>";
    /**JDK-8035467
     * no newline in default output
     */
    final String XML_DOCUMENT_DEFAULT_PRINT =
            "<?xml version=\"1.0\" encoding=\"UTF-16\"?>"
            + "<hello>"
            + "before child element"
            + "<child><children/><children/></child>"
            + "after child element</hello>";

    final String XML_DOCUMENT_PRETTY_PRINT = "<?xml version=\"1.0\" encoding=\"UTF-16\"?><hello>\n" +
            "    before child element\n" +
            "    <child>\n" +
            "        <children/>\n" +
            "        <children/>\n" +
            "    </child>\n" +
            "    after child element\n" +
            "</hello>\n";

    // it all begins with a Document
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = null;
    try {
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
    } catch (ParserConfigurationException parserConfigurationException) {
        parserConfigurationException.printStackTrace();
        Assert.fail(parserConfigurationException.toString());
    }
    Document document = null;

    StringReader stringReader = new StringReader(XML_DOCUMENT);
    InputSource inputSource = new InputSource(stringReader);
    try {
        document = documentBuilder.parse(inputSource);
    } catch (SAXException saxException) {
        saxException.printStackTrace();
        Assert.fail(saxException.toString());
    } catch (IOException ioException) {
        ioException.printStackTrace();
        Assert.fail(ioException.toString());
    }

    // query DOM Interfaces to get to a LSSerializer
    DOMImplementation domImplementation = documentBuilder.getDOMImplementation();
    DOMImplementationLS domImplementationLS = (DOMImplementationLS) domImplementation;
    LSSerializer lsSerializer = domImplementationLS.createLSSerializer();

    System.out.println("Serializer is: " + lsSerializer.getClass().getName() + " " + lsSerializer);

    // get configuration
    DOMConfiguration domConfiguration = lsSerializer.getDomConfig();

    // query current configuration
    Boolean defaultFormatPrettyPrint = (Boolean) domConfiguration.getParameter(DOM_FORMAT_PRETTY_PRINT);
    Boolean canSetFormatPrettyPrintFalse = (Boolean) domConfiguration.canSetParameter(DOM_FORMAT_PRETTY_PRINT, Boolean.FALSE);
    Boolean canSetFormatPrettyPrintTrue = (Boolean) domConfiguration.canSetParameter(DOM_FORMAT_PRETTY_PRINT, Boolean.TRUE);

    System.out.println(DOM_FORMAT_PRETTY_PRINT + " default/can set false/can set true = " + defaultFormatPrettyPrint + "/"
            + canSetFormatPrettyPrintFalse + "/" + canSetFormatPrettyPrintTrue);

    // test values
    assertEquals(defaultFormatPrettyPrint, Boolean.FALSE, "Default value of " + DOM_FORMAT_PRETTY_PRINT + " should be " + Boolean.FALSE);

    assertEquals(canSetFormatPrettyPrintFalse, Boolean.TRUE, "Can set " + DOM_FORMAT_PRETTY_PRINT + " to " + Boolean.FALSE + " should be "
            + Boolean.TRUE);

    assertEquals(canSetFormatPrettyPrintTrue, Boolean.TRUE, "Can set " + DOM_FORMAT_PRETTY_PRINT + " to " + Boolean.TRUE + " should be "
            + Boolean.TRUE);

    // get default serialization
    String prettyPrintDefault = lsSerializer.writeToString(document);
    System.out.println("(default) " + DOM_FORMAT_PRETTY_PRINT + "==" + (Boolean) domConfiguration.getParameter(DOM_FORMAT_PRETTY_PRINT)
            + ": \n\"" + prettyPrintDefault + "\"");

    assertEquals(prettyPrintDefault, XML_DOCUMENT_DEFAULT_PRINT, "Invalid serialization with default value, " + DOM_FORMAT_PRETTY_PRINT + "=="
            + (Boolean) domConfiguration.getParameter(DOM_FORMAT_PRETTY_PRINT));

    // configure LSSerializer to not format-pretty-print
    domConfiguration.setParameter(DOM_FORMAT_PRETTY_PRINT, Boolean.FALSE);
    String prettyPrintFalse = lsSerializer.writeToString(document);
    System.out.println("(FALSE) " + DOM_FORMAT_PRETTY_PRINT + "==" + (Boolean) domConfiguration.getParameter(DOM_FORMAT_PRETTY_PRINT)
            + ": \n\"" + prettyPrintFalse + "\"");

    assertEquals(prettyPrintFalse, XML_DOCUMENT_DEFAULT_PRINT, "Invalid serialization with FALSE value, " + DOM_FORMAT_PRETTY_PRINT + "=="
            + (Boolean) domConfiguration.getParameter(DOM_FORMAT_PRETTY_PRINT));

    // configure LSSerializer to format-pretty-print
    domConfiguration.setParameter(DOM_FORMAT_PRETTY_PRINT, Boolean.TRUE);
    String prettyPrintTrue = lsSerializer.writeToString(document);
    System.out.println("(TRUE) " + DOM_FORMAT_PRETTY_PRINT + "==" + (Boolean) domConfiguration.getParameter(DOM_FORMAT_PRETTY_PRINT)
            + ": \n\"" + prettyPrintTrue + "\"");

    assertEquals(prettyPrintTrue, XML_DOCUMENT_PRETTY_PRINT, "Invalid serialization with TRUE value, " + DOM_FORMAT_PRETTY_PRINT + "=="
            + (Boolean) domConfiguration.getParameter(DOM_FORMAT_PRETTY_PRINT));
}
 
Example 7
Source File: DOML3InputSourceFactoryImpl.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public InputSource newInputSource(String filename) throws Exception {
    // Create DOMImplementationLS, and DOM L3 LSParser
    DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
    DocumentBuilder bldr = fact.newDocumentBuilder();
    DOMImplementationLS impl = (DOMImplementationLS) bldr.getDOMImplementation();
    LSParser domparser = impl.createLSParser(MODE_SYNCHRONOUS, null);
    domparser.setFilter(new MyDOMBuilderFilter());

    // Parse the xml document to create the DOM Document using
    // the DOM L3 LSParser and a LSInput (formerly LSInputSource)
    Document doc = null;
    LSInput src = impl.createLSInput();
    // register the input file with the input source...
    String systemId = filenameToURL(filename);
    src.setSystemId(systemId);
    try (Reader reader = new FileReader(filename)) {
        src.setCharacterStream(reader);
        src.setEncoding("UTF-8");
        doc = domparser.parse(src);
    }

    // Use DOM L3 LSSerializer (previously called a DOMWriter)
    // to serialize the xml doc DOM to a file stream.
    String tmpCatalog = Files.createTempFile(Paths.get(USER_DIR), "catalog.xml", null).toString();

    LSSerializer domserializer = impl.createLSSerializer();
    domserializer.setFilter(new MyDOMWriterFilter());
    domserializer.getNewLine();
    DOMConfiguration config = domserializer.getDomConfig();
    config.setParameter("xml-declaration", Boolean.TRUE);
    String result = domserializer.writeToString(doc);
    try (FileWriter os = new FileWriter(tmpCatalog, false)) {
        os.write(result);
        os.flush();
    }

    // Return the Input Source created from the Serialized DOM L3 Document.
    InputSource catsrc = new InputSource(new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(tmpCatalog)))));
    catsrc.setSystemId(systemId);
    return catsrc;
}
 
Example 8
Source File: UtilXml.java    From scipio-erp with Apache License 2.0 3 votes vote down vote up
/** Returns a <code>LSSerializer</code> instance.
 * @param impl A <code>DOMImplementationLS</code> instance
 * @param includeXmlDeclaration If set to <code>true</code>,
 * the xml declaration will be included in the output
 * @param enablePrettyPrint If set to <code>true</code>, the
 * output will be formatted in human-readable form. If set to
 * <code>false</code>, the entire document will consist of a single line.
 * @return A <code>LSSerializer</code> instance
 * @see <a href="http://www.w3.org/TR/2004/REC-DOM-Level-3-LS-20040407/">DOM Level 3 Load and Save Specification</a>
 */
public static LSSerializer createLSSerializer(DOMImplementationLS impl, boolean includeXmlDeclaration, boolean enablePrettyPrint) {
    LSSerializer writer = impl.createLSSerializer();
    DOMConfiguration domConfig = writer.getDomConfig();
    domConfig.setParameter("xml-declaration", includeXmlDeclaration);
    domConfig.setParameter("format-pretty-print", enablePrettyPrint);
    return writer;
}