org.w3c.dom.ls.LSSerializer Java Examples

The following examples show how to use org.w3c.dom.ls.LSSerializer. 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: Utils.java    From SI with BSD 2-Clause "Simplified" License 8 votes vote down vote up
public static String format(String xml) {

        try {
            final InputSource src = new InputSource(new StringReader(xml));
            final Node document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(src).getDocumentElement();
            final Boolean keepDeclaration = Boolean.valueOf(xml.startsWith("<?xml"));

            //May need this: System.setProperty(DOMImplementationRegistry.PROPERTY,"com.sun.org.apache.xerces.internal.dom.DOMImplementationSourceImpl");


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

            writer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE); // Set this to true if the output needs to be beautified.
            writer.getDomConfig().setParameter("xml-declaration", keepDeclaration); // Set this to true if the declaration is needed to be outputted.

            return writer.writeToString(document);
        } catch (Exception e) {
            return xml;
        }
    }
 
Example #2
Source File: SSOUtils.java    From carbon-identity 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 SAMLSSOException
 */
public static String marshall(XMLObject xmlObject) throws SAMLSSOException {
    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();
    } catch (Exception e) {
        log.error("Error Serializing the SAML Response");
        throw new SAMLSSOException("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: 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 #5
Source File: AbstractMethodErrorTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document document = builder.newDocument();

    DOMImplementation impl = document.getImplementation();
    DOMImplementationLS implLS = (DOMImplementationLS) impl.getFeature("LS", "3.0");
    LSSerializer dsi = implLS.createLSSerializer();

    /* We should have here incorrect document without getXmlVersion() method:
     * Such Document is generated by replacing the JDK bootclasses with it's
     * own Node,Document and DocumentImpl classes (see run.sh). According to
     * XERCESJ-1007 the AbstractMethodError should be thrown in such case.
     */
    String result = dsi.writeToString(document);
    System.out.println("Result:" + result);
}
 
Example #6
Source File: CoverageMonitor.java    From teamengine with Apache License 2.0 6 votes vote down vote up
/**
 * Writes a DOM Document to the given OutputStream using the "UTF-8"
 * encoding. The XML declaration is omitted.
 * 
 * @param outStream
 *            The destination OutputStream object.
 * @param doc
 *            A Document node.
 */
void writeDocument(OutputStream outStream, Document doc) {
    DOMImplementationRegistry domRegistry = null;
    try {
        domRegistry = DOMImplementationRegistry.newInstance();
    // Fortify Mod: Broaden try block to capture all potential exceptions
    // } catch (Exception e) {
    //    LOGR.warning(e.getMessage());
    // }
    DOMImplementationLS impl = (DOMImplementationLS) domRegistry
            .getDOMImplementation("LS");
    LSSerializer writer = impl.createLSSerializer();
    writer.getDomConfig().setParameter("xml-declaration", false);
    writer.getDomConfig().setParameter("format-pretty-print", true);
    LSOutput output = impl.createLSOutput();
    output.setEncoding("UTF-8");
    output.setByteStream(outStream);
    writer.write(doc, output);
    } catch (Exception e) {
        LOGR.warning(e.getMessage());
    }
}
 
Example #7
Source File: Util.java    From carbon-apimgt 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 = XMLObjectProviderRegistrySupport.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 #8
Source File: AuctionController.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Check for DOMErrorHandler handling DOMError. Before fix of bug 4890927
 * DOMConfiguration.setParameter("well-formed",true) throws an exception.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testCreateNewItem2Sell() throws Exception {
    String xmlFile = XML_DIR + "novelsInvalid.xml";

    Document document = DocumentBuilderFactory.newInstance()
            .newDocumentBuilder().parse(xmlFile);

    document.getDomConfig().setParameter("well-formed", true);

    DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
    DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
    MyDOMOutput domOutput = new MyDOMOutput();
    domOutput.setByteStream(System.out);
    LSSerializer writer = impl.createLSSerializer();
    writer.write(document, domOutput);
}
 
Example #9
Source File: AuctionController.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Check for DOMErrorHandler handling DOMError. Before fix of bug 4896132
 * test throws DOM Level 1 node error.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testCreateNewItem2SellRetry() throws Exception  {
    String xmlFile = XML_DIR + "accountInfo.xml";

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    Document document = dbf.newDocumentBuilder().parse(xmlFile);

    DOMConfiguration domConfig = document.getDomConfig();
    MyDOMErrorHandler errHandler = new MyDOMErrorHandler();
    domConfig.setParameter("error-handler", errHandler);

    DOMImplementationLS impl =
         (DOMImplementationLS) DOMImplementationRegistry.newInstance()
                 .getDOMImplementation("LS");
    LSSerializer writer = impl.createLSSerializer();
    MyDOMOutput domoutput = new MyDOMOutput();

    domoutput.setByteStream(System.out);
    writer.write(document, domoutput);

    document.normalizeDocument();
    writer.write(document, domoutput);
    assertFalse(errHandler.isError());
}
 
Example #10
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 #11
Source File: Util.java    From carbon-identity 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 SAML2SSOUIAuthenticatorException
 */
public static String marshall(XMLObject xmlObject) throws SAML2SSOUIAuthenticatorException {

    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) {
        log.error("Error Serializing the SAML Response");
        throw new SAML2SSOUIAuthenticatorException("Error Serializing the SAML Response", e);
    }
}
 
Example #12
Source File: ConfigPersister.java    From PyramidShader with GNU General Public License v3.0 6 votes vote down vote up
public void load(File f) throws ConfigPersisterException {
    try {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document doc = builder.parse(f);

		DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation();
	    LSSerializer lsSerializer = domImplementation.createLSSerializer();
	    String configString = lsSerializer.writeToString(doc);

    	_config = (Config) _xstream.fromXML(convertToCurrent(configString));
    	setConfigPath(f);
	} catch (Exception e) {
		throw new ConfigPersisterException(e);
	}
}
 
Example #13
Source File: ConfigurationController.java    From c2mon with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Saves the process configuration.
 */
private void saveConfiguration(Document docXMLConfig) {
  String fileToSaveConf = properties.getSaveRemoteConfig();
  if (fileToSaveConf.length() > 0 && docXMLConfig != null) {
    log.info("saveConfiguration - saving the process configuration XML in a file " + fileToSaveConf + " due to user request");

    File file = new File(fileToSaveConf);
    if (file.isDirectory() || !fileToSaveConf.endsWith(".xml")) {
      throw new RuntimeException("Path to which to save remote config must end with '.xml'");
    }

    try {
      DOMImplementationLS domImplementation = (DOMImplementationLS) docXMLConfig.getImplementation();
      LSSerializer lsSerializer = domImplementation.createLSSerializer();
      lsSerializer.writeToURI(docXMLConfig, file.toURI().toURL().toString());
    } catch (java.io.IOException ex) {
      log.error("saveConfiguration - Could not save the configuration to the file " + fileToSaveConf, ex);
    }
  }
}
 
Example #14
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 #15
Source File: ConfigPersister.java    From beast-mcmc with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void load(File f) throws ConfigPersisterException {
    try {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document doc = builder.parse(f);

		DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation();
	    LSSerializer lsSerializer = domImplementation.createLSSerializer();
	    String configString = lsSerializer.writeToString(doc);

    	_config = (Config) _xstream.fromXML(convertToCurrent(configString));
    	setConfigPath(f);
	} catch (Exception e) {
		throw new ConfigPersisterException(e);
	}
}
 
Example #16
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 #17
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 #18
Source File: Utils.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public static String format(String xml) {

        try {
            final InputSource src = new InputSource(new StringReader(xml));
            final Node document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(src).getDocumentElement();
            final Boolean keepDeclaration = Boolean.valueOf(xml.startsWith("<?xml"));

            //May need this: System.setProperty(DOMImplementationRegistry.PROPERTY,"com.sun.org.apache.xerces.internal.dom.DOMImplementationSourceImpl");


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

            writer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE); // Set this to true if the output needs to be beautified.
            writer.getDomConfig().setParameter("xml-declaration", keepDeclaration); // Set this to true if the declaration is needed to be outputted.

            return writer.writeToString(document);
        } catch (Exception e) {
            return xml;
        }
    }
 
Example #19
Source File: WSXACMLMessageReceiver.java    From carbon-identity 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
 * @throws EntitlementException
 */
private String marshall(XMLObject xmlObject) throws EntitlementException {

    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 byteArrayOutputStream = new ByteArrayOutputStream();
        DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
        DOMImplementationLS impl =
                (DOMImplementationLS) registry.getDOMImplementation("LS");
        LSSerializer writer = impl.createLSSerializer();
        LSOutput output = impl.createLSOutput();
        output.setByteStream(byteArrayOutputStream);
        writer.write(element, output);
        return byteArrayOutputStream.toString();
    } catch (Exception e) {
        log.error("Error Serializing the SAML Response");
        throw new EntitlementException("Error Serializing the SAML Response", e);
    }
}
 
Example #20
Source File: WSXACMLMessageReceiver.java    From carbon-identity-framework 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
 * @throws EntitlementException
 */
private String marshall(XMLObject xmlObject) throws EntitlementException {

    try {
        doBootstrap();
        System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
                "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");

        MarshallerFactory marshallerFactory = XMLObjectProviderRegistrySupport.getMarshallerFactory();
        Marshaller marshaller = marshallerFactory.getMarshaller(xmlObject);
        Element element = marshaller.marshall(xmlObject);

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
        DOMImplementationLS impl =
                (DOMImplementationLS) registry.getDOMImplementation("LS");
        LSSerializer writer = impl.createLSSerializer();
        LSOutput output = impl.createLSOutput();
        output.setByteStream(byteArrayOutputStream);
        writer.write(element, output);
        return byteArrayOutputStream.toString();
    } catch (Exception e) {
        log.error("Error Serializing the SAML Response");
        throw new EntitlementException("Error Serializing the SAML Response", e);
    }
}
 
Example #21
Source File: DataSourceUtils.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
public static String elementToString(Element element) {
	try {
		if (element == null) {
                               /* return an empty string because, the other way around works the same,
                               where if we give a empty string as the XML, we get a null element
                               from "stringToElement" */
			return "";
		}
           Document document = element.getOwnerDocument();
           DOMImplementationLS domImplLS = (DOMImplementationLS) document.getImplementation();
           LSSerializer serializer = domImplLS.createLSSerializer();
           //by default its true, so set it to false to get String without xml-declaration
           serializer.getDomConfig().setParameter(XML_DECLARATION, false);
           return serializer.writeToString(element);
	} catch (Exception e) {
		log.error("Error while convering element to string: " + e.getMessage(), e);
		return null;
	}
}
 
Example #22
Source File: VsmResponse.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
protected void printResponse() {
    try {
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        DOMImplementationLS ls = (DOMImplementationLS)docBuilder.getDOMImplementation();
        LSSerializer lss = ls.createLSSerializer();
        System.out.println(lss.writeToString(_docResponse));
    } catch (ParserConfigurationException e) {
        s_logger.error("Error parsing the repsonse : " + e.toString());
    }
}
 
Example #23
Source File: Util.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static String format(Element data) {
    LSSerializer ser = ((DOMImplementationLS) data.getOwnerDocument().getImplementation().getFeature("LS", "3.0")).createLSSerializer();
    try {
        ser.getDomConfig().setParameter("format-pretty-print", true);
        ser.getDomConfig().setParameter("xml-declaration", false);
    } catch (DOMException ignore) {}
    return ser.writeToString(data);
}
 
Example #24
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 #25
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 #26
Source File: FreeWorshipParser.java    From Quelea with GNU General Public License v3.0 5 votes vote down vote up
private String innerXml(Node node) {
    DOMImplementationLS lsImpl = (DOMImplementationLS) node.getOwnerDocument().getImplementation().getFeature("LS", "3.0");
    LSSerializer lsSerializer = lsImpl.createLSSerializer();
    NodeList childNodes = node.getChildNodes();
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < childNodes.getLength(); i++) {
        String str = lsSerializer.writeToString(childNodes.item(i));
        if (str.endsWith("<br/>")) {
            str = "\n";
        }
        sb.append(str);
    }
    return sb.toString().replaceAll("<\\?xml.*\\?>", "");
}
 
Example #27
Source File: XMLHelper.java    From saml-client with MIT License 5 votes vote down vote up
/**
 * Writes a Node out to a Writer using the DOM, level 3, Load/Save serializer. The written content is encoded using
 * the encoding specified in the writer configuration.
 *
 * @param node the node to write out
 * @param output the writer to write the XML to
 * @param serializerParams parameters to pass to the {@link DOMConfiguration} of the serializer
 *         instance, obtained via {@link LSSerializer#getDomConfig()}. May be null.
 */
public static void writeNode(Node node, Writer output, Map<String, Object> serializerParams) {
  DOMImplementationLS domImplLS = getLSDOMImpl(node);

  LSSerializer serializer = getLSSerializer(domImplLS, serializerParams);

  LSOutput serializerOut = domImplLS.createLSOutput();
  serializerOut.setCharacterStream(output);

  serializer.write(node, serializerOut);
}
 
Example #28
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 #29
Source File: UserController.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Checking for namespace normalization.
 * @see <a href="content/screenName.xml">screenName.xml</a> has prefix of
 * userName is bound to "http://hibid.com/user" namespace normalization
 * will create a namespace of prefix us and attach userEmail.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testCheckScreenNameExists() throws Exception {
    String resultFile = USER_DIR + "screenName.out";
    String xmlFile = XML_DIR + "screenName.xml";
    String goldFile = GOLDEN_DIR + "screenNameGold.xml";

    String nsTagName = "http://hibid.com/screenName";
    String userNs = "http://hibid.com/user";

    try (FileOutputStream output = new FileOutputStream(resultFile)) {
        DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
        DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
        LSSerializer writer = impl.createLSSerializer();
        LSParser builder = impl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null);
        Document document = builder.parseURI(xmlFile);
        NodeList nl = document.getElementsByTagNameNS(nsTagName, "screen-name");
        assertEquals(nl.getLength(), 1);
        Element screenName = (Element)nl.item(0);
        Element userEmail = document.createElementNS(userNs, "userEmail");
        assertTrue(userEmail.isDefaultNamespace(userNs));

        Text email = document.createTextNode("[email protected]");
        userEmail.appendChild(email);
        screenName.appendChild(userEmail);
        document.normalizeDocument();

        MyDOMOutput domoutput = new MyDOMOutput();
        domoutput.setByteStream(output);
        writer.write(document, domoutput);
    }
    assertTrue(compareDocumentWithGold(goldFile, resultFile));
}
 
Example #30
Source File: CoreUtils.java    From TranskribusCore with GNU General Public License v3.0 5 votes vote down vote up
/**
	 * from: https://stackoverflow.com/questions/139076/how-to-pretty-print-xml-from-java
	 * @param xml The string representation of the unformatted XML
	 * @return The string representation of the formatted XML
	 * @throws ClassCastException 
	 * @throws IllegalAccessException 
	 * @throws InstantiationException 
	 * @throws ClassNotFoundException 
	 * @throws ParserConfigurationException 
	 * @throws IOException 
	 * @throws SAXException 
	 * @deprecated does it work with correct encoding?
	 */
	public static String formatXml(String xml) throws ClassNotFoundException, InstantiationException, IllegalAccessException, ClassCastException, SAXException, IOException, ParserConfigurationException {
//		try {
			final InputSource src = new InputSource(new StringReader(xml));
			final Node document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(src)
					.getDocumentElement();
			final Boolean keepDeclaration = Boolean.valueOf(xml.startsWith("<?xml"));

			// May need this:
			// System.setProperty(DOMImplementationRegistry.PROPERTY,"com.sun.org.apache.xerces.internal.dom.DOMImplementationSourceImpl");

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

			writer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE); // Set this to true if the output
																						// needs to be beautified.
			writer.getDomConfig().setParameter("xml-declaration", keepDeclaration); // Set this to true if the
																					// declaration is needed to be
																					// outputted.
			             
			LSOutput lsOutput = impl.createLSOutput();
			lsOutput.setEncoding("UTF-8");
			             StringWriter stringWriter = new StringWriter();
			             lsOutput.setCharacterStream(stringWriter);
			             writer.write(document, lsOutput);
			             return stringWriter.toString();

//			return writer.writeToString(document);
//		} catch (Exception e) {
//			throw new RuntimeException(e);
//		}
	}