Example usage for javax.xml.transform Transformer setURIResolver

List of usage examples for javax.xml.transform Transformer setURIResolver

Introduction

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

Prototype

public abstract void setURIResolver(URIResolver resolver);

Source Link

Document

Set an object that will be used to resolve URIs used in document().

Usage

From source file:fedora.localservices.fop.FOPServlet.java

/**
 * Renders an XML file into a PDF file by applying a stylesheet
 * that converts the XML to XSL-FO. The PDF is written to a byte array
 * that is returned as the method's result.
 * @param xml the XML file/*w  ww  .ja  va2  s .com*/
 * @param xslt the XSLT file
 * @param response HTTP response object
 * @throws FOPException If an error occurs during the rendering of the
 * XSL-FO
 * @throws TransformerException If an error occurs during XSL
 * transformation
 * @throws IOException In case of an I/O problem
 */
protected void renderXML(String xml, String xslt, HttpServletResponse response)
        throws FOPException, TransformerException, IOException {

    //Setup sources
    Source xmlSrc = convertString2Source(xml);
    Source xsltSrc = convertString2Source(xslt);

    //Setup the XSL transformation
    Transformer transformer = this.transFactory.newTransformer(xsltSrc);
    transformer.setURIResolver(this.uriResolver);

    //Start transformation and rendering process
    render(xmlSrc, transformer, response);
}

From source file:it.cnr.icar.eric.server.cms.CanonicalXMLValidationService.java

private void configureTransformer(Transformer transformer) {
    transformer.setURIResolver(rm.getURIResolver());
    transformer.setErrorListener(new ErrorListener() {
        public void error(TransformerException exception) throws TransformerException {
            log.info(exception);/*ww  w. j ava2 s.c om*/
        }

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

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

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

public SOAPElement catalogContent(SOAPElement partCatalogContentRequest) throws RemoteException {
    try {//from   w  ww  . j  a  va 2 s .  co  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:net.sf.joost.trax.TemplatesImpl.java

/**
 * Method returns a Transformer-instance for transformation-process
 * @return A <code>Transformer</code> object.
 * @throws TransformerConfigurationException
 *//*from   w ww  . j  av  a  2 s.c o m*/
public Transformer newTransformer() throws TransformerConfigurationException {

    synchronized (reentryGuard) {
        if (DEBUG)
            log.debug("calling newTransformer to get a " + "Transformer object for Transformation");
        try {
            // register the processor
            Transformer transformer = new TransformerImpl(processor.copy());
            if (factory.getURIResolver() != null)
                transformer.setURIResolver(factory.getURIResolver());
            return transformer;
        } catch (SAXException e) {
            if (log != null)
                log.fatal(e);
            throw new TransformerConfigurationException(e.getMessage());
        }
    }
}

From source file:it.tidalwave.northernwind.core.impl.filter.XsltMacroFilter.java

/*******************************************************************************************************************
 *
 ******************************************************************************************************************/
@Nonnull/*  www. jav a2  s . co  m*/
private Transformer createTransformer() throws TransformerConfigurationException {
    final Source transformation = new StreamSource(new StringReader(xslt));
    final Transformer transformer = transformerFactory.newTransformer(transformation);

    try {
        final URIResolver uriResolver = context.getBean(URIResolver.class);
        log.trace("Using URIResolver: {}", uriResolver.getClass());
        transformer.setURIResolver(uriResolver);
    } catch (NoSuchBeanDefinitionException e) {
        // ok, not installed
    }

    return transformer;
}

From source file:com.spoledge.audao.generator.GeneratorFlow.java

private Transformer getTransformer(String resourceKey) {
    try {// ww w.  j a  v a  2s  .  c o  m
        TemplatesCache tc = generator.getTemplatesCache();
        Templates templates = tc.getTemplates(resourceKey);

        if (templates == null) {
            InputStream is = getClass().getResourceAsStream(resourceKey);
            templates = tc.getTemplates(resourceKey, new StreamSource(is, resourceKey));
        }

        Transformer ret = templates.newTransformer();
        ret.setURIResolver(generator.getResourceURIResolver()); // not auto copied from TrFactory
        ret.setErrorListener(this);
        ret.setParameter("pkg_db", pkgName);

        return ret;
    } catch (TransformerConfigurationException e) {
        throw new RuntimeException(e);
    }
}

From source file:it.cnr.icar.eric.server.cms.CanonicalXMLCatalogingService.java

public ServiceOutput invoke(ServerRequestContext context, ServiceInput input, ServiceType service,
        InvocationController invocationController, UserType user) throws RegistryException {
    if (log.isTraceEnabled()) {
        log.trace("CanonicalXMLCatalogingService.invoke()");
    }//w w  w .j a v a 2 s.c  o m
    ServiceOutput so = new ServiceOutput();
    so.setOutput(context);
    RepositoryItem repositoryItem = input.getRepositoryItem();
    // The RI is optional per the [ebRS] spec. Return empty ServiceOutput.
    if (repositoryItem != null) {
        @SuppressWarnings("unused")
        String roId = input.getRegistryObject().getId();

        ServerRequestContext outputContext = null;

        try {
            outputContext = context; // new RequestContext(null);
            StreamSource inputSrc = getAsStreamSource((ExtrinsicObjectType) input.getRegistryObject());

            StreamSource invocationControlFileSrc = rm.getAsStreamSource(invocationController.getEoId());

            // dumpStream(invocationControlFileSrc);

            TransformerFactory tFactory = TransformerFactory.newInstance();
            Transformer transformer = initTransformer(tFactory, invocationControlFileSrc);
            // Use CatalogingService URIResolver to resolve RIs submitted in
            // the
            // ServiceInput object
            transformer.setURIResolver(getURIResolver(context));
            // Set respository item as parameter
            transformer.setParameter("repositoryItem", input.getRegistryObject().getId());

            // Create the output file with catalogedMetadata
            File outputFile = File.createTempFile("CanonicalXMLCatalogingService_OutputFile", ".xml");
            outputFile.deleteOnExit();

            log.debug("Tempfile= " + outputFile.getAbsolutePath());

            StreamResult sr = new StreamResult(outputFile);
            transformer.transform(inputSrc, sr);

            @SuppressWarnings("unchecked")
            JAXBElement<RegistryObjectListType> ebRegistryObjectList = (JAXBElement<RegistryObjectListType>) bu
                    .getJAXBContext().createUnmarshaller().unmarshal(outputFile);
            // take ComplexType from Element
            RegistryObjectListType catalogedMetadata = ebRegistryObjectList.getValue();

            //            RegistryObjectListType catalogedMetadata = (RegistryObjectListType) bu.getJAXBContext()
            //                  .createUnmarshaller().unmarshal(outputFile);

            // TODO: User should refer to "Service object for the
            // Content Management Service that generated the
            // Cataloged Content."
            outputContext.setUser(user);

            bu.getObjectRefsAndRegistryObjects(catalogedMetadata,
                    outputContext.getTopLevelRegistryObjectTypeMap(), outputContext.getObjectRefTypeMap());
        } catch (Exception e) {
            if (outputContext != context) {
                outputContext.rollback();
            }
            throw new RegistryException(e);
        }

        so.setOutput(outputContext);

        // Setting this error list is redundant, but Content Validation
        // Services
        // currently output a Boolean and a RegistryErrorList, so using
        // same mechanism to report errors from Content Cataloging Services.
        so.setErrorList(outputContext.getErrorList());

        if (outputContext != context) {
            outputContext.commit();
        }
    }
    return so;
}

From source file:org.sakaiproject.metaobj.shared.control.XsltArtifactView.java

/**
 * Perform the actual transformation, writing to the given result.
 * @param source the Source to transform
 * @param parameters a Map of parameters to be applied to the stylesheet
 * @param result the result to write to/*from  ww w . ja va2s . c  o  m*/
 * @throws Exception we let this method throw any exception; the
 * AbstractXlstView superclass will catch exceptions
 */
protected void doTransform(Source source, Map parameters, Result result, String encoding) throws Exception {

    InputStream stylesheetLocation = null;
    // Nulls gets logged by getTransformer, so don't bother logging again.
    if (parameters != null)
        stylesheetLocation = (InputStream) parameters.get(STYLESHEET_LOCATION);
    Transformer trans = getTransformer(stylesheetLocation);

    // Explicitly apply URIResolver to every created Transformer.
    if (getUriResolver() != null) {
        trans.setURIResolver(getUriResolver());
    }

    // Apply any subclass supplied parameters to the transformer.
    if (parameters != null) {
        for (Iterator it = parameters.entrySet().iterator(); it.hasNext();) {
            Map.Entry entry = (Map.Entry) it.next();
            trans.setParameter(entry.getKey().toString(), entry.getValue());
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Added parameters [" + parameters + "] to transformer object");
        }
    }

    // Specify default output properties.
    //trans.setOutputProperty(OutputKeys.ENCODING, encoding);
    trans.setOutputProperty(OutputKeys.INDENT, "yes");

    // Xalan-specific, but won't do any harm in other XSLT engines.
    trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

    // Perform the actual XSLT transformation.
    try {
        trans.transform(source, result);
        if (logger.isDebugEnabled()) {
            logger.debug("XSLT transformed with stylesheet [" + stylesheetLocation + "]");
        }
    } catch (TransformerException ex) {
        throw new NestedServletException("Couldn't perform transform with stylesheet [" + stylesheetLocation
                + "] in XSLT view with name [" + getBeanName() + "]", ex);
    }
}

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

private void setupTransformer(Transformer transformer, ErrorListener errorListener, URIResolver uriResolver) {
    if (errorListener != null)
        transformer.setErrorListener(errorListener);
    if (uriResolver != null)
        transformer.setURIResolver(uriResolver);
}

From source file:org.ambraproject.article.service.XslIngestArchiveProcessor.java

/**
 * Run the zip file through the xsl stylesheet
 *
 * @param zip          the zip archive containing the items to ingest
 * @param zipInfo      the document describing the zip archive (adheres to zip.dtd)
 * @param articleXml      the stylesheet to run on <var>zipInfo</var>; this is the main script
 * @param doiUrlPrefix DOI URL prefix// w  w  w.j av a 2  s. co m
 * @return a document describing the fedora objects to create (must adhere to fedora.dtd)
 * @throws javax.xml.transform.TransformerException
 *          if an error occurs during the processing
 */
private Document transformZip(ZipFile zip, String zipInfo, Document articleXml, String doiUrlPrefix)
        throws TransformerException, URISyntaxException {
    Transformer t = getTranslet(articleXml);
    t.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    t.setURIResolver(new ZipURIResolver(zip));

    // override the doi url prefix if one is specified in the config
    if (doiUrlPrefix != null)
        t.setParameter("doi-url-prefix", doiUrlPrefix);

    /*
     * Note: it would be preferable (and correct according to latest JAXP specs) to use
     * t.setErrorListener(), but Saxon does not forward <xls:message>'s to the error listener.
     * Hence we need to use Saxon's API's in order to get at those messages.
     */
    final StringWriter msgs = new StringWriter();
    MessageWarner em = new MessageWarner();
    ((Controller) t).setMessageEmitter(em);
    t.setErrorListener(new ErrorListener() {
        public void warning(TransformerException te) {
            log.warn("Warning received while processing zip", te);
        }

        public void error(TransformerException te) {
            log.warn("Error received while processing zip", te);
            msgs.write(te.getMessageAndLocation() + '\n');
        }

        public void fatalError(TransformerException te) {
            log.warn("Fatal error received while processing zip", te);
            msgs.write(te.getMessageAndLocation() + '\n');
        }
    });

    Source inp = new StreamSource(new StringReader(zipInfo), "zip:/");
    DOMResult res = new DOMResult();

    try {
        t.transform(inp, res);
    } catch (TransformerException te) {
        if (msgs.getBuffer().length() > 0) {
            log.error(msgs.getBuffer().toString());
            throw new TransformerException(msgs.toString(), te);
        } else
            throw te;
    }
    if (msgs.getBuffer().length() > 0)
        throw new TransformerException(msgs.toString());
    return (Document) res.getNode();
}