org.w3c.dom.ls.DOMImplementationLS Java Examples

The following examples show how to use org.w3c.dom.ls.DOMImplementationLS. 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: XmlFormatter.java    From carina with Apache License 2.0 6 votes vote down vote up
public static String prettyPrint(String xml) {
    if (StringUtils.isEmpty(xml))
        return xml;

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

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

        writer.getDomConfig().setParameter("format-pretty-print", true);
        writer.getDomConfig().setParameter("xml-declaration", keepDeclaration);

        return writer.writeToString(document);
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
    }
    return xml; // Return the same string if error take place
}
 
Example #3
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 #4
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 #5
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 #6
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 #7
Source File: XMLUtils.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 #8
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 #9
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 #10
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 #11
Source File: Utils.java    From iaf with Apache License 2.0 6 votes vote down vote up
public static String dom2String2(Document document) {
	DOMImplementationRegistry registry;
	try {
		registry = DOMImplementationRegistry.newInstance();
        DOMImplementationLS domImplLS = (DOMImplementationLS)registry.getDOMImplementation("LS");
      	 
		LSSerializer ser = domImplLS.createLSSerializer();  // Create a serializer for the DOM
        LSOutput out = domImplLS.createLSOutput();
        StringWriter stringOut = new StringWriter();        // Writer will be a String
        out.setCharacterStream(stringOut);
        ser.write(document, out);                           // Serialize the DOM

        System.out.println( "STRXML = " 
                + stringOut.toString() );                   // Spit out the DOM as a String

		return stringOut.toString();
	} catch (Exception e) {
		System.err.println("Cannot create registry: "+e.getMessage());
	}
	return null;
}
 
Example #12
Source File: DeleteSearchTest.java    From java-client-api with Apache License 2.0 6 votes vote down vote up
public static void writeDoc() throws Exception {
  DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  factory.setNamespaceAware(true);
  factory.setValidating(false);

  Document domDocument = factory.newDocumentBuilder().newDocument();
  Element root = domDocument.createElement("root");
  root.setAttribute("xml:lang", "en");
  root.setAttribute("foo", "bar");
  root.appendChild(domDocument.createElement("child"));
  root.appendChild(domDocument.createTextNode("mixed"));
  domDocument.appendChild(root);

  @SuppressWarnings("unused")
  String domString = ((DOMImplementationLS) factory.newDocumentBuilder()
    .getDOMImplementation()).createLSSerializer().writeToString(domDocument);

  XMLDocumentManager docMgr = client.newXMLDocumentManager();
  docMgr.write(docId, new DOMHandle().with(domDocument));
}
 
Example #13
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 #14
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 #15
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 #16
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 #17
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 #18
Source File: XmlUtils.java    From Doradus with Apache License 2.0 6 votes vote down vote up
static public String getInnerXmlText(Node xmlNode)
{
    StringBuilder result = new StringBuilder();

    Document xmlDocument = xmlNode.getOwnerDocument();
    DOMImplementation xmlDocumentImpl = xmlDocument.getImplementation();
    DOMImplementationLS lsImpl = (DOMImplementationLS) xmlDocumentImpl.getFeature("LS", "3.0");
    LSSerializer lsSerializer = lsImpl.createLSSerializer();

    NodeList childNodes = xmlNode.getChildNodes();
    for (int i = 0; i < childNodes.getLength(); i++) {
        String childText = lsSerializer.writeToString(childNodes.item(i));
        int pos = childText.indexOf("?>");
        if (pos > -1) {
            childText = childText.substring(pos + 2);
        }
        result.append(childText);
    }

    return result.toString();
}
 
Example #19
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 #20
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 #21
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 #22
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 #23
Source File: DocumentLSTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testLSInputParsingByteStream() throws Exception {
    DOMImplementationLS impl = (DOMImplementationLS) getDocumentBuilder().getDOMImplementation();
    LSParser domParser = impl.createLSParser(MODE_SYNCHRONOUS, null);
    LSInput src = impl.createLSInput();

    try (InputStream is = new FileInputStream(ASTROCAT)) {
        src.setByteStream(is);
        assertNotNull(src.getByteStream());
        // set certified accessor methods
        boolean origCertified = src.getCertifiedText();
        src.setCertifiedText(true);
        assertTrue(src.getCertifiedText());
        src.setCertifiedText(origCertified); // set back to orig

        src.setSystemId(filenameToURL(ASTROCAT));

        Document doc = domParser.parse(src);
        Element result = doc.getDocumentElement();
        assertEquals(result.getTagName(), "stardb");
    }
}
 
Example #24
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 #25
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 #26
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 #27
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 #28
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 #29
Source File: cfXmlData.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Checks that the underlying XML parser is JAXP 1.3 compliant. Throws a cfmRunTimeException
 * if it is not compliant.
 * 
 * @throws cfmRunTimeException
 */
protected static void checkCompliance() throws cfmRunTimeException {
	// Verify that the XML parser is JAX 1.3 compliant
	try {
		DOMImplementation domImpl = DocumentBuilderFactory.newInstance().newDocumentBuilder().getDOMImplementation();
		if (!DOMImplementationLS.class.isAssignableFrom(domImpl.getClass())) {
			String errMsg = "The configured XML parser does not support JAXP 1.3. Please configure the " + "JVM to use a JAXP 1.3 compliant XML parser. If using Sun Microsystems' JDK 1.5, " + "this can be done by setting the system property javax.xml.parsers.DocumentBuilderFactory " + "to \"com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl\".";
			throw new cfmRunTimeException(catchDataFactory.generalException("errorCode.runtimeError", errMsg));
		}
	} catch (Exception ex) {
		throw new cfmRunTimeException(catchDataFactory.javaMethodException("errorCode.javaException", ex.getClass().getName(), ex.getMessage(), ex));
	}
	complianceChecked = true;
}
 
Example #30
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);
    }
}