Example usage for javax.xml.transform Transformer getClass

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

Introduction

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

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:Main.java

public static boolean supportsXSLT20(final Transformer tranformer) {
    return tranformer.getClass().getName().startsWith("net.sf.saxon.");
}

From source file:com.microsoft.tfs.util.xml.JAXPUtils.java

/**
 * A convenience method to create a new {@link Transformer} using the given
 * {@link TransformerFactory}. The new {@link Transformer} is not configured
 * in any way by this method./*w ww  .j  av a  2 s  .  c  o m*/
 *
 * @throws XMLException
 *         if a new {@link Transformer} can't be created
 *
 * @param factory
 *        the {@link TransformerFactory} to use or <code>null</code> to
 *        create a new factory using the {@link #newTransformerFactory()}
 *        method
 * @return a new {@link Transformer} created from the given
 *         {@link TransformerFactory} (never <code>null</code>)
 */
public static Transformer newTransformer(TransformerFactory factory) {
    if (factory == null) {
        factory = newTransformerFactory();
    }

    try {
        final Transformer transformer = factory.newTransformer();

        if (log.isTraceEnabled()) {
            final String messageFormat = "Created a new Transformer: {0} (loaded from: {1}) (factory: {2})"; //$NON-NLS-1$
            final String message = MessageFormat.format(messageFormat, transformer.getClass().getName(),
                    transformer.getClass().getClassLoader(), factory.getClass().getName());
            log.trace(message);
        }

        return transformer;
    } catch (final TransformerConfigurationException e) {
        throw new XMLException(e);
    }
}

From source file:com.lmco.ddf.ui.Query.java

/**
 * //from   w  w w  .jav a2s .c om
 * @param unformattedXml Unformatted xml.
 * @return Returns formatted xml.
 */
private String format(String unformattedXml) {
    Source xmlInput = new StreamSource(new StringReader(unformattedXml));
    StringWriter stringWriter = new StringWriter();
    StreamResult xmlOutput = new StreamResult(stringWriter);
    TransformerFactory transformerFactory = TransformerFactory.newInstance();

    Transformer transformer = null;
    String formattedXml = null;

    try {
        transformer = transformerFactory.newTransformer();
        LOGGER.debug("transformer class: " + transformer.getClass());
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        transformer.transform(xmlInput, xmlOutput);
        formattedXml = xmlOutput.getWriter().toString();
    } catch (TransformerConfigurationException e)

    {
        String message = "Unable to transform xml:\n" + unformattedXml + "\nUsing unformatted xml.";
        LOGGER.error(message, e);
        formattedXml = unformattedXml;
    } catch (TransformerException e) {
        String message = "Unable to transform xml:\n" + unformattedXml + "\nUsing unformatted xml.";
        LOGGER.error(message, e);
        formattedXml = unformattedXml;
    }

    LOGGER.debug("Formatted xml:\n" + formattedXml);

    return formattedXml;
}

From source file:com.panet.imeta.job.entries.xslt.JobEntryXSLT.java

public Result execute(Result previousResult, int nr, Repository rep, Job parentJob) {
    LogWriter log = LogWriter.getInstance();
    Result result = previousResult;
    result.setResult(false);//  w w  w.jav a 2  s. c  o m

    String realxmlfilename = getRealxmlfilename();
    String realxslfilename = getRealxslfilename();
    String realoutputfilename = getRealoutputfilename();

    FileObject xmlfile = null;
    FileObject xslfile = null;
    FileObject outputfile = null;

    try

    {

        if (xmlfilename != null && xslfilename != null && outputfilename != null) {
            xmlfile = KettleVFS.getFileObject(realxmlfilename);
            xslfile = KettleVFS.getFileObject(realxslfilename);
            outputfile = KettleVFS.getFileObject(realoutputfilename);

            if (xmlfile.exists() && xslfile.exists()) {
                if (outputfile.exists() && iffileexists == 2) {
                    //Output file exists
                    // User want to fail
                    log.logError(toString(), Messages.getString("JobEntryXSLT.OuputFileExists1.Label")
                            + realoutputfilename + Messages.getString("JobEntryXSLT.OuputFileExists2.Label"));
                    result.setResult(false);
                    result.setNrErrors(1);
                }

                else if (outputfile.exists() && iffileexists == 1) {
                    // Do nothing
                    if (log.isDebug())
                        log.logDebug(toString(),
                                Messages.getString("JobEntryXSLT.OuputFileExists1.Label") + realoutputfilename
                                        + Messages.getString("JobEntryXSLT.OuputFileExists2.Label"));
                    result.setResult(true);
                } else {
                    if (outputfile.exists() && iffileexists == 0) {
                        // the output file exists and user want to create new one with unique name
                        //Format Date

                        // Try to clean filename (without wildcard)
                        String wildcard = realoutputfilename.substring(realoutputfilename.length() - 4,
                                realoutputfilename.length());
                        if (wildcard.substring(0, 1).equals(".")) {
                            // Find wildcard
                            realoutputfilename = realoutputfilename.substring(0,
                                    realoutputfilename.length() - 4) + "_"
                                    + StringUtil.getFormattedDateTimeNow(true) + wildcard;
                        } else {
                            // did not find wildcard
                            realoutputfilename = realoutputfilename + "_"
                                    + StringUtil.getFormattedDateTimeNow(true);
                        }
                        if (log.isDebug())
                            log.logDebug(toString(),
                                    Messages.getString("JobEntryXSLT.OuputFileExists1.Label")
                                            + realoutputfilename
                                            + Messages.getString("JobEntryXSLT.OuputFileExists2.Label"));
                        log.logDebug(toString(),
                                Messages.getString("JobEntryXSLT.OuputFileNameChange1.Label")
                                        + realoutputfilename
                                        + Messages.getString("JobEntryXSLT.OuputFileNameChange2.Label"));
                    }

                    // Create transformer factory
                    TransformerFactory factory = TransformerFactory.newInstance();

                    if (xsltfactory.equals(FACTORY_SAXON)) {
                        // Set the TransformerFactory to the SAXON implementation.
                        factory = new net.sf.saxon.TransformerFactoryImpl();
                    }

                    if (log.isDetailed())
                        log.logDetailed(Messages.getString("JobEntryXSL.Log.TransformerFactoryInfos"), Messages
                                .getString("JobEntryXSL.Log.TransformerFactory", factory.getClass().getName()));

                    // Use the factory to create a template containing the xsl file
                    Templates template = factory
                            .newTemplates(new StreamSource(KettleVFS.getInputStream(xslfile)));

                    // Use the template to create a transformer
                    Transformer xformer = template.newTransformer();

                    if (log.isDetailed())
                        log.logDetailed(Messages.getString("JobEntryXSL.Log.TransformerClassInfos"), Messages
                                .getString("JobEntryXSL.Log.TransformerClass", xformer.getClass().getName()));

                    // Prepare the input and output files
                    Source source = new StreamSource(KettleVFS.getInputStream(xmlfile));
                    StreamResult resultat = new StreamResult(KettleVFS.getOutputStream(outputfile, false));

                    // Apply the xsl file to the source file and write the result to the output file
                    xformer.transform(source, resultat);

                    if (isAddFileToResult()) {
                        // Add output filename to output files
                        ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL,
                                KettleVFS.getFileObject(realoutputfilename), parentJob.getJobname(),
                                toString());
                        result.getResultFiles().put(resultFile.getFile().toString(), resultFile);
                    }

                    // Everything is OK
                    result.setResult(true);
                }
            } else {

                if (!xmlfile.exists()) {
                    log.logError(toString(), Messages.getString("JobEntryXSLT.FileDoesNotExist1.Label")
                            + realxmlfilename + Messages.getString("JobEntryXSLT.FileDoesNotExist2.Label"));
                }
                if (!xslfile.exists()) {
                    log.logError(toString(), Messages.getString("JobEntryXSLT.FileDoesNotExist1.Label")
                            + realxslfilename + Messages.getString("JobEntryXSLT.FileDoesNotExist2.Label"));
                }
                result.setResult(false);
                result.setNrErrors(1);
            }

        } else {
            log.logError(toString(), Messages.getString("JobEntryXSLT.AllFilesNotNull.Label"));
            result.setResult(false);
            result.setNrErrors(1);
        }
    } catch (Exception e) {
        log.logError(toString(),
                Messages.getString("JobEntryXSLT.ErrorXLST.Label")
                        + Messages.getString("JobEntryXSLT.ErrorXLSTXML1.Label") + realxmlfilename
                        + Messages.getString("JobEntryXSLT.ErrorXLSTXML2.Label")
                        + Messages.getString("JobEntryXSLT.ErrorXLSTXSL1.Label") + realxslfilename
                        + Messages.getString("JobEntryXSLT.ErrorXLSTXSL2.Label") + e.getMessage());
        result.setResult(false);
        result.setNrErrors(1);
    } finally {
        try {
            if (xmlfile != null)
                xmlfile.close();

            if (xslfile != null)
                xslfile.close();
            if (outputfile != null)
                outputfile.close();

            // file object is not properly garbaged collected and thus the file cannot
            // be deleted anymore. This is a known problem in the JVM.

            System.gc();
        } catch (IOException e) {
        }
    }

    return result;
}

From source file:org.apache.xalan.test.TransformWithExtensionTest.java

/**
 * Test transform xml document.//from   w ww  .j  a  v  a2 s.c  o m
 * 
 * @throws Exception
 *           the exception
 */
@SuppressWarnings("unchecked")
public final void testTransformWithExtension() throws Exception {
    final TransformerFactory tFactory = TransformerFactory.newInstance();
    assertTrue(tFactory instanceof org.apache.xalan.processor.TransformerFactoryImpl);

    final Transformer transformer = tFactory.newTransformer(
            new StreamSource(TransformWithExtensionTest.class.getResourceAsStream(FOO_XSL_FILE_NAME)));
    assertTrue(transformer instanceof org.apache.xalan.transformer.TransformerImpl);

    // its not required - only for testing that ext class was loaded!
    final ClassLoader classLoader = transformer.getClass().getClassLoader();
    final Class clazz = classLoader.loadClass("org.apache.xalan.test.ExtensionSample");
    assertNotNull(clazz);

    final ByteArrayOutputStream fooOutOS = new ByteArrayOutputStream();
    final Source source = new StreamSource(
            TransformWithExtensionTest.class.getResourceAsStream(FOO_XML_FILE_NAME));
    final Result result = new StreamResult(fooOutOS);
    transformer.transform(source, result);

    final String resultStr = fooOutOS.toString();
    _log.info("result=" + resultStr);

    final InputStream origFooOutIS = TransformWithExtensionTest.class.getResourceAsStream(FOO_OUT_FILE);
    final StringBuffer origFooOutContent = new StringBuffer();
    final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(origFooOutIS));
    String line = null;
    while ((line = bufferedReader.readLine()) != null) {
        origFooOutContent.append(line);
    }
    assertEquals(origFooOutContent.toString(), resultStr);
}

From source file:org.docx4j.XmlUtils.java

/**
 * //w w w .  ja va2 s  .  c  o m
 * Transform an input document using XSLT
 * 
 * @param doc
 * @param xslt
 * @param transformParameters
 * @param result
 * @throws Docx4JException In case serious transformation errors occur
 */
public static void transform(javax.xml.transform.Source source, javax.xml.transform.Templates template,
        Map<String, Object> transformParameters, javax.xml.transform.Result result) throws Docx4JException {

    if (source == null) {
        Throwable t = new Throwable();
        throw new Docx4JException("Null Source doc", t);
    }

    // Use the template to create a transformer
    // A Transformer may not be used in multiple threads running concurrently. 
    // Different Transformers may be used concurrently by different threads.
    // A Transformer may be used multiple times. Parameters and output properties 
    // are preserved across transformations.      
    javax.xml.transform.Transformer xformer;
    try {
        xformer = template.newTransformer();
    } catch (TransformerConfigurationException e) {
        throw new Docx4JException("The Transformer is ill-configured", e);
    }

    log.info("Using " + xformer.getClass().getName());

    if (xformer.getClass().getName().equals("org.apache.xalan.transformer.TransformerImpl")) {

        if (Docx4jProperties.getProperty("docx4j.xalan.XALANJ-2419.workaround", false)) {
            // Use our patched serializer, which fixes Unicode astral character
            // issue. See https://issues.apache.org/jira/browse/XALANJ-2419

            log.info("Working around https://issues.apache.org/jira/browse/XALANJ-2419");

            Properties p = xformer.getOutputProperties();
            String method = p.getProperty("method");
            System.out.println("method: " + method);
            if (method == null || method.equals("xml")) {

                ((org.apache.xalan.transformer.TransformerImpl) xformer).setOutputProperty(
                        S_KEY_CONTENT_HANDLER, "org.docx4j.org.apache.xml.serializer.ToXMLStream");

            } else if (method.equals("html")) {

                ((org.apache.xalan.transformer.TransformerImpl) xformer).setOutputProperty(
                        S_KEY_CONTENT_HANDLER, "org.docx4j.org.apache.xml.serializer.ToHTMLStream");

            } else if (method.equals("text")) {

                ((org.apache.xalan.transformer.TransformerImpl) xformer).setOutputProperty(
                        S_KEY_CONTENT_HANDLER, "org.docx4j.org.apache.xml.serializer.ToTextStream");

            } else {

                log.warn("fallback for method: " + method);
                ((org.apache.xalan.transformer.TransformerImpl) xformer).setOutputProperty(
                        S_KEY_CONTENT_HANDLER, "org.docx4j.org.apache.xml.serializer.ToUnknownStream");

            }

            /* That wasn't quite enough:
             * 
               at org.docx4j.org.apache.xml.serializer.ToXMLStream.startDocumentInternal(ToXMLStream.java:143)
               at org.docx4j.org.apache.xml.serializer.SerializerBase.startDocument(SerializerBase.java:1190)
               at org.apache.xml.serializer.ToSAXHandler.startDocumentInternal(ToSAXHandler.java:97)
               at org.apache.xml.serializer.ToSAXHandler.flushPending(ToSAXHandler.java:273)
               at org.apache.xml.serializer.ToXMLSAXHandler.startPrefixMapping(ToXMLSAXHandler.java:350)
               at org.apache.xml.serializer.ToXMLSAXHandler.startPrefixMapping(ToXMLSAXHandler.java:320)
               at org.apache.xalan.templates.ElemLiteralResult.execute(ElemLiteralResult.java:1317)
             *
             * (TransformerImpl's createSerializationHandler makes a new org.apache.xml.serializer.ToXMLSAXHandler.ToXMLSAXHandler
             * and that's hard coded.)
             * 
             * But it seems to be enough now...
                        
             */
        }

    } else {

        log.error("Detected " + xformer.getClass().getName()
                + ", but require org.apache.xalan.transformer.TransformerImpl. "
                + "Ensure Xalan 2.7.x is on your classpath!");
    }
    LoggingErrorListener errorListener = new LoggingErrorListener(false);
    xformer.setErrorListener(errorListener);

    if (transformParameters != null) {
        Iterator parameterIterator = transformParameters.entrySet().iterator();
        while (parameterIterator.hasNext()) {
            Map.Entry pairs = (Map.Entry) parameterIterator.next();

            if (pairs.getKey() == null) {
                log.info("Skipped null key");
                // pairs = (Map.Entry)parameterIterator.next();
                continue;
            }

            if (pairs.getKey().equals("customXsltTemplates"))
                continue;

            if (pairs.getValue() == null) {
                log.warn("parameter '" + pairs.getKey() + "' was null.");
            } else {
                xformer.setParameter((String) pairs.getKey(), pairs.getValue());
            }
        }
    }

    /* SUPER DEBUGGING
    // http://xml.apache.org/xalan-j/usagepatterns.html#debugging
    // debugging
    // Set up a PrintTraceListener object to print to a file.
    java.io.FileWriter fw = new java.io.FileWriter("/tmp/xslt-events" + xsltCount++ + ".log");
    java.io.PrintWriter pw = new java.io.PrintWriter(fw);
    PrintTraceListener ptl = new PrintTraceListener(pw);
            
    // Print information as each node is 'executed' in the stylesheet.
    ptl.m_traceElements = true;
    // Print information after each result-tree generation event.
    ptl.m_traceGeneration = true;
    // Print information after each selection event.
    ptl.m_traceSelection = true;
    // Print information whenever a template is invoked.
    ptl.m_traceTemplates = true;
    // Print information whenever an extension is called.
    ptl.m_traceExtension = true;
    TransformerImpl transformerImpl = (TransformerImpl)xformer;
            
      // Register the TraceListener with the TraceManager associated
      // with the TransformerImpl.
      TraceManager trMgr = transformerImpl.getTraceManager();
      trMgr.addTraceListener(ptl);
            
    */
    // DEBUGGING
    // use the identity transform if you want to send wordDocument;
    // otherwise you'll get the XHTML
    // javax.xml.transform.Transformer xformer = tfactory.newTransformer();
    try {
        xformer.transform(source, result);
    } catch (TransformerException e) {
        throw new Docx4JException("Cannot perform the transformation", e);
    } finally {
        //pw.flush();
    }

}

From source file:org.pentaho.di.job.entries.xslt.JobEntryXSLT.java

private boolean processOneXMLFile(String xmlfilename, String xslfilename, String outputfilename, Result result,
        Job parentJob) {/*from w  w w .ja v a 2s  .c om*/
    boolean retval = false;
    FileObject xmlfile = null;
    FileObject xslfile = null;
    FileObject outputfile = null;

    try {
        xmlfile = KettleVFS.getFileObject(xmlfilename, this);
        xslfile = KettleVFS.getFileObject(xslfilename, this);
        outputfile = KettleVFS.getFileObject(outputfilename, this);

        if (xmlfile.exists() && xslfile.exists()) {
            if (outputfile.exists() && iffileexists == 2) {
                // Output file exists
                // User want to fail
                logError(BaseMessages.getString(PKG, "JobEntryXSLT.OuputFileExists1.Label") + outputfilename
                        + BaseMessages.getString(PKG, "JobEntryXSLT.OuputFileExists2.Label"));
                return retval;

            } else if (outputfile.exists() && iffileexists == 1) {
                // Do nothing
                if (log.isDebug()) {
                    logDebug(BaseMessages.getString(PKG, "JobEntryXSLT.OuputFileExists1.Label") + outputfilename
                            + BaseMessages.getString(PKG, "JobEntryXSLT.OuputFileExists2.Label"));
                }
                retval = true;
                return retval;

            } else {
                if (outputfile.exists() && iffileexists == 0) {
                    // the output file exists and user want to create new one with unique name
                    // Format Date

                    // Try to clean filename (without wildcard)
                    String wildcard = outputfilename.substring(outputfilename.length() - 4,
                            outputfilename.length());
                    if (wildcard.substring(0, 1).equals(".")) {
                        // Find wildcard
                        outputfilename = outputfilename.substring(0, outputfilename.length() - 4) + "_"
                                + StringUtil.getFormattedDateTimeNow(true) + wildcard;
                    } else {
                        // did not find wildcard
                        outputfilename = outputfilename + "_" + StringUtil.getFormattedDateTimeNow(true);
                    }
                    if (log.isDebug()) {
                        logDebug(BaseMessages.getString(PKG, "JobEntryXSLT.OuputFileExists1.Label")
                                + outputfilename
                                + BaseMessages.getString(PKG, "JobEntryXSLT.OuputFileExists2.Label"));
                        logDebug(BaseMessages.getString(PKG, "JobEntryXSLT.OuputFileNameChange1.Label")
                                + outputfilename
                                + BaseMessages.getString(PKG, "JobEntryXSLT.OuputFileNameChange2.Label"));
                    }
                }

                // Create transformer factory
                TransformerFactory factory = TransformerFactory.newInstance();

                if (xsltfactory.equals(FACTORY_SAXON)) {
                    // Set the TransformerFactory to the SAXON implementation.
                    factory = new net.sf.saxon.TransformerFactoryImpl();
                }

                if (log.isDetailed()) {
                    log.logDetailed(BaseMessages.getString(PKG, "JobEntryXSL.Log.TransformerFactoryInfos"),
                            BaseMessages.getString(PKG, "JobEntryXSL.Log.TransformerFactory",
                                    factory.getClass().getName()));
                }

                InputStream xslInputStream = KettleVFS.getInputStream(xslfile);
                InputStream xmlInputStream = KettleVFS.getInputStream(xmlfile);
                OutputStream os = null;
                try {
                    // Use the factory to create a template containing the xsl file
                    Templates template = factory.newTemplates(new StreamSource(xslInputStream));

                    // Use the template to create a transformer
                    Transformer xformer = template.newTransformer();

                    if (log.isDetailed()) {
                        log.logDetailed(BaseMessages.getString(PKG, "JobEntryXSL.Log.TransformerClassInfos"),
                                BaseMessages.getString(PKG, "JobEntryXSL.Log.TransformerClass",
                                        xformer.getClass().getName()));
                    }

                    // Do we need to set output properties?
                    if (setOutputProperties) {
                        xformer.setOutputProperties(outputProperties);
                    }

                    // Do we need to pass parameters?
                    if (useParameters) {
                        for (int i = 0; i < nrParams; i++) {
                            xformer.setParameter(nameOfParams[i], valueOfParams[i]);
                        }
                    }

                    // Prepare the input and output files
                    Source source = new StreamSource(xmlInputStream);
                    os = KettleVFS.getOutputStream(outputfile, false);
                    StreamResult resultat = new StreamResult(os);

                    // Apply the xsl file to the source file and write the result to the output file
                    xformer.transform(source, resultat);

                    if (isAddFileToResult()) {
                        // Add output filename to output files
                        ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL,
                                KettleVFS.getFileObject(outputfilename, this), parentJob.getJobname(),
                                toString());
                        result.getResultFiles().put(resultFile.getFile().toString(), resultFile);
                    }

                    // Everything is OK
                    retval = true;
                } finally {
                    try {
                        xslInputStream.close();
                    } catch (IOException ignored) {
                        // ignore IO Exception on close
                    }
                    try {
                        xmlInputStream.close();
                    } catch (IOException ignored) {
                        // ignore IO Exception on close
                    }
                    try {
                        if (os != null) {
                            os.close();
                        }
                    } catch (IOException ignored) {
                        // ignore IO Exception on close
                    }
                }
            }
        } else {

            if (!xmlfile.exists()) {
                logError(BaseMessages.getString(PKG, "JobEntryXSLT.FileDoesNotExist1.Label") + xmlfilename
                        + BaseMessages.getString(PKG, "JobEntryXSLT.FileDoesNotExist2.Label"));
            }
            if (!xslfile.exists()) {
                logError(BaseMessages.getString(PKG, "JobEntryXSLT.FileDoesNotExist1.Label") + xmlfilename
                        + BaseMessages.getString(PKG, "JobEntryXSLT.FileDoesNotExist2.Label"));
            }
        }
    } catch (Exception e) {
        logError(BaseMessages.getString(PKG, "JobEntryXSLT.ErrorXLST.Label")
                + BaseMessages.getString(PKG, "JobEntryXSLT.ErrorXLSTXML1.Label") + xmlfilename
                + BaseMessages.getString(PKG, "JobEntryXSLT.ErrorXLSTXML2.Label")
                + BaseMessages.getString(PKG, "JobEntryXSLT.ErrorXLSTXSL1.Label") + xslfilename
                + BaseMessages.getString(PKG, "JobEntryXSLT.ErrorXLSTXSL2.Label") + e.getMessage());
    } finally {
        try {
            if (xmlfile != null) {
                xmlfile.close();
            }

            if (xslfile != null) {
                xslfile.close();
            }
            if (outputfile != null) {
                outputfile.close();
            }
        } catch (IOException e) {
            logError("Unable to close file", e);
        }
    }

    return retval;
}