org.w3c.dom.bootstrap.DOMImplementationRegistry Java Examples

The following examples show how to use org.w3c.dom.bootstrap.DOMImplementationRegistry. 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: DoctypeMakerTest.java    From caja with Apache License 2.0 6 votes vote down vote up
private static void assertDoctype(
    String name, String pubid, String systemId, String text)
    throws Exception {
  Function<DOMImplementation, DocumentType> maker = DoctypeMaker.parse(text);
  if (name == null) {
    assertNull(text, maker);
    return;
  } else {
    assertNotNull(text, maker);
    DOMImplementation impl = DOMImplementationRegistry.newInstance()
        .getDOMImplementation("XML 1.0 Traversal");
    DocumentType doctype = maker.apply(impl);
    assertEquals(text, name, doctype.getName());
    assertEquals(text, systemId, doctype.getSystemId());
    assertEquals(text, pubid, doctype.getPublicId());
  }
}
 
Example #3
Source File: MergeStdCommentTest.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 {
    String format = "javax_imageio_1.0";
    BufferedImage img =
        new BufferedImage(16, 16, BufferedImage.TYPE_INT_RGB);
    ImageWriter iw = ImageIO.getImageWritersByMIMEType("image/png").next();
    IIOMetadata meta =
        iw.getDefaultImageMetadata(new ImageTypeSpecifier(img), null);
    DOMImplementationRegistry registry;
    registry = DOMImplementationRegistry.newInstance();
    DOMImplementation impl = registry.getDOMImplementation("XML 3.0");
    Document doc = impl.createDocument(null, format, null);
    Element root, text, entry;
    root = doc.getDocumentElement();
    root.appendChild(text = doc.createElement("Text"));
    text.appendChild(entry = doc.createElement("TextEntry"));
    // keyword isn't #REQUIRED by the standard metadata format.
    // However, it is required by the PNG format, so we include it here.
    entry.setAttribute("keyword", "Comment");
    entry.setAttribute("value", "Some demo comment");
    meta.mergeTree(format, root);
}
 
Example #4
Source File: MergeStdCommentTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    String format = "javax_imageio_1.0";
    BufferedImage img =
        new BufferedImage(16, 16, BufferedImage.TYPE_INT_RGB);
    ImageWriter iw = ImageIO.getImageWritersByMIMEType("image/png").next();
    IIOMetadata meta =
        iw.getDefaultImageMetadata(new ImageTypeSpecifier(img), null);
    DOMImplementationRegistry registry;
    registry = DOMImplementationRegistry.newInstance();
    DOMImplementation impl = registry.getDOMImplementation("XML 3.0");
    Document doc = impl.createDocument(null, format, null);
    Element root, text, entry;
    root = doc.getDocumentElement();
    root.appendChild(text = doc.createElement("Text"));
    text.appendChild(entry = doc.createElement("TextEntry"));
    // keyword isn't #REQUIRED by the standard metadata format.
    // However, it is required by the PNG format, so we include it here.
    entry.setAttribute("keyword", "Comment");
    entry.setAttribute("value", "Some demo comment");
    meta.mergeTree(format, root);
}
 
Example #5
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 #6
Source File: MergeStdCommentTest.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    String format = "javax_imageio_1.0";
    BufferedImage img =
        new BufferedImage(16, 16, BufferedImage.TYPE_INT_RGB);
    ImageWriter iw = ImageIO.getImageWritersByMIMEType("image/png").next();
    IIOMetadata meta =
        iw.getDefaultImageMetadata(new ImageTypeSpecifier(img), null);
    DOMImplementationRegistry registry;
    registry = DOMImplementationRegistry.newInstance();
    DOMImplementation impl = registry.getDOMImplementation("XML 3.0");
    Document doc = impl.createDocument(null, format, null);
    Element root, text, entry;
    root = doc.getDocumentElement();
    root.appendChild(text = doc.createElement("Text"));
    text.appendChild(entry = doc.createElement("TextEntry"));
    // keyword isn't #REQUIRED by the standard metadata format.
    // However, it is required by the PNG format, so we include it here.
    entry.setAttribute("keyword", "Comment");
    entry.setAttribute("value", "Some demo comment");
    meta.mergeTree(format, root);
}
 
Example #7
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 #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 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 #9
Source File: MergeStdCommentTest.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    String format = "javax_imageio_1.0";
    BufferedImage img =
        new BufferedImage(16, 16, BufferedImage.TYPE_INT_RGB);
    ImageWriter iw = ImageIO.getImageWritersByMIMEType("image/png").next();
    IIOMetadata meta =
        iw.getDefaultImageMetadata(new ImageTypeSpecifier(img), null);
    DOMImplementationRegistry registry;
    registry = DOMImplementationRegistry.newInstance();
    DOMImplementation impl = registry.getDOMImplementation("XML 3.0");
    Document doc = impl.createDocument(null, format, null);
    Element root, text, entry;
    root = doc.getDocumentElement();
    root.appendChild(text = doc.createElement("Text"));
    text.appendChild(entry = doc.createElement("TextEntry"));
    // keyword isn't #REQUIRED by the standard metadata format.
    // However, it is required by the PNG format, so we include it here.
    entry.setAttribute("keyword", "Comment");
    entry.setAttribute("value", "Some demo comment");
    meta.mergeTree(format, root);
}
 
Example #10
Source File: MergeStdCommentTest.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    String format = "javax_imageio_1.0";
    BufferedImage img =
        new BufferedImage(16, 16, BufferedImage.TYPE_INT_RGB);
    ImageWriter iw = ImageIO.getImageWritersByMIMEType("image/png").next();
    IIOMetadata meta =
        iw.getDefaultImageMetadata(new ImageTypeSpecifier(img), null);
    DOMImplementationRegistry registry;
    registry = DOMImplementationRegistry.newInstance();
    DOMImplementation impl = registry.getDOMImplementation("XML 3.0");
    Document doc = impl.createDocument(null, format, null);
    Element root, text, entry;
    root = doc.getDocumentElement();
    root.appendChild(text = doc.createElement("Text"));
    text.appendChild(entry = doc.createElement("TextEntry"));
    // keyword isn't #REQUIRED by the standard metadata format.
    // However, it is required by the PNG format, so we include it here.
    entry.setAttribute("keyword", "Comment");
    entry.setAttribute("value", "Some demo comment");
    meta.mergeTree(format, root);
}
 
Example #11
Source File: MergeStdCommentTest.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    String format = "javax_imageio_1.0";
    BufferedImage img =
        new BufferedImage(16, 16, BufferedImage.TYPE_INT_RGB);
    ImageWriter iw = ImageIO.getImageWritersByMIMEType("image/png").next();
    IIOMetadata meta =
        iw.getDefaultImageMetadata(new ImageTypeSpecifier(img), null);
    DOMImplementationRegistry registry;
    registry = DOMImplementationRegistry.newInstance();
    DOMImplementation impl = registry.getDOMImplementation("XML 3.0");
    Document doc = impl.createDocument(null, format, null);
    Element root, text, entry;
    root = doc.getDocumentElement();
    root.appendChild(text = doc.createElement("Text"));
    text.appendChild(entry = doc.createElement("TextEntry"));
    // keyword isn't #REQUIRED by the standard metadata format.
    // However, it is required by the PNG format, so we include it here.
    entry.setAttribute("keyword", "Comment");
    entry.setAttribute("value", "Some demo comment");
    meta.mergeTree(format, root);
}
 
Example #12
Source File: MergeStdCommentTest.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    String format = "javax_imageio_1.0";
    BufferedImage img =
        new BufferedImage(16, 16, BufferedImage.TYPE_INT_RGB);
    ImageWriter iw = ImageIO.getImageWritersByMIMEType("image/png").next();
    IIOMetadata meta =
        iw.getDefaultImageMetadata(new ImageTypeSpecifier(img), null);
    DOMImplementationRegistry registry;
    registry = DOMImplementationRegistry.newInstance();
    DOMImplementation impl = registry.getDOMImplementation("XML 3.0");
    Document doc = impl.createDocument(null, format, null);
    Element root, text, entry;
    root = doc.getDocumentElement();
    root.appendChild(text = doc.createElement("Text"));
    text.appendChild(entry = doc.createElement("TextEntry"));
    // keyword isn't #REQUIRED by the standard metadata format.
    // However, it is required by the PNG format, so we include it here.
    entry.setAttribute("keyword", "Comment");
    entry.setAttribute("value", "Some demo comment");
    meta.mergeTree(format, root);
}
 
Example #13
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 #14
Source File: XSParser.java    From jlibs with Apache License 2.0 6 votes vote down vote up
public XSParser(LSResourceResolver entityResolver, DOMErrorHandler errorHandler){
    System.setProperty(DOMImplementationRegistry.PROPERTY, DOMXSImplementationSourceImpl.class.getName());
    DOMImplementationRegistry registry;
    try{
        registry = DOMImplementationRegistry.newInstance();
    }catch(Exception ex){
        throw new ImpossibleException(ex);
    }
    XSImplementationImpl xsImpl = (XSImplementationImpl)registry.getDOMImplementation("XS-Loader");

    xsLoader = xsImpl.createXSLoader(null);
    DOMConfiguration config = xsLoader.getConfig();

    config.setParameter(Constants.DOM_VALIDATE, Boolean.TRUE);

    if(entityResolver!=null)
        config.setParameter(Constants.DOM_RESOURCE_RESOLVER, entityResolver);

    if(errorHandler!=null)
        config.setParameter(Constants.DOM_ERROR_HANDLER, errorHandler);
}
 
Example #15
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 #16
Source File: MergeStdCommentTest.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    String format = "javax_imageio_1.0";
    BufferedImage img =
        new BufferedImage(16, 16, BufferedImage.TYPE_INT_RGB);
    ImageWriter iw = ImageIO.getImageWritersByMIMEType("image/png").next();
    IIOMetadata meta =
        iw.getDefaultImageMetadata(new ImageTypeSpecifier(img), null);
    DOMImplementationRegistry registry;
    registry = DOMImplementationRegistry.newInstance();
    DOMImplementation impl = registry.getDOMImplementation("XML 3.0");
    Document doc = impl.createDocument(null, format, null);
    Element root, text, entry;
    root = doc.getDocumentElement();
    root.appendChild(text = doc.createElement("Text"));
    text.appendChild(entry = doc.createElement("TextEntry"));
    // keyword isn't #REQUIRED by the standard metadata format.
    // However, it is required by the PNG format, so we include it here.
    entry.setAttribute("keyword", "Comment");
    entry.setAttribute("value", "Some demo comment");
    meta.mergeTree(format, root);
}
 
Example #17
Source File: Html5ElementStackTest.java    From caja with Apache License 2.0 6 votes vote down vote up
@Override
public void setUp() throws Exception {
  super.setUp();
  DOMImplementationRegistry registry =
      DOMImplementationRegistry.newInstance();
  DOMImplementation domImpl = registry.getDOMImplementation(
      "XML 1.0 Traversal 2.0");

  String qname = "html";
  String systemId = "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd";
  String publicId = "-//W3C//DTD XHTML 1.0 Transitional//EN";

  DocumentType documentType = domImpl.createDocumentType(
      qname, publicId, systemId);
  Document doc = domImpl.createDocument(null, null, documentType);
  mq = new SimpleMessageQueue();

  stack = new Html5ElementStack(doc, false, mq);
  stack.open(false);
}
 
Example #18
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 #19
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 #20
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 #21
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 #22
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 #23
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 #24
Source File: PersistentResourceXMLParserTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private 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 #25
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 #26
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 #27
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 #28
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 #29
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 #30
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
}