Example usage for javax.xml.transform TransformerConfigurationException TransformerConfigurationException

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

Introduction

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

Prototype

public TransformerConfigurationException(Throwable e) 

Source Link

Document

Create a new TransformerConfigurationException with a given Exception base cause of the error.

Usage

From source file:nl.nn.adapterframework.util.TransformerPool.java

protected Transformer getTransformer() throws TransformerConfigurationException {
    try {/*w w  w  .j  av  a 2 s  .co  m*/
        reloadTransformerPool();
        return (Transformer) pool.borrowObject();
    } catch (Exception e) {
        throw new TransformerConfigurationException(e);
    }
}

From source file:nl.nn.adapterframework.util.TransformerPool.java

protected synchronized Transformer createTransformer() throws TransformerConfigurationException {
    Transformer t = templates.newTransformer();
    if (t == null) {
        throw new TransformerConfigurationException("cannot instantiate transformer");
    }//from w w  w.  ja  va 2  s .  co m
    t.setErrorListener(new TransformerErrorListener());
    return t;
}

From source file:nl.nn.adapterframework.util.XmlUtils.java

public static String createXPathEvaluatorSource(String namespaceDefs, String XPathExpression,
        String outputMethod, boolean includeXmlDeclaration, List params, boolean stripSpace, boolean xslt2,
        String separator) throws TransformerConfigurationException {
    if (StringUtils.isEmpty(XPathExpression))
        throw new TransformerConfigurationException("XPathExpression must be filled");

    String namespaceClause = "";
    if (namespaceDefs != null) {
        StringTokenizer st1 = new StringTokenizer(namespaceDefs, ", \t\r\n\f");
        while (st1.hasMoreTokens()) {
            String namespaceDef = st1.nextToken();
            int separatorPos = namespaceDef.indexOf('=');
            if (separatorPos < 1) {
                throw new TransformerConfigurationException(
                        "cannot parse namespace definition from string [" + namespaceDef + "]");
            } else {
                namespaceClause += " xmlns:" + namespaceDef.substring(0, separatorPos) + "=\""
                        + namespaceDef.substring(separatorPos + 1) + "\"";
            }/*from w w  w.  j  a va  2s. c  o  m*/
        }
    }

    final String copyMethod;
    if ("xml".equals(outputMethod)) {
        copyMethod = "copy-of";
    } else {
        copyMethod = "value-of";
    }

    String paramsString = "";
    if (params != null) {
        for (Iterator it = params.iterator(); it.hasNext();) {
            paramsString = paramsString + "<xsl:param name=\"" + it.next() + "\"/>";
        }
    }
    String separatorString = "";
    if (separator != null) {
        separatorString = " separator=\"" + separator + "\"";
    }
    String xsl =
            // "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
            "<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" version=\""
                    + (xslt2 ? "2.0" : "1.0") + "\" xmlns:xalan=\"http://xml.apache.org/xslt\">"
                    + "<xsl:output method=\"" + outputMethod + "\" omit-xml-declaration=\""
                    + (includeXmlDeclaration ? "no" : "yes") + "\"/>"
                    + (stripSpace ? "<xsl:strip-space elements=\"*\"/>" : "") + paramsString
                    + "<xsl:template match=\"/\">" + "<xsl:" + copyMethod + " " + namespaceClause + " select=\""
                    + XPathExpression + "\"" + separatorString + "/>" + "</xsl:template>" + "</xsl:stylesheet>";

    return xsl;
}

From source file:org.alfresco.repo.content.transform.TikaPoweredContentTransformer.java

public void transformInternal(ContentReader reader, ContentWriter writer, TransformationOptions options)
        throws Exception {
    OutputStream os = writer.getContentOutputStream();
    String encoding = writer.getEncoding();
    String targetMimeType = writer.getMimetype();

    Writer ow = new OutputStreamWriter(os, encoding);

    Parser parser = getParser();//  ww w .j a v  a2 s  .c om
    Metadata metadata = new Metadata();
    if (metadataExtracterConfig != null) {
        metadataExtracterConfig.prepareMetadataWithConfigParams(metadata);
    }

    ParseContext context = buildParseContext(metadata, targetMimeType, options);

    ContentHandler handler = getContentHandler(targetMimeType, ow);
    if (handler == null) {
        throw new TransformerConfigurationException(
                "Unable to create Tika Handler for configured output " + targetMimeType);
    }

    InputStream is = null;

    long startTime = 0;
    try {
        is = reader.getContentInputStream();
        if (logger.isDebugEnabled()) {
            startTime = System.currentTimeMillis();
        }

        parser.parse(is, handler, metadata, context);
    } finally {
        if (logger.isDebugEnabled()) {
            logger.debug(calculateMemoryAndTimeUsage(reader, startTime));
        }

        if (is != null) {
            try {
                is.close();
            } catch (Throwable e) {
            }
        }
        if (ow != null) {
            try {
                ow.close();
            } catch (Throwable e) {
            }
        }
        if (os != null) {
            try {
                os.close();
            } catch (Throwable 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(/*from  ww  w.j a  v  a2s  .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.dd4t.core.util.XSLTransformer.java

private Transformer getTransformer(String resource) throws TransformerConfigurationException {
    Transformer trans = null;/*from  w w  w .  j a  va2s .  c o  m*/
    Templates temp = null;

    // first, lets get the template
    if (CACHE.containsKey(resource)) {
        temp = CACHE.get(resource);
    } else {

        InputStream stream = null;
        try {
            stream = getClass().getResourceAsStream(resource);
            if (null == stream) {
                throw new TransformerConfigurationException(
                        "Resource '" + resource + "' could not be loaded. ");
            }
            StreamSource source = new StreamSource(stream);

            // instantiate a transformer
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            temp = transformerFactory.newTemplates(source);

            CACHE.put(resource, temp);
        } finally {
            IOUtils.closeQuietly(stream);
        }
    }

    trans = temp.newTransformer();
    return trans;
}

From source file:org.mycore.common.content.transformer.MCRXSLTransformer.java

private void checkTemplateUptodate() throws TransformerConfigurationException, SAXException {
    boolean check = System.currentTimeMillis() - modifiedChecked > CHECK_PERIOD;
    boolean useCache = MCRConfiguration.instance().getBoolean("MCR.UseXSLTemplateCache", true);
    if (!useCache) {
        check = true;//  w  ww  . j a va 2 s .  c o m
        LOGGER.info("XSL template cache OFF.");
    }

    if (check) {
        for (int i = 0; i < templateSources.length; i++) {
            long lastModified = templateSources[i].getLastModified();
            if (templates[i] == null || modified[i] < lastModified) {
                SAXSource source = templateSources[i].getSource();
                templates[i] = tFactory.newTemplates(source);
                if (templates[i] == null) {
                    throw new TransformerConfigurationException(
                            "XSLT Stylesheet could not be compiled: " + templateSources[i].getURL());
                }
                modified[i] = lastModified;
            }
        }
        modifiedChecked = System.currentTimeMillis();
    }
}

From source file:org.wm.xml.transform.CachingTransformerFactory.java

/**
 * Process the source into a Transformer object. If source is a StreamSource
 * with <code>systemID</code> pointing to a file, transformer is produced
 * from a cached templates object. Cache is done in soft references; cached
 * objects are reloaded, when file's date of last modification changes.
 *
 * @param source An object that holds a URI, input stream, etc.
 * @return A Transformer object that may be used to perform a transformation
 *         in a single thread, never null.
 * @throws TransformerConfigurationException
 *          - May throw this during the/*from  w  w  w .  j  a v  a 2s.  c  om*/
 *          parse when it is constructing the Templates object and fails.
 */
public Transformer newTransformer(final Source source) throws TransformerConfigurationException {
    // Check that source is a StreamSource
    if (source instanceof StreamSource)
        try {
            if (null != source.getSystemId()) {
                // Create URI of the source
                final URI uri = new URI(source.getSystemId());
                // If URI points to a file, load transformer from the file
                // (or from the cache)
                if (FILE_SCHEME.equalsIgnoreCase(uri.getScheme()))
                    return getTemplatesCacheEntry(new File(uri)).templates.newTransformer();
            }
        } catch (URISyntaxException urise) {
            throw new TransformerConfigurationException(urise);
        }
    return super.newTransformer(source);
}

From source file:org.wm.xml.transform.CachingTransformerFactory.java

/**
 * Returns a templates cache entry for the specified file.
 *
 * @param file transformer's file.// w  w  w . j  a va 2 s.c  o  m
 * @return Templates cache entry for the given file.
 * @throws TransformerConfigurationException
 *
 */
private TemplatesCacheEntry getTemplatesCacheEntry(final File file) throws TransformerConfigurationException {
    // Get file's absolute path
    final String absoluteFilePath = file.getAbsolutePath();

    // Search the cache for the templates entry
    TemplatesCacheEntry templatesCacheEntry = (TemplatesCacheEntry) templatesCache.get(absoluteFilePath);

    // If entry found
    if (templatesCacheEntry != null) {
        // Check, if entry was modified
        if (templatesCacheEntry.isModified()) {
            // If it was, set it to null
            templatesCacheEntry = null;
            // And remove from the cache
            templatesCache.remove(absoluteFilePath);
        }
    }

    // If no templatesEntry is found or this entry was obsolete
    if (templatesCacheEntry == null) {
        logger.debug("Loading transformation [" + file.getAbsolutePath() + "].");
        // If this file does not exists, throw the exception
        if (!file.exists()) {
            throw new TransformerConfigurationException(
                    "Requested transformation [" + file.getAbsolutePath() + "] does not exist.");
        }
        // Create new cache entry
        templatesCacheEntry = new TemplatesCacheEntry(file);
    } else
        logger.debug("Using cached transformation [" + file.getAbsolutePath() + "].");
    return templatesCacheEntry;
}