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

The following examples show how to use org.w3c.dom.bootstrap.DOMImplementationRegistry#getDOMImplementation() . 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: 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 2
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 3
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 4
Source File: MergeStdCommentTest.java    From hottub 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: ErrorResponseBuilder.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
private static String marshall(XMLObject xmlObject) throws org.wso2.carbon.identity.base.IdentityException {
    try {
        System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
                "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");

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

        ByteArrayOutputStream byteArrayOutputStrm = new ByteArrayOutputStream();
        DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
        DOMImplementationLS impl =
                (DOMImplementationLS) registry.getDOMImplementation("LS");
        LSSerializer writer = impl.createLSSerializer();
        LSOutput output = impl.createLSOutput();
        output.setByteStream(byteArrayOutputStrm);
        writer.write(element, output);
        return byteArrayOutputStrm.toString("UTF-8");
    } catch (Exception e) {
        log.error("Error Serializing the SAML Response");
        throw IdentityException.error("Error Serializing the SAML Response", e);
    }
}
 
Example 6
Source File: 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 7
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 8
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 9
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 10
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 11
Source File: Bug6367542.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testDOMImplementationRegistry() {
    try {
        DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
        DOMImplementation domImpl = registry.getDOMImplementation("XML");
        Assert.assertTrue(domImpl != null, "Non null implementation is expected for getDOMImplementation('XML')");
    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail("Exception occured: " + e.getMessage());
    }
}
 
Example 12
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 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: CoreUtils.java    From TranskribusCore with GNU General Public License v3.0 5 votes vote down vote up
/**
	 * from: https://stackoverflow.com/questions/139076/how-to-pretty-print-xml-from-java
	 * @param xml The string representation of the unformatted XML
	 * @return The string representation of the formatted XML
	 * @throws ClassCastException 
	 * @throws IllegalAccessException 
	 * @throws InstantiationException 
	 * @throws ClassNotFoundException 
	 * @throws ParserConfigurationException 
	 * @throws IOException 
	 * @throws SAXException 
	 * @deprecated does it work with correct encoding?
	 */
	public static String formatXml(String xml) throws ClassNotFoundException, InstantiationException, IllegalAccessException, ClassCastException, SAXException, IOException, ParserConfigurationException {
//		try {
			final InputSource src = new InputSource(new StringReader(xml));
			final Node document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(src)
					.getDocumentElement();
			final Boolean keepDeclaration = Boolean.valueOf(xml.startsWith("<?xml"));

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

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

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

//			return writer.writeToString(document);
//		} catch (Exception e) {
//			throw new RuntimeException(e);
//		}
	}
 
Example 15
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 16
Source File: PrettyPrintTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private String serializerWrite(Node xml, boolean pretty) throws Exception {
    DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
    DOMImplementationLS domImplementation = (DOMImplementationLS) registry.getDOMImplementation("LS");
    StringWriter writer = new StringWriter();
    LSOutput formattedOutput = domImplementation.createLSOutput();
    formattedOutput.setCharacterStream(writer);
    LSSerializer domSerializer = domImplementation.createLSSerializer();
    domSerializer.getDomConfig().setParameter(DOM_FORMAT_PRETTY_PRINT, pretty);
    domSerializer.getDomConfig().setParameter("xml-declaration", false);
    domSerializer.write(xml, formattedOutput);
    return writer.toString();
}
 
Example 17
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 18
Source File: WebBrowserImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void _dumpDocument( Document doc, String title ) {
    if( null == title || title.isEmpty() ) {
        title = NbBundle.getMessage(WebBrowserImpl.class, "Lbl_GenericDomDumpTitle");
    }
    InputOutput io = IOProvider.getDefault().getIO( title, true );
    io.select();
    try {
        DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
        DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation( "XML 3.0 LS 3.0" ); //NOI18N
        if( null == impl ) {
            io.getErr().println( NbBundle.getMessage(WebBrowserImpl.class, "Err_DOMImplNotFound") );
            return;
        }


        LSSerializer serializer = impl.createLSSerializer();
        if( serializer.getDomConfig().canSetParameter( "format-pretty-print", Boolean.TRUE ) ) { //NOI18N
            serializer.getDomConfig().setParameter( "format-pretty-print", Boolean.TRUE ); //NOI18N
        }
        LSOutput output = impl.createLSOutput();
        output.setEncoding("UTF-8"); //NOI18N
        output.setCharacterStream( io.getOut() );
        serializer.write(doc, output);
        io.getOut().println();

    } catch( Exception ex ) {
        ex.printStackTrace( io.getErr() );
    } finally {
        if( null != io ) {
            io.getOut().close();
            io.getErr().close();
        }
    }
}
 
Example 19
Source File: CordovaPluginXMLHelper.java    From thym with Eclipse Public License 1.0 5 votes vote down vote up
public static String stringifyNode(Node node){
	try {
		DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
		DOMImplementationLS impl = (DOMImplementationLS)registry.getDOMImplementation("LS");
		LSSerializer writer = impl.createLSSerializer();
		writer.getDomConfig().setParameter("xml-declaration", Boolean.FALSE);
		String str = writer.writeToString(node);
		return str;
	} catch (Exception e) {
		HybridCore.log(IStatus.ERROR, "Error resolving node for injection", e);
		return null;
	}
}
 
Example 20
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();
    }
}