Example usage for org.w3c.dom.bootstrap DOMImplementationRegistry newInstance

List of usage examples for org.w3c.dom.bootstrap DOMImplementationRegistry newInstance

Introduction

In this page you can find the example usage for org.w3c.dom.bootstrap DOMImplementationRegistry newInstance.

Prototype

public static DOMImplementationRegistry newInstance()
        throws ClassNotFoundException, InstantiationException, IllegalAccessException, ClassCastException 

Source Link

Document

Obtain a new instance of a DOMImplementationRegistry.

Usage

From source file:gov.nih.nci.cacis.common.util.ExtractSchematron.java

/**
 * Creates new instance of the schematron extractor.
 * //from w  ww .j  a  va  2s . c o  m
 * @throws ClassCastException if there is an error getting a SchemaLoader
 * @throws ClassNotFoundException if there is an error getting a SchemaLoader
 * @throws InstantiationException if there is an error getting a SchemaLoader
 * @throws IllegalAccessException if there is an error getting a SchemaLoader
 * @throws TransformerFactoryConfigurationError if there is an error getting a serializer
 * @throws TransformerConfigurationException if there is an error getting a serializer
 * @throws XPathExpressionException if there is an error compiling expressions
 */
public ExtractSchematron()
        throws ClassCastException, ClassNotFoundException, InstantiationException, IllegalAccessException,
        TransformerConfigurationException, TransformerFactoryConfigurationError, XPathExpressionException {
    final DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
    final XSImplementation impl = (XSImplementation) registry.getDOMImplementation("XS-Loader");

    this.dfactory = DocumentBuilderFactory.newInstance();
    this.dfactory.setNamespaceAware(true);

    final XPathFactory factory = XPathFactory.newInstance();
    final XPath xpath = factory.newXPath();
    xpath.setNamespaceContext(new SchNamespaceContext());

    this.serializer = TransformerFactory.newInstance().newTransformer();
    this.serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

    this.patternExpr = xpath.compile("//sch:pattern");

    this.schemaLoader = impl.createXSLoader(null);
}

From source file:com.collabnet.ccf.core.recovery.HospitalArtifactReplayer.java

@SuppressWarnings("deprecation")
private void loadBeanDefinitionsFromUrl(String url, GenericApplicationContext context) {
    BeanDefinitionReader reader = null;/*from   w  ww  .j  a  v  a 2s  . co m*/
    if (url.endsWith(".xml")) {
        reader = new XmlBeanDefinitionReader(context);
    } else if (url.endsWith(".properties")) {
        reader = new PropertiesBeanDefinitionReader(context);
    }

    if (reader != null) {
        try {
            UrlResource urlResource = new UrlResource(url);
            InputStream is = urlResource.getInputStream();
            Document document = builder.parse(is);
            Element routerElement = this.getRouterElement(document);
            this.stripOffProcessors(routerElement);
            this.addGAImportComponents(document, routerElement);
            DOMImplementationRegistry registry = null;
            try {
                registry = DOMImplementationRegistry.newInstance();
            } catch (ClassCastException e) {
                log.error("error", e);
                throw new CCFRuntimeException("error", e);
            } catch (ClassNotFoundException e) {
                log.error("error", e);
                throw new CCFRuntimeException("error", e);
            } catch (InstantiationException e) {
                log.error("error", e);
                throw new CCFRuntimeException("error", e);
            } catch (IllegalAccessException e) {
                log.error("error", e);
                throw new CCFRuntimeException("error", e);
            }
            String originalConfigFileAbsolutePath = urlResource.getFile().getAbsolutePath();
            String componentName = entry.getSourceComponent();
            String configComponentIdentifier = "{" + originalConfigFileAbsolutePath + "}" + componentName;

            File outputFile = null;
            if (componentConfigFileMap.containsKey(configComponentIdentifier)) {
                outputFile = componentConfigFileMap.get(configComponentIdentifier);
            } else {
                outputFile = File.createTempFile(componentName, ".xml", replayWorkDir);
                DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
                LSSerializer writer = impl.createLSSerializer();
                LSOutput output = impl.createLSOutput();
                FileOutputStream bas = new FileOutputStream(outputFile.getAbsolutePath());
                output.setByteStream(bas);
                writer.write(document, output);
                bas.flush();
                bas.close();
                componentConfigFileMap.put(configComponentIdentifier, outputFile);
            }

            // FIXME Use of deprecated method
            UrlResource newUrlResource = new UrlResource(outputFile.toURL().toString());
            ((XmlBeanDefinitionReader) reader).registerBeanDefinitions(document, newUrlResource);
        } catch (BeansException e) {
            log.error("error", e);
            throw new RuntimeException("BeansException : " + e.getMessage(), e);
        } catch (MalformedURLException e) {
            log.error("error", e);
            throw new RuntimeException("MalformedUrlException : " + e.getMessage(), e);
        } catch (IOException e) {
            log.error("error", e);
            throw new RuntimeException("IOExceptionException : " + e.getMessage(), e);
        } catch (SAXException e) {
            log.error("error", e);
            throw new RuntimeException("SAXException : " + e.getMessage(), e);
        }
    } else {
        throw new RuntimeException("No BeanDefinitionReader associated with " + url);
    }
}

From source file:eu.europa.esig.dss.DSSXMLUtils.java

/**
 * Document Object Model (DOM) Level 3 Load and Save Specification See: http://www.w3.org/TR/2004/REC-DOM-Level-3-LS-20040407/
 *
 * @param xmlNode The node to be serialized.
 * @return//from   w  w  w  .  j  a  va 2 s.  c  om
 */
public static byte[] serializeNode(final Node xmlNode) {

    try {

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

        final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        final LSOutput output = impl.createLSOutput();
        output.setByteStream(buffer);
        writer.write(xmlNode, output);

        final byte[] bytes = buffer.toByteArray();
        return bytes;
    } catch (Exception e) {
        throw new DSSException(e);
    }
}

From source file:eu.europa.ec.markt.dss.signature.xades.XAdESProfileT.java

@Override
public Document extendSignatures(Document document, Document originalData, SignatureParameters parameters)
        throws IOException {
    InputStream input = document.openStream();

    if (this.tspSource == null) {
        throw new ConfigurationException(MSG.CONFIGURE_TSP_SERVER);
    }/*w w w .j  a  v a2s  .  com*/

    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder db = dbf.newDocumentBuilder();
        org.w3c.dom.Document doc = db.parse(input);

        NodeList signatureNodeList = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
        if (signatureNodeList.getLength() == 0) {
            throw new RuntimeException(
                    "Impossible to perform the extension of the signature, the document is not signed.");
        }
        for (int i = 0; i < signatureNodeList.getLength(); i++) {
            Element signatureEl = (Element) signatureNodeList.item(i);
            extendSignatureTag(signatureEl, originalData, parameters.getSignatureFormat());
        }

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

        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        LSOutput output = impl.createLSOutput();
        output.setByteStream(buffer);
        writer.write(doc, output);

        return new InMemoryDocument(buffer.toByteArray());

    } catch (ParserConfigurationException ex) {
        throw new RuntimeException(ex);
    } catch (SAXException e) {
        throw new IOException("Cannot parse document", e);
    } catch (ClassCastException e) {
        throw new IOException("Cannot save document", e);
    } catch (ClassNotFoundException e) {
        throw new IOException("Cannot save document", e);
    } catch (InstantiationException e) {
        throw new IOException("Cannot save document", e);
    } catch (IllegalAccessException e) {
        throw new IOException("Cannot save document", e);
    } finally {
        if (input != null) {
            input.close();
        }
    }

}

From source file:ch.agent.crnickl.demo.stox.Chart.java

private void saveChartAsSVG(JFreeChart chart, String fileName, int width, int height) throws KeyedException {
    Writer out = null;/*w  w  w.j ava 2s  .c  o m*/
    try {
        out = new OutputStreamWriter(new FileOutputStream(fileName), "UTF-8");
        String svgNS = "http://www.w3.org/2000/svg";
        DOMImplementation di = DOMImplementationRegistry.newInstance().getDOMImplementation("XML 1.0");
        Document document = di.createDocument(svgNS, "svg", null);

        SVGGeneratorContext ctx = SVGGeneratorContext.createDefault(document);
        ctx.setEmbeddedFontsOn(true);
        SVGGraphics2D svgGenerator = new CustomSVGGraphics2D(ctx, true, 100, true);
        svgGenerator.setSVGCanvasSize(new Dimension(width, height));
        chart.draw(svgGenerator, new Rectangle2D.Double(0, 0, width, height));
        boolean useCSS = true;
        svgGenerator.stream(out, useCSS);
        svgGenerator.dispose();
    } catch (Exception e) {
        throw K.JFC_OUTPUT_ERR.exception(e, fileName);
    } finally {
        try {
            if (out != null)
                out.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:no.difi.sdp.client.asice.signature.CreateSignatureTest.java

private String prettyPrint(final Signature signature)
        throws TransformerException, ClassNotFoundException, InstantiationException, IllegalAccessException {
    StreamSource xmlSource = new StreamSource(new ByteArrayInputStream(signature.getBytes()));
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    DOMResult outputTarget = new DOMResult();
    transformer.transform(xmlSource, outputTarget);

    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);
    writer.getDomConfig().setParameter("xml-declaration", Boolean.FALSE);

    return writer.writeToString(outputTarget.getNode());
}

From source file:eu.europa.ec.markt.dss.signature.xades.XAdESProfileT.java

@Override
public Document extendSignature(Object signatureId, Document document, Document originalData,
        SignatureParameters parameters) throws IOException {
    InputStream input = document.openStream();

    if (this.tspSource == null) {
        throw new ConfigurationException(MSG.CONFIGURE_TSP_SERVER);
    }//from www  .ja va  2s.c o  m

    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder db = dbf.newDocumentBuilder();
        org.w3c.dom.Document doc = db.parse(input);

        NodeList signatureNodeList = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
        if (signatureNodeList.getLength() == 0) {
            throw new RuntimeException(
                    "Impossible to perform the extension of the signature, the document is not signed.");
        }
        for (int i = 0; i < signatureNodeList.getLength(); i++) {
            Element signatureEl = (Element) signatureNodeList.item(i);
            String sid = signatureEl.getAttribute("Id");
            if (signatureId.equals(sid)) {
                extendSignatureTag(signatureEl, originalData, parameters.getSignatureFormat());
            }
        }

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

        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        LSOutput output = impl.createLSOutput();
        output.setByteStream(buffer);
        writer.write(doc, output);

        return new InMemoryDocument(buffer.toByteArray());

    } catch (ParserConfigurationException ex) {
        throw new RuntimeException(ex);
    } catch (SAXException e) {
        throw new IOException("Cannot parse document", e);
    } catch (ClassCastException e) {
        throw new IOException("Cannot save document", e);
    } catch (ClassNotFoundException e) {
        throw new IOException("Cannot save document", e);
    } catch (InstantiationException e) {
        throw new IOException("Cannot save document", e);
    } catch (IllegalAccessException e) {
        throw new IOException("Cannot save document", e);
    } finally {
        if (input != null) {
            input.close();
        }
    }

}

From source file:org.dasein.cloud.cloudstack.CSMethod.java

private String prettifyXml(Document doc) {
    try {//from www. j  a va 2 s .  c o  m
        DOMImplementationLS impl = (DOMImplementationLS) DOMImplementationRegistry.newInstance()
                .getDOMImplementation("LS");
        LSSerializer writer = impl.createLSSerializer();
        writer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);
        return writer.writeToString(doc);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:eu.semaine.util.XMLTool.java

/**
 * Document type to String format conversion 
 * @param document//  w  w w . ja va 2  s  .c  om
 * @return
 * @throws Exception
 * @throws FileNotFoundException
 */
public static String document2String(Document document) throws SystemConfigurationException {
    LSSerializer serializer;
    DOMImplementationLS domImplLS;
    try {
        DOMImplementation implementation = DOMImplementationRegistry.newInstance()
                .getDOMImplementation("XML 3.0");
        domImplLS = (DOMImplementationLS) implementation.getFeature("LS", "3.0");
        serializer = domImplLS.createLSSerializer();
        DOMConfiguration config = serializer.getDomConfig();
        config.setParameter("format-pretty-print", Boolean.TRUE);
        //config.setParameter("canonical-form", Boolean.TRUE);
    } catch (Exception e) {
        throw new SystemConfigurationException("Problem instantiating XML serializer code", e);
    }
    LSOutput output = domImplLS.createLSOutput();
    output.setEncoding("UTF-8");
    StringWriter buf = new StringWriter();
    output.setCharacterStream(buf);
    serializer.write(document, output);
    return buf.toString();
}

From source file:de.betterform.xml.xforms.model.Model.java

private XSLoader getSchemaLoader()
        throws IllegalAccessException, InstantiationException, ClassNotFoundException {
    // System.setProperty(DOMImplementationRegistry.PROPERTY,
    // "org.apache.xerces.dom.DOMXSImplementationSourceImpl");
    DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
    XSImplementation implementation = (XSImplementation) registry.getDOMImplementation("XS-Loader");
    XSLoader loader = implementation.createXSLoader(null);

    DOMConfiguration cfg = loader.getConfig();

    cfg.setParameter("resource-resolver", new LSResourceResolver() {
        public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId,
                String baseURI) {
            LSInput input = new LSInput() {
                String systemId;/*  w ww  .  ja v  a 2 s. c o m*/

                public void setSystemId(String systemId) {
                    this.systemId = systemId;
                }

                public void setStringData(String s) {
                }

                String publicId;

                public void setPublicId(String publicId) {
                    this.publicId = publicId;
                }

                public void setEncoding(String s) {
                }

                public void setCharacterStream(Reader reader) {
                }

                public void setCertifiedText(boolean flag) {
                }

                public void setByteStream(InputStream inputstream) {
                }

                String baseURI;

                public void setBaseURI(String baseURI) {
                    if (baseURI == null || "".equals(baseURI)) {
                        baseURI = getContainer().getProcessor().getBaseURI();
                    }
                    this.baseURI = baseURI;
                }

                public String getSystemId() {
                    return this.systemId;
                }

                public String getStringData() {
                    return null;
                }

                public String getPublicId() {
                    return this.publicId;
                }

                public String getEncoding() {
                    return null;
                }

                public Reader getCharacterStream() {
                    return null;
                }

                public boolean getCertifiedText() {
                    return false;
                }

                public InputStream getByteStream() {
                    if (LOGGER.isTraceEnabled()) {
                        LOGGER.trace("Schema resource\n\t\t publicId '" + publicId + "'\n\t\t systemId '"
                                + systemId + "' requested");
                    }
                    try {
                        String pathToSchema = null;
                        if ("http://www.w3.org/MarkUp/SCHEMA/xml-events-attribs-1.xsd".equals(systemId)) {
                            pathToSchema = "schema/xml-events-attribs-1.xsd";
                        } else if ("http://www.w3.org/2001/XMLSchema.xsd".equals(systemId)) {
                            pathToSchema = "schema/XMLSchema.xsd";
                        } else if ("-//W3C//DTD XMLSCHEMA 200102//EN".equals(publicId)) {
                            pathToSchema = "schema/XMLSchema.dtd";
                        } else if ("datatypes".equals(publicId)) {
                            pathToSchema = "schema/datatypes.dtd";
                        } else if ("http://www.w3.org/2001/xml.xsd".equals(systemId)) {
                            pathToSchema = "schema/xml.xsd";
                        }

                        // LOAD WELL KNOWN SCHEMA
                        if (pathToSchema != null) {
                            if (LOGGER.isTraceEnabled()) {
                                LOGGER.trace("loading Schema '" + pathToSchema + "'\n\n");
                            }
                            return Thread.currentThread().getContextClassLoader()
                                    .getResourceAsStream(pathToSchema);
                        }
                        // LOAD SCHEMA THAT IS NOT(!) YET KNWON TO THE XFORMS PROCESSOR
                        else if (systemId != null && !"".equals(systemId)) {
                            URI schemaURI = new URI(baseURI);
                            schemaURI = schemaURI.resolve(systemId);

                            // ConnectorFactory.getFactory()
                            if (LOGGER.isDebugEnabled()) {
                                LOGGER.debug("loading schema resource '" + schemaURI.toString() + "'\n\n");
                            }
                            return ConnectorFactory.getFactory().getHTTPResourceAsStream(schemaURI);

                        } else {
                            LOGGER.error("resource not known '" + systemId + "'\n\n");
                            return null;
                        }

                    } catch (XFormsException e) {
                        e.printStackTrace();
                    } catch (URISyntaxException e) {
                        e.printStackTrace();
                    }
                    return null;
                }

                public String getBaseURI() {
                    return this.baseURI;
                }
            };
            input.setSystemId(systemId);
            input.setBaseURI(baseURI);
            input.setPublicId(publicId);
            return input;
        }
    });
    // END: Patch
    return loader;
}