Example usage for javax.xml.transform TransformerFactory newTemplates

List of usage examples for javax.xml.transform TransformerFactory newTemplates

Introduction

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

Prototype

public abstract Templates newTemplates(Source source) throws TransformerConfigurationException;

Source Link

Document

Process the Source into a Templates object, which is a a compiled representation of the source.

Usage

From source file:org.ambraproject.service.xml.XMLServiceImpl.java

/**
 * Initialization method called by Spring.
 *
 * @throws org.ambraproject.ApplicationException On Template creation Exceptions.
 */// w w  w. j a  v  a  2 s  .  com
public void init() throws ApplicationException {
    // set JAXP properties
    System.getProperties().putAll(xmlFactoryProperty);

    // Create a document builder factory and set the defaults
    factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setValidating(false);

    // set the Templates
    final TransformerFactory tFactory = TransformerFactory.newInstance();

    //Because we have XSL sheets with import statements.  I override the URI resolver
    //here so the factory knows to look inside the jar files for these files
    tFactory.setURIResolver(new XMLServiceURIResolver());

    try {
        log.debug("Loading XSL: {}", xslDefaultTemplate);
        translet = tFactory.newTemplates(getResourceAsStreamSource(xslDefaultTemplate));
    } catch (TransformerConfigurationException ex) {
        throw new ApplicationException(ex.getMessage(), ex);
    } catch (IOException ex) {
        throw new ApplicationException(ex.getMessage(), ex);
    }
}

From source file:org.ambraproject.service.xml.XMLServiceImpl.java

/**
 * Get a translet, compiled stylesheet, for the xslTemplate. If the doc is null
 * use the default template. If the doc is not null then get the DTD version.
 * IF the DTD version does not exist use the default template else use the
 * template associated with that version.
 *
 * @param  doc  the dtd version of document
 * @return Translet for the xslTemplate.
 * @throws javax.xml.transform.TransformerException TransformerException.
 *//* w w  w. j ava2  s.c o  m*/
private Transformer getTranslet(Document doc) throws TransformerException, URISyntaxException, IOException {
    Transformer transformer;
    // key is "" if the Attribute does not exist
    String key = (doc == null) ? "default" : doc.getDocumentElement().getAttribute("dtd-version").trim();

    if ((!xslTemplateMap.containsKey(key)) || (key.equalsIgnoreCase(""))) {
        transformer = this.translet.newTransformer();
    } else {
        Templates translet;
        String templateName = xslTemplateMap.get(key);

        // set the Templates
        final TransformerFactory tFactory = TransformerFactory.newInstance();
        //Because we have XSL sheets with import statements.  I override the URI resolver
        //here so the factory knows to look inside the jar files for these files
        tFactory.setURIResolver(new XMLServiceURIResolver());

        //TODO: (performace) We should cache the translets when this class is initialized.  We don't need
        //to parse the XSLs for every transform.

        translet = tFactory.newTemplates(getResourceAsStreamSource(templateName));
        transformer = translet.newTransformer();
    }
    transformer.setParameter("pubAppContext", configuration.getString("ambra.platform.appContext", ""));
    return transformer;
}

From source file:org.apache.axis2.util.XMLPrettyPrinter.java

/**
 * Pretty prints contents of the xml file.
 *
 * @param file//from  w  w  w  .  j  av  a2  s .c o m
 */
public static void prettify(final File file) {
    InputStream inputStream = null;
    FileOutputStream outputStream = null;
    byte[] byteArray = null;
    try {
        FileInputStream fin = new FileInputStream(file);
        byteArray = IOUtils.getStreamAsByteArray(fin);
        fin.close();
        inputStream = new ByteArrayInputStream(byteArray);
        outputStream = new FileOutputStream(file);

        Source stylesheetSource = new StreamSource(new ByteArrayInputStream(prettyPrintStylesheet.getBytes()));
        Source xmlSource = new StreamSource(inputStream);

        TransformerFactory tf = TransformerFactory.newInstance();
        Templates templates = tf.newTemplates(stylesheetSource);
        Transformer transformer = templates.newTransformer();
        transformer.setErrorListener(new ErrorListener() {
            public void warning(TransformerException exception) throws TransformerException {
                log.warn("Exception occurred while trying to pretty print file " + file, exception);
            }

            public void error(TransformerException exception) throws TransformerException {
                log.error("Exception occurred while trying to pretty print file " + file, exception);
            }

            public void fatalError(TransformerException exception) throws TransformerException {
                log.error("Exception occurred while trying to pretty print file " + file, exception);
            }
        });
        transformer.transform(xmlSource, new StreamResult(outputStream));

        inputStream.close();
        outputStream.close();
        log.debug("Pretty printed file : " + file);
    } catch (Throwable t) {
        log.debug("Exception occurred while trying to pretty print file " + file, t);

        /* if outputStream is already created, close them, because we are going reassign
         * different value to that. It will leak the file handle (specially in windows, since
         * deleting is going to be an issue)
         */
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException e) {
                log.debug(e.getMessage(), e);
            }
        }
        try {
            if (byteArray != null) {
                outputStream = new FileOutputStream(file);
                outputStream.write(byteArray);
            }
        } catch (IOException e) {
            log.debug(e.getMessage(), e);
        }
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                log.debug(e.getMessage(), e);
            }
        }
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException e) {
                log.debug(e.getMessage(), e);
            }
        }
    }
}

From source file:org.apache.axis2.util.XMLPrettyPrinter.java

public static void prettify(OMElement wsdlElement, OutputStream out) throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    wsdlElement.serialize(baos);//  www . j  a  v a2s .  co m

    Source stylesheetSource = new StreamSource(new ByteArrayInputStream(prettyPrintStylesheet.getBytes()));
    Source xmlSource = new StreamSource(new ByteArrayInputStream(baos.toByteArray()));

    TransformerFactory tf = TransformerFactory.newInstance();
    Templates templates = tf.newTemplates(stylesheetSource);
    Transformer transformer = templates.newTransformer();
    transformer.transform(xmlSource, new StreamResult(out));
}

From source file:org.apache.lucene.gdata.server.registry.ProvidedServiceConfig.java

/**
 * Sets and creates the preview transformer xslt template to provide a html formate for feeds and entries.
 * The given file name must be available in the classpath. 
 * @param filename - the name of the file in the classpath
 *///from   w w  w  .j  av a2s .c o  m
public void setXsltStylesheet(String filename) {
    if (filename == null || filename.length() == 0) {
        LOG.info("No preview stylesheet configured for service " + this.serviceName);
        return;
    }

    TransformerFactory factory = TransformerFactory.newInstance();

    try {
        this.transformerTemplate = factory.newTemplates(new StreamSource(ProvidedServiceConfig.class
                .getResourceAsStream(filename.startsWith("/") ? filename : "/" + filename)));
    } catch (TransformerConfigurationException e) {
        throw new RuntimeException("Can not compile xslt stylesheet path: " + filename, e);
    }

}

From source file:org.apache.nifi.processors.standard.TransformXml.java

private Templates newTemplates(final ProcessContext context, final String path)
        throws TransformerConfigurationException, LookupFailureException {
    final Boolean secureProcessing = context.getProperty(SECURE_PROCESSING).asBoolean();
    TransformerFactory factory = TransformerFactory.newInstance();
    final boolean isFilename = context.getProperty(XSLT_FILE_NAME).isSet();

    if (secureProcessing) {
        factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        // don't be overly DTD-unfriendly forcing http://apache.org/xml/features/disallow-doctype-decl
        factory.setFeature(/* w w  w.j a  va  2 s.  c  o  m*/
                "http://saxon.sf.net/feature/parserFeature?uri=http://xml.org/sax/features/external-parameter-entities",
                false);
        factory.setFeature(
                "http://saxon.sf.net/feature/parserFeature?uri=http://xml.org/sax/features/external-general-entities",
                false);
    }

    if (isFilename) {
        return factory.newTemplates(new StreamSource(path));
    } else {
        final String coordinateKey = lookupService.get().getRequiredKeys().iterator().next();
        final Optional<String> attributeValue = lookupService.get()
                .lookup(Collections.singletonMap(coordinateKey, path));
        if (attributeValue.isPresent() && StringUtils.isNotBlank(attributeValue.get())) {
            return factory.newTemplates(new StreamSource(
                    new ByteArrayInputStream(attributeValue.get().getBytes(StandardCharsets.UTF_8))));
        } else {
            throw new TransformerConfigurationException(
                    "No XSLT definition is associated to " + path + " in the lookup controller service.");
        }
    }
}

From source file:org.apache.solr.util.xslt.TransformerProvider.java

/** Return a Templates object for the given filename */
private Templates getTemplates(ResourceLoader loader, String filename, int cacheLifetimeSeconds)
        throws IOException {

    Templates result = null;/*from   ww  w . j  a va 2s.  c  o  m*/
    lastFilename = null;
    try {
        if (log.isDebugEnabled()) {
            log.debug("compiling XSLT templates:" + filename);
        }
        final String fn = "xslt/" + filename;
        final TransformerFactory tFactory = TransformerFactory.newInstance();
        tFactory.setURIResolver(new SystemIdResolver(loader).asURIResolver());
        tFactory.setErrorListener(xmllog);
        final StreamSource src = new StreamSource(loader.openResource(fn),
                SystemIdResolver.createSystemIdFromResourceName(fn));
        try {
            result = tFactory.newTemplates(src);
        } finally {
            // some XML parsers are broken and don't close the byte stream (but they should according to spec)
            IOUtils.closeQuietly(src.getInputStream());
        }
    } catch (Exception e) {
        log.error(getClass().getName(), "newTemplates", e);
        final IOException ioe = new IOException("Unable to initialize Templates '" + filename + "'");
        ioe.initCause(e);
        throw ioe;
    }

    lastFilename = filename;
    lastTemplates = result;
    cacheExpires = System.currentTimeMillis() + (cacheLifetimeSeconds * 1000);

    return result;
}

From source file:org.apache.struts2.views.xslt.XSLTResult.java

protected Templates getTemplates(final String path) throws TransformerException, IOException {
    if (path == null)
        throw new TransformerException("Stylesheet path is null");

    Templates templates = templatesCache.get(path);

    if (noCache || (templates == null)) {
        synchronized (templatesCache) {
            URL resource = ServletActionContext.getServletContext().getResource(path);

            if (resource == null) {
                throw new TransformerException("Stylesheet " + path + " not found in resources.");
            }//from   w ww  .j  a v a 2  s.c  o m

            LOG.debug("Preparing XSLT stylesheet templates: {}", path);

            TransformerFactory factory = TransformerFactory.newInstance();
            factory.setURIResolver(getURIResolver());
            factory.setErrorListener(buildErrorListener());
            templates = factory.newTemplates(new StreamSource(resource.openStream()));
            templatesCache.put(path, templates);
        }
    }

    return templates;
}

From source file:org.apereo.portal.utils.cache.resource.TemplatesBuilder.java

@Override
public LoadedResource<Templates> loadResource(Resource resource) throws IOException {
    final TransformerFactory transformerFactory = TransformerFactory.newInstance();

    if (this.transformerAttributes != null) {
        for (final Map.Entry<String, Object> attributeEntry : this.transformerAttributes.entrySet()) {
            transformerFactory.setAttribute(attributeEntry.getKey(), attributeEntry.getValue());
        }/*from  www .j a va 2s.c o  m*/
    }

    final ResourceTrackingURIResolver uriResolver = new ResourceTrackingURIResolver(this.resourceLoader);
    transformerFactory.setURIResolver(uriResolver);

    final URI uri = resource.getURI();
    final String systemId = uri.toString();

    final InputStream stream = resource.getInputStream();
    final Templates templates;
    try {
        final StreamSource source = new StreamSource(stream, systemId);
        templates = transformerFactory.newTemplates(source);
    } catch (TransformerConfigurationException e) {
        throw new IOException("Failed to parse stream into Templates", e);
    } finally {
        IOUtils.closeQuietly(stream);
    }

    final Map<Resource, Long> resolvedResources = uriResolver.getResolvedResources();

    return new LoadedResourceImpl<Templates>(templates, resolvedResources);
}

From source file:org.carrot2.dcs.RestProcessorServlet.java

/**
 * /*  ww  w  .j a  va 2 s  . c  om*/
 */
private void initXslt(DcsConfig config, ResourceLookup resourceLookup) {
    final TransformerFactory tFactory = TransformerFactory.newInstance();
    tFactory.setURIResolver(new NopURIResolver());

    InputStream xsltStream = null;

    if (StringUtils.isNotBlank(config.xslt)) {
        IResource resource = resourceLookup.getFirst(config.xslt);
        if (resource == null) {
            config.logger.warn(
                    "XSLT stylesheet " + config.xslt + " not found. No XSLT transformation will be applied.");
            return;
        }

        try {
            xsltStream = resource.open();
            xsltTemplates = tFactory.newTemplates(new StreamSource(xsltStream));
            config.logger.info("XSL stylesheet loaded successfully from: " + config.xslt);
        } catch (IOException e) {
            config.logger.warn("Could not load stylesheet, no XSLT transform will be applied.", e);
        } catch (TransformerConfigurationException e) {
            config.logger.warn("Could not load stylesheet, no XSLT transform will be applied", e);
        } finally {
            CloseableUtils.close(xsltStream);
        }
    }
}