Example usage for javax.xml.transform URIResolver URIResolver

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

Introduction

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

Prototype

URIResolver

Source Link

Usage

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

/**
 * Transform.// w  w w .j  a v  a  2 s .c om
 *
 * @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:com.consol.citrus.admin.service.spring.SpringBeanService.java

@PostConstruct
protected void init() {
    transformerFactory.setURIResolver(new URIResolver() {
        @Override//from ww  w .j a v a2s. c o  m
        public Source resolve(String href, String base) throws TransformerException {
            try {
                return new StreamSource(new ClassPathResource("transform/" + href).getInputStream());
            } catch (IOException e) {
                throw new TransformerException("Failed to resolve uri: " + href, e);
            }
        }
    });
}

From source file:com.predic8.membrane.core.interceptor.schemavalidation.SchematronValidator.java

public SchematronValidator(ResolverMap resourceResolver, String schematron,
        ValidatorInterceptor.FailureHandler failureHandler, Router router, BeanFactory beanFactory)
        throws Exception {
    this.failureHandler = failureHandler;

    //works as standalone "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl"
    TransformerFactory fac;/*w ww  .j a  va2s .  co m*/
    try {
        fac = beanFactory.getBean("transformerFactory", TransformerFactory.class);
    } catch (NoSuchBeanDefinitionException e) {
        throw new RuntimeException(
                "Please define a bean called 'transformerFactory' in monitor-beans.xml, e.g. with "
                        + "<spring:bean id=\"transformerFactory\" class=\"com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl\" />",
                e);
    }
    fac.setURIResolver(new URIResolver() {
        @Override
        public Source resolve(String href, String base) throws TransformerException {
            return new StreamSource(SchematronValidator.class.getResourceAsStream(href));
        }
    });
    Transformer t = fac.newTransformer(
            new StreamSource(SchematronValidator.class.getResourceAsStream("conformance1-5.xsl")));

    // transform schematron-XML into XSLT
    DOMResult r = new DOMResult();
    t.transform(new StreamSource(router.getResolverMap().resolve(schematron)), r);

    // build XSLT transformers
    fac.setURIResolver(null);
    int concurrency = Runtime.getRuntime().availableProcessors() * 2;
    transformers = new ArrayBlockingQueue<Transformer>(concurrency);
    for (int i = 0; i < concurrency; i++) {
        Transformer transformer = fac.newTransformer(new DOMSource(r.getNode()));
        transformer.setErrorListener(new NullErrorListener()); // silence console logging
        transformers.put(transformer);
    }

    xmlInputFactory = XMLInputFactory.newInstance();
    xmlInputFactory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, false);
    xmlInputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
}

From source file:org.jboss.windup.decorator.xml.XSLTDecorator.java

@Override
public void afterPropertiesSet() {
    LOG.debug("Getting XSLT Location: " + xsltLocation);
    Source xsltSource = new StreamSource(
            Thread.currentThread().getContextClassLoader().getResourceAsStream(xsltLocation));
    try {/*from   w  ww  . j a  va2s  .  co  m*/
        TransformerFactory tf = TransformerFactory.newInstance();
        tf.setURIResolver(new URIResolver() {
            @Override
            public Source resolve(String href, String base) throws TransformerException {
                // fetch local only, for speed reasons.
                if (StringUtils.contains(href, "http://")) {
                    LOG.warn("Trying to fetch remote URL for XSLT.  This is not possible; for speed reasons: "
                            + href + ": " + base);
                    return null;
                }
                return new StreamSource(
                        Thread.currentThread().getContextClassLoader().getResourceAsStream(href));
            }
        });

        xsltTransformer = tf.newTransformer(xsltSource);
        if (xsltParameters != null) {
            for (String key : xsltParameters.keySet()) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Setting property: " + key + " -> " + xsltParameters.get(key));
                }
                xsltTransformer.setParameter(key, xsltParameters.get(key));
            }
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug("Created XSLT successfully: " + xsltLocation);
        }
    } catch (Exception e) {
        LOG.error("Exception creating XSLT: " + xsltLocation, e);
    }
}

From source file:edu.unc.lib.dl.ingest.sip.METSPackageSIPProcessor.java

public METSPackageSIPProcessor() {
    try {/*from  w  w  w .  j a  va  2s.com*/
        _countObjectsXpath = XPath.newInstance(countObjectsXpath);
        _countObjectsXpath.addNamespace(METS_NS);
    } catch (JDOMException e) {
        log.error("Bad Configuration for Mets2FoxmlFilter", e);
        throw new IllegalArgumentException("Bad Configuration for Mets2FoxmlFilter", e);
    }
    Source mets2foxsrc = new StreamSource(
            METSPackageSIPProcessor.class.getResourceAsStream(stylesheetPackage + "base-model.xsl"));
    // requires a Saxon 8 transformer factory
    try {
        TransformerFactory factory = TransformerFactory.newInstance();
        // set a Resolver that can look in the classpath
        factory.setURIResolver(new URIResolver() {
            public Source resolve(String href, String base) throws TransformerException {
                Source result = null;
                if (href.startsWith("/"))
                    result = new StreamSource(METSPackageSIPProcessor.class.getResourceAsStream(href));
                else
                    result = new StreamSource(
                            METSPackageSIPProcessor.class.getResourceAsStream(stylesheetPackage + href));
                return result;
            }
        });

        mets2fox = factory.newTemplates(mets2foxsrc);
    } catch (TransformerFactoryConfigurationError e) {
        log.error("Error setting up transformer factory.", e);
        throw new Error("Error setting up transformer factory", e);
    } catch (TransformerConfigurationException e) {
        log.error("Error setting up transformer.", e);
        throw new Error("Error setting up transformer", e);
    }
}

From source file:edu.unc.lib.dl.schematron.SchematronValidator.java

/**
 * Use this to initialize the configured schemas. Generate stylesheet
 * implementations of ISO Schematron files and preload them into Transformer
 * Templates for quick use.//ww w  . j  av  a2 s .c  o  m
 */
public void loadSchemas() {
    templates = new HashMap<String, Templates>();
    // Load up a transformer and the ISO Schematron to XSL templates.
    Templates isoSVRLTemplates = null;
    ClassPathResource svrlRes = new ClassPathResource("/edu/unc/lib/dl/schematron/iso_svrl.xsl",
            SchematronValidator.class);
    Source svrlrc;
    try {
        svrlrc = new StreamSource(svrlRes.getInputStream());
    } catch (IOException e1) {
        throw new Error("Cannot load iso_svrl.xsl", e1);
    }
    TransformerFactory factory = null;
    try {
        factory = new TransformerFactoryImpl();
        // enable relative classpath-based URIs
        factory.setURIResolver(new URIResolver() {
            public Source resolve(String href, String base) throws TransformerException {
                ClassPathResource svrlRes = new ClassPathResource(href, SchematronValidator.class);
                Source result;
                try {
                    result = new StreamSource(svrlRes.getInputStream());
                } catch (IOException e1) {
                    throw new TransformerException("Cannot resolve " + href, e1);
                }
                return result;
            }
        });
        isoSVRLTemplates = factory.newTemplates(svrlrc);
    } catch (TransformerFactoryConfigurationError e) {
        log.error("Error setting up transformer factory.", e);
        throw new Error("Error setting up transformer factory", e);
    } catch (TransformerConfigurationException e) {
        log.error("Error setting up transformer.", e);
        throw new Error("Error setting up transformer", e);
    }

    // Get a transformer
    Transformer t = null;
    try {
        t = isoSVRLTemplates.newTransformer();
    } catch (TransformerConfigurationException e) {
        throw new Error("There was a problem configuring the transformer.", e);
    }

    for (String schema : schemas.keySet()) {
        // make XSLT out of Schematron for each schema
        Resource resource = schemas.get(schema);
        Source schematron = null;
        try {
            schematron = new StreamSource(resource.getInputStream());
        } catch (IOException e) {
            throw new Error("Cannot load resource for schema \"" + schema + "\" at " + resource.getDescription()
                    + resource.toString());
        }
        JDOMResult res = new JDOMResult();
        try {
            t.transform(schematron, res);
        } catch (TransformerException e) {
            throw new Error("Schematron issue: There were problems transforming Schematron to XSL.", e);
        }

        // compile templates object for each profile
        try {
            Templates schemaTemplates = factory.newTemplates(new JDOMSource(res.getDocument()));
            templates.put(schema, schemaTemplates);
        } catch (TransformerConfigurationException e) {
            throw new Error("There was a problem configuring the transformer.", e);
        }
    }

}

From source file:it.cnr.icar.eric.service.catalogingTest.cppaCataloging.CPPACataloging.java

public SOAPElement catalogContent(SOAPElement partCatalogContentRequest) throws RemoteException {
    try {/*from  ww w  . j a  v a2 s  . c o m*/
        if (log.isDebugEnabled()) {
            printNodeToConsole(partCatalogContentRequest);
        }

        final HashMap<String, DataHandler> repositoryItemDHMap = getRepositoryItemDHMap();

        if (log.isDebugEnabled()) {
            log.debug("Attachments: " + repositoryItemDHMap.size());
        }

        Object requestObj = getBindingObjectFromNode(partCatalogContentRequest);

        if (!(requestObj instanceof CatalogContentRequest)) {
            throw new Exception(
                    "Wrong response received from validation service.  Expected CatalogContentRequest, got: "
                            + partCatalogContentRequest.getElementName().getQualifiedName());
        }

        ccReq = (CatalogContentRequest) requestObj;

        IdentifiableType originalContentIT = ccReq.getOriginalContent().getIdentifiable().get(0).getValue();
        IdentifiableType invocationControlIT = ccReq.getInvocationControlFile().get(0);

        DataHandler invocationControlDH = repositoryItemDHMap.get(invocationControlIT.getId());

        if (log.isDebugEnabled()) {
            log.debug("originalContentIT id: " + originalContentIT.getId());
            log.debug("invocationControlIT id: " + invocationControlIT.getId());
        }

        StreamSource invocationControlSrc = new StreamSource(invocationControlDH.getInputStream());

        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer(invocationControlSrc);

        transformer.setURIResolver(new URIResolver() {
            public Source resolve(String href, String base) throws TransformerException {
                Source source = null;
                try {
                    // Should this check that href is UUID URN first?
                    source = new StreamSource((repositoryItemDHMap.get(href)).getInputStream());
                } catch (Exception e) {
                    source = null;
                }

                return source;
            }
        });
        transformer.setErrorListener(new ErrorListener() {
            public void error(TransformerException exception) throws TransformerException {
                log.info(exception);
            }

            public void fatalError(TransformerException exception) throws TransformerException {
                log.error(exception);
                throw exception;
            }

            public void warning(TransformerException exception) throws TransformerException {
                log.info(exception);
            }
        });

        //Set respository item as parameter
        transformer.setParameter("repositoryItem", originalContentIT.getId());

        StringWriter sw = new StringWriter();
        transformer.transform(new JAXBSource(jaxbContext, originalContentIT), new StreamResult(sw));

        ccResp = cmsFac.createCatalogContentResponse();

        RegistryObjectListType catalogedMetadata = (RegistryObjectListType) getUnmarshaller()
                .unmarshal(new StreamSource(new StringReader(sw.toString())));
        RegistryObjectListType roList = rimFac.createRegistryObjectListType();
        ccResp.setCatalogedContent(roList);
        // FIXME: Setting catalogedMetadata as CatalogedContent results in incorrect serialization.
        roList.getIdentifiable().addAll(catalogedMetadata.getIdentifiable());

        ccResp.setStatus(CANONICAL_RESPONSE_STATUS_TYPE_ID_Success);

        ccRespElement = getSOAPElementFromBindingObject(ccResp);

        // Copy request's attachments to response to exercise attachment-processing code on client.
        MessageContext mc = servletEndpointContext.getMessageContext();
        mc.setProperty(com.sun.xml.rpc.server.ServerPropertyConstants.SET_ATTACHMENT_PROPERTY,
                (Collection<?>) mc
                        .getProperty(com.sun.xml.rpc.server.ServerPropertyConstants.GET_ATTACHMENT_PROPERTY));

    } catch (Exception e) {
        throw new RemoteException("Could not create response.", e);
    }

    return ccRespElement;
}

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

/**
 * Merge two XML files using XSLT//from   w  w  w. j  av  a2  s .com
 * @param xmlFileContent1, first XML file content 
 * @param xmlFileContent2, second XML file content
 * @param xmlStyleSheet, XSL style sheet as a inputstream 
 * @param refCodeName, code name used in xsl sheet to refer xmlFile2 (example: semaine.mary.intonation ) 
 * @return output of merged xml file
 * @throws Exception
 * @throws FileNotFoundException
 */
public static String mergeTwoXMLFiles(String xmlFileContent1, final String xmlFileContent2,
        InputStream xmlStyleSheet, final String refCodeName) throws Exception, FileNotFoundException {

    Templates mergeXML2IntoStylesheet;
    TransformerFactory tFactory = TransformerFactory.newInstance();
    //StreamSource stylesheetStream = new StreamSource(new FileReader(xmlStyleSheet));
    StreamSource stylesheetStream = new StreamSource(xmlStyleSheet);

    mergeXML2IntoStylesheet = tFactory.newTemplates(stylesheetStream);
    StreamSource xml1Source = new StreamSource(new StringReader(xmlFileContent1));
    StringWriter mergedWriter = new StringWriter();
    StreamResult mergedResult = new StreamResult(mergedWriter);
    // Transformer is not guaranteed to be thread-safe -- therefore, we
    // need one per thread.
    Transformer mergingTransformer = mergeXML2IntoStylesheet.newTransformer();
    mergingTransformer.setURIResolver(new URIResolver() {
        public Source resolve(String href, String base) {
            if (href == null) {
                return null;
            } else if (href.equals(refCodeName)) {
                return (new StreamSource(new StringReader(xmlFileContent2)));
            } else {
                return null;
            }
        }
    });

    mergingTransformer.transform(xml1Source, mergedResult);
    return mergedWriter.toString();
}

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

/**
 * Merge two XML files using XSLT/*from  w  w w. j a v  a2s  .  c o  m*/
 * @param xmlFileContent1, first XML file content 
 * @param xmlFileContent2, second XML file content
 * @param mergingStylesheet, the XSLT style sheet merging xml2 into xml1.
 * @param refCodeName, code name used in xsl sheet to refer xmlFile2 (example: semaine.mary.intonation ) 
 * @return output of merged xml file
 * @throws Exception
 * @throws FileNotFoundException
 */
public static Document mergeTwoXMLFiles(Document xmlFileContent1, final Document xmlFileContent2,
        Templates mergingStylesheet, final String refCodeName) throws Exception, FileNotFoundException {

    DOMSource xml1Source = new DOMSource(xmlFileContent1);
    DOMResult mergedDR = new DOMResult();
    // Transformer is not guaranteed to be thread-safe -- therefore, we
    // need one per thread.
    Transformer mergingTransformer = mergingStylesheet.newTransformer();
    mergingTransformer.setURIResolver(new URIResolver() {
        public Source resolve(String href, String base) {
            if (href == null) {
                return null;
            } else if (href.equals(refCodeName)) {
                return (new DOMSource(xmlFileContent2));
            } else {
                return null;
            }
        }
    });

    mergingTransformer.transform(xml1Source, mergedDR);
    return (Document) mergedDR.getNode();
}

From source file:com.enonic.vertical.adminweb.AdminHandlerBaseServlet.java

protected URIResolver getStylesheetURIResolver(final AdminService adminBean) {
    return new URIResolver() {

        public Source resolve(String href, String base) throws TransformerException {
            Source source = null;
            ResourceKey key = new ResourceKey(href);
            ResourceFile res = resourceService.getResourceFile(key);
            if (res != null) {
                String xsl = res.getDataAsString();
                source = new StreamSource(new StringReader(xsl));
            }/* w  w w .  j  a  v a2s . co  m*/
            return source;
        }
    };
}