Java Code Examples for org.w3c.dom.ls.DOMImplementationLS#createLSSerializer()

The following examples show how to use org.w3c.dom.ls.DOMImplementationLS#createLSSerializer() . 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: ModelTestUtils.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Normalize and pretty-print XML so that it can be compared using string
 * compare. The following code does the following: - Removes comments -
 * Makes sure attributes are ordered consistently - Trims every element -
 * Pretty print the document
 *
 * @param xml The XML to be normalized
 * @return The equivalent XML, but now normalized
 */
public static String normalizeXML(String xml) throws Exception {
    // Remove all white space adjoining tags ("trim all elements")
    xml = xml.replaceAll("\\s*<", "<");
    xml = xml.replaceAll(">\\s*", ">");

    DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
    DOMImplementationLS domLS = (DOMImplementationLS) registry.getDOMImplementation("LS");
    LSParser lsParser = domLS.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null);

    LSInput input = domLS.createLSInput();
    input.setStringData(xml);
    Document document = lsParser.parse(input);

    LSSerializer lsSerializer = domLS.createLSSerializer();
    lsSerializer.getDomConfig().setParameter("comments", Boolean.FALSE);
    lsSerializer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);
    return lsSerializer.writeToString(document);
}
 
Example 2
Source File: Util.java    From carbon-commons with Apache License 2.0 6 votes vote down vote up
/**
 * Serializing a SAML2 object into a String
 *
 * @param xmlObject object that needs to serialized.
 * @return serialized object
 * @throws Exception
 */
public static String marshall(XMLObject xmlObject) throws Exception {
    try {
        doBootstrap();
        System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
                           "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");

        MarshallerFactory marshallerFactory = org.opensaml.xml.Configuration.getMarshallerFactory();
        Marshaller marshaller = marshallerFactory.getMarshaller(xmlObject);
        Element element = marshaller.marshall(xmlObject);

        ByteArrayOutputStream byteArrayOutputStrm = new ByteArrayOutputStream();
        DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
        DOMImplementationLS impl =
                (DOMImplementationLS) registry.getDOMImplementation("LS");
        LSSerializer writer = impl.createLSSerializer();
        LSOutput output = impl.createLSOutput();
        output.setByteStream(byteArrayOutputStrm);
        writer.write(element, output);
        return byteArrayOutputStrm.toString();
    } catch (Exception e) {
        throw new Exception("Error Serializing the SAML Response", e);
    }
}
 
Example 3
Source File: WSXACMLEntitlementServiceClient.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
/**
 * Serialize XML objects
 *
 * @param xmlObject : XACML or SAML objects to be serialized
 * @return serialized XACML or SAML objects
 */
private String marshall(XMLObject xmlObject) throws EntitlementProxyException {

    try {
        doBootstrap();
        System.setProperty(DOCUMENT_BUILDER_FACTORY, DOCUMENT_BUILDER_FACTORY_IMPL);

        MarshallerFactory marshallerFactory = org.opensaml.xml.Configuration.getMarshallerFactory();
        Marshaller marshaller = marshallerFactory.getMarshaller(xmlObject);
        Element element = marshaller.marshall(xmlObject);

        ByteArrayOutputStream byteArrayOutputStrm = new ByteArrayOutputStream();
        DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
        DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
        LSSerializer writer = impl.createLSSerializer();
        LSOutput output = impl.createLSOutput();
        output.setByteStream(byteArrayOutputStrm);
        writer.write(element, output);
        return new String(byteArrayOutputStrm.toByteArray(), Charset.forName("UTF-8"));
    } catch (Exception e) {
        log.error("Error Serializing the SAML Response");
        throw new EntitlementProxyException("Error Serializing the SAML Response", e);
    }
}
 
Example 4
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 5
Source File: ErrorResponseBuilder.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
private static String marshall(XMLObject xmlObject) throws org.wso2.carbon.identity.base.IdentityException {
    try {
        System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
                "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");

        MarshallerFactory marshallerFactory = org.opensaml.xml.Configuration.getMarshallerFactory();
        Marshaller marshaller = marshallerFactory.getMarshaller(xmlObject);
        Element element = marshaller.marshall(xmlObject);

        ByteArrayOutputStream byteArrayOutputStrm = new ByteArrayOutputStream();
        DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
        DOMImplementationLS impl =
                (DOMImplementationLS) registry.getDOMImplementation("LS");
        LSSerializer writer = impl.createLSSerializer();
        LSOutput output = impl.createLSOutput();
        output.setByteStream(byteArrayOutputStrm);
        writer.write(element, output);
        return byteArrayOutputStrm.toString("UTF-8");
    } catch (Exception e) {
        log.error("Error Serializing the SAML Response");
        throw IdentityException.error("Error Serializing the SAML Response", e);
    }
}
 
Example 6
Source File: SVGDocument.java    From latexdraw with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Serialise the given SVG document.
 * @param path The file of the future serialised document.
 * @return True: the document has been successfully saved.
 */
public boolean saveSVGDocument(final String path) {
	if(path == null) {
		return false;
	}

	boolean ok = true;
	try {
		final DOMImplementationLS impl = (DOMImplementationLS) DOMImplementationRegistry.newInstance().getDOMImplementation("XML 3.0 LS 3.0"); //NON-NLS
		final LSSerializer serializer = impl.createLSSerializer();
		serializer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE); //NON-NLS
		serializer.getDomConfig().setParameter("namespaces", Boolean.FALSE); //NON-NLS
		final LSOutput output = impl.createLSOutput();
		final Charset charset = Charset.defaultCharset();
		try(final OutputStreamWriter fw = new OutputStreamWriter(Files.newOutputStream(Path.of(path)), charset.newEncoder())) {
			output.setEncoding(charset.name());
			output.setCharacterStream(fw);
			serializer.write(getDocumentElement(), output);
		}
	}catch(final ClassNotFoundException | InstantiationException | IllegalAccessException | ClassCastException | IOException ex) {
		BadaboomCollector.INSTANCE.add(ex);
		ok = false;
	}
	return ok;
}
 
Example 7
Source File: Helper.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
/***
 * Helper method which converts XML Document into pretty formatted string
 *
 * @param doc to convert
 * @return converted XML as String
 */
public static String documentToString(Document doc) {

    String strMsg = "";
    try {
        DOMImplementation domImpl = doc.getImplementation();
        DOMImplementationLS domImplLS = (DOMImplementationLS) domImpl.getFeature("LS", "3.0");
        LSSerializer lsSerializer = domImplLS.createLSSerializer();
        lsSerializer.getDomConfig().setParameter("format-pretty-print", true);

        Writer stringWriter = new StringWriter();
        LSOutput lsOutput = domImplLS.createLSOutput();
        lsOutput.setEncoding("UTF-8");
        lsOutput.setCharacterStream(stringWriter);
        lsSerializer.write(doc, lsOutput);
        strMsg = stringWriter.toString();
    } catch (Exception e) {
        logger.warn("Error occurred when converting document to string", e);
    }
    return strMsg;
}
 
Example 8
Source File: XMLUtil.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
public static String elementToString(Element el) {
  if (el == null)
    return "";
  Document document = el.getOwnerDocument();
  DOMImplementationLS domImplLS = (DOMImplementationLS) document
      .getImplementation();
  LSSerializer serializer = domImplLS.createLSSerializer();
  return serializer.writeToString(el);
}
 
Example 9
Source File: WSXACMLEntitlementServiceClient.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Serialize XML objects
 *
 * @param xmlObject : XACML or SAML objects to be serialized
 * @return serialized XACML or SAML objects
 */
private String marshall(XMLObject xmlObject) throws EntitlementProxyException {

    try {
        doBootstrap();
        System.setProperty(
                DOCUMENT_BUILDER_FACTORY,
                DOCUMENT_BUILDER_FACTORY_IMPL);

        MarshallerFactory marshallerFactory = org.opensaml.xml.Configuration.getMarshallerFactory();
        Marshaller marshaller = marshallerFactory.getMarshaller(xmlObject);
        Element element = marshaller.marshall(xmlObject);

        ByteArrayOutputStream byteArrayOutputStrm = new ByteArrayOutputStream();
        DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
        DOMImplementationLS impl =
                (DOMImplementationLS) registry.getDOMImplementation("LS");
        LSSerializer writer = impl.createLSSerializer();
        LSOutput output = impl.createLSOutput();
        output.setByteStream(byteArrayOutputStrm);
        writer.write(element, output);
        return new String(byteArrayOutputStrm.toByteArray(), Charset.forName("UTF-8"));
    } catch (Exception e) {
        log.error("Error Serializing the SAML Response");
        throw new EntitlementProxyException("Error Serializing the SAML Response", e);
    }
}
 
Example 10
Source File: XmlFormatter.java    From tomee with Apache License 2.0 5 votes vote down vote up
public static String format(final String in) {
    try {
        final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        final DocumentBuilder db = dbf.newDocumentBuilder();
        final InputSource is = new InputSource(new StringReader(in));
        final Document document = db.parse(is);

        final DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
        final DOMImplementationLS impl = DOMImplementationLS.class.cast(registry.getDOMImplementation("XML 3.0 LS 3.0"));
        if (impl == null) {
            return in;
        }

        final LSSerializer serializer = impl.createLSSerializer();
        if (serializer.getDomConfig().canSetParameter("format-pretty-print", Boolean.TRUE)) {
            serializer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);
            final LSOutput lsOutput = impl.createLSOutput();
            lsOutput.setEncoding("UTF-8");
            final StringWriter stringWriter = new StringWriter();
            lsOutput.setCharacterStream(stringWriter);
            serializer.write(document, lsOutput);
            return stringWriter.toString().replace("\"UTF-8\"?><", "\"UTF-8\"?>\n<");
        }

        return in;
    } catch (final Throwable t) {
        return in; // just to be more sexy so ignore it and use ugly xml
    }
}
 
Example 11
Source File: UserController.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Checking when creating an XML document using DOM Level 2 validating
 * it without having a schema source or a schema location It must throw a
 * sax parse exception.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testCreateNewUser() throws Exception {
    String resultFile = USER_DIR + "accountInfoOut.xml";
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setValidating(true);

    DocumentBuilder docBuilder = dbf.newDocumentBuilder();
    MyErrorHandler eh = new MyErrorHandler();
    docBuilder.setErrorHandler(eh);

    Document document = docBuilder.newDocument();

    Element account = document.createElementNS(PORTAL_ACCOUNT_NS, "acc:Account");
    Attr accountID = document.createAttributeNS(PORTAL_ACCOUNT_NS, "acc:accountID");
    account.setAttributeNode(accountID);

    account.appendChild(document.createElement("FirstName"));
    account.appendChild(document.createElementNS(PORTAL_ACCOUNT_NS, "acc:LastName"));
    account.appendChild(document.createElement("UserID"));

    DOMImplementationLS impl
            = (DOMImplementationLS) DOMImplementationRegistry
                    .newInstance().getDOMImplementation("LS");
    LSSerializer writer = impl.createLSSerializer();
    LSParser builder = impl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null);
    try(FileOutputStream output = new FileOutputStream(resultFile)) {
        MyDOMOutput domOutput = new MyDOMOutput();
        domOutput.setByteStream(output);
        writer.write(account, domOutput);
        docBuilder.parse(resultFile);
    }
    assertTrue(eh.isAnyError());
}
 
Example 12
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 13
Source File: Xml.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * Write a DOM Document to an output stream.
 * 
 * @param doc
 *        The DOM Document to write.
 * @param out
 *        The output stream.
 */
public static String writeDocumentToString(Document doc)
{
	try
	{
		
		StringWriter sw = new StringWriter();
		
		 DocumentBuilderFactory factory 
		   = DocumentBuilderFactory.newInstance();
		  DocumentBuilder builder = factory.newDocumentBuilder();
		  DOMImplementation impl = builder.getDOMImplementation();
		  
		
		DOMImplementationLS feature = (DOMImplementationLS) impl.getFeature("LS",
		"3.0");
		LSSerializer serializer = feature.createLSSerializer();
		LSOutput output = feature.createLSOutput();
		output.setCharacterStream(sw);
		output.setEncoding("UTF-8");
		serializer.write(doc, output);
		
		sw.flush();
		return sw.toString();
	}
	catch (Exception any)
	{
		log.warn("writeDocumentToString: " + any.toString());
		return null;
	}
}
 
Example 14
Source File: ExistRunnerApp.java    From intellij-xquery with Apache License 2.0 5 votes vote down vote up
private String prettyPrint(Element node) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
    DOMImplementationRegistry domImplementationRegistry = DOMImplementationRegistry.newInstance();
    DOMImplementationLS domImplementationLS = (DOMImplementationLS) domImplementationRegistry.getDOMImplementation("LS");
    LSOutput lsOutput = domImplementationLS.createLSOutput();
    LSSerializer lsSerializer = domImplementationLS.createLSSerializer();
    lsOutput.setEncoding("UTF-8");
    Writer stringWriter = new StringWriter();
    lsOutput.setCharacterStream(stringWriter);
    lsSerializer.write(node, lsOutput);
    String result = stringWriter.toString();
    return result;
}
 
Example 15
Source File: MappingApiToModel.java    From juddi with Apache License 2.0 5 votes vote down vote up
private static String serializeTransformElement(Element xformEl) throws DOMException, LSException {
                Document document = xformEl.getOwnerDocument();
                DOMImplementationLS domImplLS = (DOMImplementationLS) document.getImplementation();
                LSSerializer serializer = domImplLS.createLSSerializer();
//        serializer.getDomConfig().setParameter("namespaces", true);
//        serializer.getDomConfig().setParameter("namespace-declarations", true);
                serializer.getDomConfig().setParameter("canonical-form", false);
                serializer.getDomConfig().setParameter("xml-declaration", false);
                String str = serializer.writeToString(xformEl);
                return str;
        }
 
Example 16
Source File: UserController.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * This will check if adoptNode works will adoptNode from
 * @see <a href="content/userInfo.xml">userInfo.xml</a>
 * @see <a href="content/accountInfo.xml">accountInfo.xml</a>. This is
 * adopting a node from the XML file which is validated by a DTD and
 * into an XML file which is validated by the schema This covers Row 5
 * for the table
 * http://javaweb.sfbay/~jsuttor/JSR206/jsr-206-html/ch03s05.html. Filed
 * bug 4893745 because there was a difference in behavior.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testCreateUserAccount() throws Exception {
    String userXmlFile = XML_DIR + "userInfo.xml";
    String accountXmlFile = XML_DIR + "accountInfo.xml";
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setValidating(true);

    DocumentBuilder docBuilder = dbf.newDocumentBuilder();
    MyErrorHandler eh = new MyErrorHandler();
    docBuilder.setErrorHandler(eh);

    Document document = docBuilder.parse(userXmlFile);
    Element user = (Element) document.getElementsByTagName("FirstName").item(0);
    // Set schema after parsing userInfo.xml. Otherwise it will conflict
    // with DTD validation.
    dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI);
    DocumentBuilder docBuilder1 = dbf.newDocumentBuilder();
    docBuilder1.setErrorHandler(eh);
    Document accDocument = docBuilder1.parse(accountXmlFile);

    Element firstName = (Element) accDocument
            .getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "FirstName").item(0);
    Element adoptedAccount = (Element) accDocument.adoptNode(user);

    Element parent = (Element) firstName.getParentNode();
    parent.replaceChild(adoptedAccount, firstName);

    DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
    DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
    LSSerializer writer = impl.createLSSerializer();

    MyDOMOutput mydomoutput = new MyDOMOutput();
    mydomoutput.setByteStream(System.out);

    writer.write(document, mydomoutput);
    writer.write(accDocument, mydomoutput);

    assertFalse(eh.isAnyError());
}
 
Example 17
Source File: MainUIModel.java    From Motion_Profile_Generator with MIT License 4 votes vote down vote up
/**
 * Saves the working project.
 */
public void saveWorkingProject() throws ParserConfigurationException
{
    if( workingProject != null )
    {
        // Create document
        DocumentBuilder db = dbFactory.newDocumentBuilder();
        Document dom = db.newDocument();

        // XML entry for the path waypoints and vars
        Element pathElement = dom.createElement("Path" );

        // Save generator type
        pathElement.setAttribute( "GeneratorType", settings.getGeneratorType().name() );

        // Save shared vars
        settings.getSharedGeneratorVars().writeXMLAttributes( pathElement );

        // Write generator vars to xml file
        settings.getGeneratorVars().writeXMLAttributes( pathElement );
        dom.appendChild( pathElement );

        // Write waypoints to xml file
        for( Waypoint wp : waypointList )
        {
            Element waypointEle = dom.createElement("Waypoint" );
            Element xEle = dom.createElement("X" );
            Element yEle = dom.createElement("Y" );
            Element angleEle = dom.createElement("Angle" );
            Text xText = dom.createTextNode("" + wp.getX() );
            Text yText = dom.createTextNode("" + wp.getY() );
            Text angleText = dom.createTextNode("" + wp.getAngle() );

            xEle.appendChild( xText );
            yEle.appendChild( yText );
            angleEle.appendChild( angleText );

            waypointEle.appendChild( xEle );
            waypointEle.appendChild( yEle );
            waypointEle.appendChild( angleEle );

            pathElement.appendChild( waypointEle );
        }

        FileOutputStream fos;
        try
        {
            fos = new FileOutputStream( workingProject );
            DOMImplementationRegistry reg = DOMImplementationRegistry.newInstance();
            DOMImplementationLS impl = (DOMImplementationLS) reg.getDOMImplementation("LS" );
            LSSerializer serializer = impl.createLSSerializer();
            
            serializer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE );
            
            LSOutput lso = impl.createLSOutput();
            lso.setByteStream( fos );
            serializer.write( dom, lso );
           
        }
        catch( Exception e )
        {
            throw new RuntimeException( e );
        }
    }
}
 
Example 18
Source File: LSSerializerTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@Test
public void testXML11() {

    /**
     * XML 1.1 document to parse.
     */
    final String XML11_DOCUMENT = "<?xml version=\"1.1\" encoding=\"UTF-16\"?>\n" + "<hello>" + "world" + "<child><children/><children/></child>"
            + "</hello>";

    /**JDK-8035467
     * no newline in default output
     */
    final String XML11_DOCUMENT_OUTPUT =
            "<?xml version=\"1.1\" encoding=\"UTF-16\"?>"
            + "<hello>"
            + "world"
            + "<child><children/><children/></child>"
            + "</hello>";

    // 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(XML11_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 default serialization
    String defaultSerialization = lsSerializer.writeToString(document);

    System.out.println("XML 1.1 serialization = \"" + defaultSerialization + "\"");

    // output should == input
    Assert.assertEquals(XML11_DOCUMENT_OUTPUT, defaultSerialization, "Invalid serialization of XML 1.1 document: ");
}
 
Example 19
Source File: CombinedQueryBuilderImpl.java    From java-client-api with Apache License 2.0 4 votes vote down vote up
private CombinedQueryDefinitionImpl parseCombinedQuery(RawCombinedQueryDefinition qdef) {
  DOMHandle handle = new DOMHandle();
  HandleAccessor.receiveContent(handle, HandleAccessor.contentAsString(qdef.getHandle()));
  Document combinedQueryXml = handle.get();
  DOMImplementationLS domImplementation = (DOMImplementationLS) combinedQueryXml.getImplementation();
  LSSerializer lsSerializer = domImplementation.createLSSerializer();
  lsSerializer.getDomConfig().setParameter("xml-declaration", false);

  NodeList nl = combinedQueryXml.getElementsByTagNameNS("http://marklogic.com/appservices/search", "options");
  Node n = nl.item(0);
  String options = null;
  StringHandle optionsHandle = null;
  if (n != null) {
    options = lsSerializer.writeToString(n);
    optionsHandle = new StringHandle(options).withFormat(Format.XML);
  }

  //TODO this could be more than one string...
  nl = combinedQueryXml.getElementsByTagNameNS("http://marklogic.com/appservices/search", "qtext");
  n = nl.item(0);
  String qtext = null;
  if (n != null) {
    qtext = lsSerializer.writeToString(n);
  }

  nl = combinedQueryXml.getElementsByTagNameNS("http://marklogic.com/appservices/search", "sparql");
  n = nl.item(0);
  String sparql = null;
  if (n != null) {
    sparql = lsSerializer.writeToString(n);
  }

  nl = combinedQueryXml.getElementsByTagNameNS("http://marklogic.com/appservices/search", "query");
  n = nl.item(0);
  String query = null;
  if (n != null) {
    query = lsSerializer.writeToString(nl.item(0));
  }
  StringHandle structuredQueryHandle = new StringHandle().with(query).withFormat(Format.XML);
  RawStructuredQueryDefinition structuredQueryDefinition =
    new RawQueryDefinitionImpl.Structured(structuredQueryHandle);
  return new CombinedQueryDefinitionImpl(structuredQueryDefinition,
    optionsHandle, qtext, sparql);
}
 
Example 20
Source File: CoreDocumentImpl.java    From JDKSourceCode1.8 with MIT License 3 votes vote down vote up
/**
 * DOM Level 3 WD - Experimental.
 * Save the document or the given node and all its descendants to a string
 * (i.e. serialize the document or node).
 * <br>The parameters used in the <code>LSSerializer</code> interface are
 * assumed to have their default values when invoking this method.
 * <br> The result of a call to this method is the same the result of a
 * call to <code>LSSerializer.writeToString</code> with the document as
 * the node to write.
 * @param node Specifies what to serialize, if this parameter is
 *   <code>null</code> the whole document is serialized, if it's
 *   non-null the given node is serialized.
 * @return The serialized document or <code>null</code> in case an error
 *   occurred.
 * @exception DOMException
 *   WRONG_DOCUMENT_ERR: Raised if the node passed in as the node
 *   parameter is from an other document.
 */
public String saveXML(Node node)
        throws DOMException {
    if (errorChecking && node != null
            && this != node.getOwnerDocument()) {
        String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "WRONG_DOCUMENT_ERR", null);
        throw new DOMException(DOMException.WRONG_DOCUMENT_ERR, msg);
    }
    DOMImplementationLS domImplLS = (DOMImplementationLS) DOMImplementationImpl.getDOMImplementation();
    LSSerializer xmlWriter = domImplLS.createLSSerializer();
    if (node == null) {
        node = this;
    }
    return xmlWriter.writeToString(node);
}