Java Code Examples for org.w3c.dom.bootstrap.DOMImplementationRegistry#newInstance()

The following examples show how to use org.w3c.dom.bootstrap.DOMImplementationRegistry#newInstance() . 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: 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 2
Source File: MergeStdCommentTest.java    From openjdk-8-source 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 3
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 4
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 5
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 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: 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 8
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 9
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 10
Source File: DOMRegistryTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
@Test
public void testDefaultClassloader() throws Exception {
    DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
    DOMImplementation domImpl = registry.getDOMImplementation("LS 3.0");
    Assert.assertNotNull("DOMImplementation not null", domImpl);
    Assert.assertEquals(domImpl.getClass().getName(), getExpectedDOMImplClassName());
}
 
Example 11
Source File: DOMSerializer.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public DOMSerializer() {
    super(Node.class);
    DOMImplementationRegistry registry;
    try {
        registry = DOMImplementationRegistry.newInstance();
    } catch (Exception e) {
        throw new IllegalStateException("Could not instantiate DOMImplementationRegistry: "+e.getMessage(), e);
    }
    _domImpl = (DOMImplementationLS)registry.getDOMImplementation("LS");
}
 
Example 12
Source File: TransformerTestTemplate.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public String prettyPrintDOMResult(DOMResult dr) throws ClassNotFoundException, InstantiationException,
    IllegalAccessException, ClassCastException
{
    DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
    DOMImplementationLS domImplementationLS = (DOMImplementationLS)registry.getDOMImplementation("LS");
    StringWriter writer = new StringWriter();
    LSOutput formattedOutput = domImplementationLS.createLSOutput();
    formattedOutput.setCharacterStream(writer);
    LSSerializer domSerializer = domImplementationLS.createLSSerializer();
    domSerializer.getDomConfig().setParameter("format-pretty-print", true);
    domSerializer.getDomConfig().setParameter("xml-declaration", false);
    domSerializer.write(dr.getNode(), formattedOutput);
    return writer.toString();
}
 
Example 13
Source File: HttpParserTest.java    From teamengine with Apache License 2.0 5 votes vote down vote up
static String writeNodeToString(Node node) throws ClassNotFoundException,
        InstantiationException, IllegalAccessException, ClassCastException {
    DOMImplementationRegistry registry = DOMImplementationRegistry
            .newInstance();
    DOMImplementationLS impl = (DOMImplementationLS) registry
            .getDOMImplementation("LS");
    LSSerializer serializer = impl.createLSSerializer();
    return serializer.writeToString(node);
}
 
Example 14
Source File: DOMRegistryTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeploymentClassloader() throws Exception {
    ClassLoader tccl = Thread.currentThread().getContextClassLoader();
    try {
        ClassLoader classLoader = DOMRegistryTest.class.getClassLoader();
        Thread.currentThread().setContextClassLoader(classLoader);
        DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
        DOMImplementation domImpl = registry.getDOMImplementation("LS 3.0");
        Assert.assertNotNull("DOMImplementation not null", domImpl);
        Assert.assertEquals(domImpl.getClass().getName(), getExpectedDOMImplClassName());
    } finally {
        Thread.currentThread().setContextClassLoader(tccl);
    }
}
 
Example 15
Source File: XmlStringBuffer.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * string value of document
 *
 * @return the string
 */
public final String stringValue()
{
  if(log.isDebugEnabled())
  {
    log.debug("stringValue()");
  }

  if(document == null)
  {
    return this.xml.toString();
  }
  else
  {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
	DOMImplementationRegistry registry = DOMImplementationRegistry
			.newInstance();
	DOMImplementationLS impl = (DOMImplementationLS) registry
			.getDOMImplementation("LS");
	LSSerializer writer = impl.createLSSerializer();
	writer.getDomConfig().setParameter("format-pretty-print",
			Boolean.TRUE);
	LSOutput output = impl.createLSOutput();
	output.setByteStream(out);
	writer.write(document, output);
} catch (Exception e) {
	log.error(e.getMessage(), e);
}
return out.toString();	
  }
}
 
Example 16
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 17
Source File: XercesSchemaValidationUtils.java    From cxf with Apache License 2.0 4 votes vote down vote up
XercesSchemaValidationUtils() throws ClassNotFoundException, InstantiationException,
    IllegalAccessException, ClassCastException {

    DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
    impl = registry.getDOMImplementation("XS-Loader");
}
 
Example 18
Source File: ImportRepairTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
private void tryToParseSchemas() throws Exception {
    // Get DOM Implementation using DOM Registry
    final List<DOMLSInput> inputs = new ArrayList<>();
    final Map<String, LSInput> resolverMap = new HashMap<>();

    for (XmlSchema schema : collection.getXmlSchemas()) {
        if (XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(schema.getTargetNamespace())) {
            continue;
        }
        Document document = new XmlSchemaSerializer().serializeSchema(schema, false)[0];
        DOMLSInput input = new DOMLSInput(document, schema.getTargetNamespace());
        dumpSchema(document);
        resolverMap.put(schema.getTargetNamespace(), input);
        inputs.add(input);
    }

    DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
    DOMImplementation impl = registry.getDOMImplementation("XS-Loader");


    try {
        Object schemaLoader = findMethod(impl, "createXSLoader").invoke(impl, new Object[1]);
        DOMConfiguration config = (DOMConfiguration)findMethod(schemaLoader, "getConfig").invoke(schemaLoader);

        config.setParameter("validate", Boolean.TRUE);
        try {
            //bug in the JDK doesn't set this, but accesses it
            config.setParameter("http://www.oracle.com/xml/jaxp/properties/xmlSecurityPropertyManager",
                                Class.forName("com.sun.org.apache.xerces.internal.utils.XMLSecurityPropertyManager")
                                    .newInstance());

            config.setParameter("http://apache.org/xml/properties/security-manager",
                                Class.forName("com.sun.org.apache.xerces.internal.utils.XMLSecurityManager")
                                    .newInstance());
        } catch (Throwable t) {
            //ignore
        }
        config.setParameter("error-handler", new DOMErrorHandler() {

            public boolean handleError(DOMError error) {
                LOG.info("Schema parsing error: " + error.getMessage()
                         + " " + error.getType()
                         + " " + error.getLocation().getUri()
                         + " " + error.getLocation().getLineNumber()
                         + ":" + error.getLocation().getColumnNumber());
                throw new DOMErrorException(error);
            }
        });
        config.setParameter("resource-resolver", new LSResourceResolver() {

            public LSInput resolveResource(String type, String namespaceURI, String publicId,
                                           String systemId, String baseURI) {
                return resolverMap.get(namespaceURI);
            }
        });

        Method m = findMethod(schemaLoader, "loadInputList");
        String name = m.getParameterTypes()[0].getName() + "Impl";
        name = name.replace("xs.LS", "impl.xs.util.LS");
        Class<?> c = Class.forName(name);
        Object inputList = c.getConstructor(LSInput[].class, Integer.TYPE)
        .newInstance(inputs.toArray(new LSInput[0]), inputs.size());

        findMethod(schemaLoader, "loadInputList").invoke(schemaLoader, inputList);
    } catch (InvocationTargetException ite) {
        throw (Exception)ite.getTargetException();
    }
}
 
Example 19
Source File: HtmlAssetTranslator.java    From RipplePower with Apache License 2.0 4 votes vote down vote up
private static void translateOneFile(String language, Path targetHtmlDir, Path sourceFile,
		String translationTextTranslated) throws IOException {

	Path destFile = targetHtmlDir.resolve(sourceFile.getFileName());

	DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	Document document;
	try {
		DocumentBuilder builder = factory.newDocumentBuilder();
		document = builder.parse(sourceFile.toFile());
	} catch (ParserConfigurationException pce) {
		throw new IllegalStateException(pce);
	} catch (SAXException sae) {
		throw new IOException(sae);
	}

	Element rootElement = document.getDocumentElement();
	rootElement.normalize();

	Queue<Node> nodes = new LinkedList<>();
	nodes.add(rootElement);

	while (!nodes.isEmpty()) {
		Node node = nodes.poll();
		if (shouldTranslate(node)) {
			NodeList children = node.getChildNodes();
			for (int i = 0; i < children.getLength(); i++) {
				nodes.add(children.item(i));
			}
		}
		if (node.getNodeType() == Node.TEXT_NODE) {
			String text = node.getTextContent();
			if (!text.trim().isEmpty()) {
				text = StringsResourceTranslator.translateString(text, language);
				node.setTextContent(' ' + text + ' ');
			}
		}
	}

	Node translateText = document.createTextNode(translationTextTranslated);
	Node paragraph = document.createElement("p");
	paragraph.appendChild(translateText);
	Node body = rootElement.getElementsByTagName("body").item(0);
	body.appendChild(paragraph);

	DOMImplementationRegistry registry;
	try {
		registry = DOMImplementationRegistry.newInstance();
	} catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
		throw new IllegalStateException(e);
	}

	DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
	LSSerializer writer = impl.createLSSerializer();
	String fileAsString = writer.writeToString(document);
	// Replace default XML header with HTML DOCTYPE
	fileAsString = fileAsString.replaceAll("<\\?xml[^>]+>", "<!DOCTYPE HTML>");
	Files.write(destFile, Collections.singleton(fileAsString), StandardCharsets.UTF_8);
}
 
Example 20
Source File: UtilXml.java    From scipio-erp with Apache License 2.0 2 votes vote down vote up
/** Returns a <code>DOMImplementationLS</code> instance.
 * @return A <code>DOMImplementationLS</code> instance
 * @see <a href="http://www.w3.org/TR/2004/REC-DOM-Level-3-LS-20040407/">DOM Level 3 Load and Save Specification</a>
 * @throws ClassCastException
 * @throws ClassNotFoundException
 * @throws InstantiationException
 * @throws IllegalAccessException
 */
public static DOMImplementationLS getDomLsImplementation() throws ClassCastException, ClassNotFoundException, InstantiationException, IllegalAccessException {
    DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
    return (DOMImplementationLS)registry.getDOMImplementation("LS");
}