Example usage for javax.xml.transform URIResolver resolve

List of usage examples for javax.xml.transform URIResolver resolve

Introduction

In this page you can find the example usage for javax.xml.transform URIResolver resolve.

Prototype

public Source resolve(String href, String base) throws TransformerException;

Source Link

Document

Called by the processor when it encounters an xsl:include, xsl:import, or document() function.

Usage

From source file:Main.java

public static Document formatXML(Document xml, URIResolver resolver, String... xsls) throws Exception {
    TransformerFactory factory = TransformerFactory.newInstance();
    for (String xsl : xsls) {
        DOMSource xmlSource = new DOMSource(xml);
        Source xslSource = resolver.resolve(xsl, "");
        Templates t = factory.newTemplates(xslSource);
        Transformer transformer = t.newTransformer();
        transformer.setURIResolver(resolver);
        Document resultDoc = newDocument();
        DOMResult result = new DOMResult(resultDoc);
        transformer.transform(xmlSource, result);
        xml = resultDoc;/* w  w w.j a  va 2  s .c o  m*/
    }
    return xml;
}

From source file:edu.mayo.xsltserver.Transformer.java

/**
 * Transform.//  w w w  .  j av  a  2  s . c o m
 *
 * @param xmlInputStream the xml input stream
 * @param xsltInputStream the xslt input stream
 * @param outputStream the output stream
 * @param parameters the parameters
 */
public void transform(InputStream xmlInputStream, InputStream xsltInputStream, OutputStream outputStream,
        Map<String, String> parameters) {
    try {
        // Source XML File
        StreamSource xmlFile = new StreamSource(xmlInputStream);

        // Source XSLT Stylesheet
        StreamSource xsltFile = new StreamSource(xsltInputStream);
        TransformerFactory xsltFactory = TransformerFactory.newInstance();

        final URIResolver decoratedResolver = xsltFactory.getURIResolver();

        xsltFactory.setURIResolver(new URIResolver() {

            @Override
            public Source resolve(String href, String base) throws TransformerException {
                Source source = decoratedResolver.resolve(href,
                        fileService.getStorageDirectory() + File.separator);

                return source;
            }

        });

        javax.xml.transform.Transformer transformer = xsltFactory.newTransformer(xsltFile);

        if (parameters != null) {
            for (Entry<String, String> entry : parameters.entrySet()) {
                transformer.setParameter(entry.getKey(), entry.getValue());
            }
        }

        // Send transformed output to the console
        StreamResult resultStream = new StreamResult(outputStream);

        // Apply the transformation
        transformer.transform(xmlFile, resultStream);
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:net.sf.joost.plugins.traxfilter.THResolver.java

/**
 * @see net.sf.joost.TransformerHandlerResolver#resolve(java.lang.String,
 *      java.lang.String, java.lang.String, javax.xml.transform.URIResolver,
 *      javax.xml.transform.ErrorListener, java.util.Hashtable)
 *//* ww w.j a  va2s. com*/
public TransformerHandler resolve(String method, String href, String base, URIResolver uriResolver,
        ErrorListener errorListener, Hashtable params) throws SAXException {
    if (!available(method))
        throw new SAXException("Not supported filter-method:" + method);

    if (DEBUG)
        log.debug("resolve(url): href=" + href + ", base=" + base);

    if (href == null)
        throw new SAXException("method-src must be url() or buffer()");

    setFilterAttributes(params);

    TransformerHandler th = null;

    // reuse th if available
    th = getReusableHrefTH(method, href);

    // new transformer if non available
    if (th == null) {
        // prepare the source
        Source source = null;
        try {
            // use custom URIResolver if present
            if (uriResolver != null) {
                source = uriResolver.resolve(href, base);
            }
            if (source == null) {
                if (HREF_IS_SYSTEM_ID.booleanValue()) {
                    // systemId
                    if (DEBUG)
                        log.debug("resolve(url): new source out of systemId='" + href + "'");
                    source = new StreamSource(href);
                } else {
                    // file
                    String url = new URL(new URL(base), href).toExternalForm();
                    if (DEBUG)
                        log.debug("resolve(url): new source out of file='" + url + "'");
                    source = new StreamSource(url);
                }
            }
        } catch (MalformedURLException muex) {
            throw new SAXException(muex);
        } catch (TransformerException tex) {
            throw new SAXException(tex);
        }

        th = newTHOutOfTrAX(method, source, params, errorListener, uriResolver);

        // cache the instance if required
        cacheHrefTH(method, href, th);
    }

    prepareTh(th, params);
    return th;
}

From source file:org.mycore.common.xml.MCRURIResolver.java

/**
 * URI Resolver that resolves XSL document() or xsl:include calls.
 *
 * @see javax.xml.transform.URIResolver//ww w.  j a v a2 s.  c o  m
 */
public Source resolve(String href, String base) throws TransformerException {
    if (LOGGER.isDebugEnabled()) {
        if (base != null) {
            LOGGER.debug("Including " + href + " from " + base);
            addDebugInfo(href, base);
        } else {
            LOGGER.debug("Including " + href);
            addDebugInfo(href, null);
        }
    }
    if (!href.contains(":")) {
        return tryResolveXSL(href, base);
    }

    String scheme = getScheme(href, base);

    URIResolver uriResolver = SUPPORTED_SCHEMES.get(scheme);
    if (uriResolver != null) {
        return uriResolver.resolve(href, base);
    } else { // try to handle as URL, use default resolver for file:// and
        try {
            InputSource entity = MCREntityResolver.instance().resolveEntity(null, href);
            if (entity != null) {
                LOGGER.debug("Resolved via EntityResolver: " + entity.getSystemId());
                return new MCRLazyStreamSource(entity::getByteStream, entity.getSystemId());
            }
        } catch (SAXException | IOException e) {
            LOGGER.debug("Error while resolving uri: " + href);
        }
        // http://
        if (href.endsWith("/") && scheme.equals("file")) {
            //cannot stream directories
            return null;
        }
        StreamSource streamSource = new StreamSource();
        streamSource.setSystemId(href);
        return streamSource;
    }
}

From source file:org.apache.xmlgraphics.util.uri.DataURIResolverTestCase.java

/**
 * Test the URIResolver contract if the protocol doesn't match. Resolver
 * must return null in this case./*from  w  w  w  .j  a  v a  2 s  . c  om*/
 *
 * @throws Exception
 *             if an error occurs
 */
public void testNonMatchingContract() throws Exception {
    URIResolver resolver = new DataURIResolver();
    Source src;

    src = resolver.resolve("http://xmlgraphics.apache.org/fop/index.html", null);
    assertNull(src);

    src = resolver.resolve("index.html", "http://xmlgraphics.apache.org/fop/");
    assertNull(src);
}

From source file:org.apache.xmlgraphics.util.uri.DataURIResolverTestCase.java

static final void actualURLHAndlingTest(URIResolver resolver) throws Exception {
    Source src;/* w  w w .  j av  a 2 s  . c  o m*/

    src = resolver.resolve("data:;base64,AAECAwQF", null);
    assertNotNull(src);
    StreamSource streamSource = (StreamSource) src;
    byte[] data = IOUtils.toByteArray(streamSource.getInputStream());
    assertTrue("Decoded data doesn't match the test data", byteCmp(TESTDATA, 0, data));

    src = resolver.resolve("data:application/octet-stream;interpreter=fop;base64,AAECAwQF", null);
    assertNotNull(src);
    streamSource = (StreamSource) src;
    assertNotNull(streamSource.getInputStream());
    assertNull(streamSource.getReader());
    data = IOUtils.toByteArray(streamSource.getInputStream());
    assertTrue("Decoded data doesn't match the test data", byteCmp(TESTDATA, 0, data));

    src = resolver.resolve("data:,FOP", null);
    assertNotNull(src);
    streamSource = (StreamSource) src;
    assertNull(streamSource.getInputStream());
    assertNotNull(streamSource.getReader());
    String text = IOUtils.toString(streamSource.getReader());
    assertEquals("FOP", text);

    src = resolver.resolve("data:,A%20brief%20note", null);
    assertNotNull(src);
    streamSource = (StreamSource) src;
    text = IOUtils.toString(streamSource.getReader());
    assertEquals("A brief note", text);

    src = resolver.resolve("data:text/plain;charset=iso-8859-7,%be%f9%be", null);
    assertNotNull(src);
    streamSource = (StreamSource) src;
    text = IOUtils.toString(streamSource.getReader());
    assertEquals("\u038e\u03c9\u038e", text);
}

From source file:org.trancecode.xproc.cli.CommandLineExecutor.java

private static Source newSource(final URIResolver uriResolver, final String uri, final String errorMessage,
        final Object... args) {
    try {//from   ww w  .  j  a  v  a 2  s  .c o  m
        return uriResolver.resolve(uri, "");
    } catch (final TransformerException resolverError) {
        try {
            return uriResolver.resolve(new File(uri).toURI().toString(), "");
        } catch (final TransformerException fileError) {
            throw new IllegalArgumentException(String.format(errorMessage, args), resolverError);
        }
    }
}