Java Code Examples for javax.xml.transform.TransformerFactory#newTemplates()
The following examples show how to use
javax.xml.transform.TransformerFactory#newTemplates() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: XMLTransformerFactory.java From ph-commons with Apache License 2.0 | 6 votes |
/** * Create a new XSLT Template for the passed resource. * * @param aTransformerFactory * The transformer factory to be used. May not be <code>null</code>. * @param aSource * The resource to be templated. May not be <code>null</code>. * @return <code>null</code> if something goes wrong */ @Nullable public static Templates newTemplates (@Nonnull final TransformerFactory aTransformerFactory, @Nonnull final Source aSource) { ValueEnforcer.notNull (aTransformerFactory, "TransformerFactory"); ValueEnforcer.notNull (aSource, "Source"); try { return aTransformerFactory.newTemplates (aSource); } catch (final TransformerConfigurationException ex) { LOGGER.error ("Failed to parse " + aSource, ex); return null; } }
Example 2
Source File: StylesheetManager.java From symja_android_library with GNU General Public License v3.0 | 6 votes |
/** * Helper to create "driver" XSLT stylesheets that import the stylesheets at the given URIs, * using the given {@link TransformerFactory}. * * @param transformerFactory * @param importUris */ private Templates compileImporterStylesheet(final TransformerFactory transformerFactory, boolean requireXSLT20, final String... importUris) { /* Build up driver XSLT that simply imports the required stylesheets */ StringBuilder xsltBuilder = new StringBuilder("<stylesheet version='") .append(requireXSLT20 ? "2.0" : "1.0") .append("' xmlns='http://www.w3.org/1999/XSL/Transform'>\n"); for (String importUri : importUris) { xsltBuilder.append("<import href='").append(importUri).append("'/>\n"); } xsltBuilder.append("</stylesheet>"); String xslt = xsltBuilder.toString(); /* Now compile and return result */ try { return transformerFactory.newTemplates(new StreamSource(new StringReader(xslt))); } catch (TransformerConfigurationException e) { throw new SnuggleRuntimeException("Could not compile stylesheet driver " + xslt, e); } }
Example 3
Source File: NamespacePrefixTest.java From jdk8u-jdk with GNU General Public License v2.0 | 6 votes |
@Test public void testConcurrentTransformations() throws Exception { final TransformerFactory tf = TransformerFactory.newInstance(); final Source xslsrc = new StreamSource(new StringReader(XSL)); final Templates tmpl = tf.newTemplates(xslsrc); concurrentTestPassed.set(true); // Execute multiple TestWorker tasks for (int id = 0; id < THREADS_COUNT; id++) { EXECUTOR.execute(new TransformerThread(tmpl.newTransformer(), id)); } // Initiate shutdown of previously submitted task EXECUTOR.shutdown(); // Wait for termination of submitted tasks if (!EXECUTOR.awaitTermination(THREADS_COUNT, TimeUnit.SECONDS)) { // If not all tasks terminates during the time out force them to shutdown EXECUTOR.shutdownNow(); } // Check if all transformation threads generated the correct namespace prefix assertTrue(concurrentTestPassed.get()); }
Example 4
Source File: NamespacePrefixTest.java From jdk8u_jdk with GNU General Public License v2.0 | 6 votes |
@Test public void testConcurrentTransformations() throws Exception { final TransformerFactory tf = TransformerFactory.newInstance(); final Source xslsrc = new StreamSource(new StringReader(XSL)); final Templates tmpl = tf.newTemplates(xslsrc); concurrentTestPassed.set(true); // Execute multiple TestWorker tasks for (int id = 0; id < THREADS_COUNT; id++) { EXECUTOR.execute(new TransformerThread(tmpl.newTransformer(), id)); } // Initiate shutdown of previously submitted task EXECUTOR.shutdown(); // Wait for termination of submitted tasks if (!EXECUTOR.awaitTermination(THREADS_COUNT, TimeUnit.SECONDS)) { // If not all tasks terminates during the time out force them to shutdown EXECUTOR.shutdownNow(); } // Check if all transformation threads generated the correct namespace prefix assertTrue(concurrentTestPassed.get()); }
Example 5
Source File: XPathNegativeZero.java From jdk8u-jdk with GNU General Public License v2.0 | 5 votes |
private static String xform(final String xml, final String xsl) throws Exception { final TransformerFactory tf = TransformerFactory.newInstance(); final Source xslsrc = new StreamSource(new File(xsl)); final Templates tmpl = tf.newTemplates(xslsrc); final Transformer t = tmpl.newTransformer(); StringWriter writer = new StringWriter(); final Source src = new StreamSource(new File(xml)); final Result res = new StreamResult(writer); t.transform(src, res); return writer.toString(); }
Example 6
Source File: BuildTutorial.java From itext2 with GNU Lesser General Public License v3.0 | 5 votes |
/** * Converts an <code>infile</code>, using an <code>xslfile</code> to an * <code>outfile</code>. * * @param infile * the path to an XML file * @param xslfile * the path to the XSL file * @param outfile * the path for the output file */ public static void convert(File infile, File xslfile, File outfile) { try { // Create transformer factory TransformerFactory factory = TransformerFactory.newInstance(); // Use the factory to create a template containing the xsl file Templates template = factory.newTemplates(new StreamSource( new FileInputStream(xslfile))); // Use the template to create a transformer Transformer xformer = template.newTransformer(); // passing 2 parameters String branch = outfile.getParentFile().getCanonicalPath().substring(root.length()); branch = branch.replace(File.separatorChar, '/'); StringBuffer path = new StringBuffer(); for (int i = 0; i < branch.length(); i++) { if (branch.charAt(i) == '/') path.append("/.."); } xformer.setParameter("branch", branch); xformer.setParameter("root", path.toString()); // Prepare the input and output files Source source = new StreamSource(new FileInputStream(infile)); Result result = new StreamResult(new FileOutputStream(outfile)); // Apply the xsl file to the source file and write the result to the // output file xformer.transform(source, result); } catch (Exception e) { e.printStackTrace(); } }
Example 7
Source File: XPathNegativeZero.java From openjdk-8-source with GNU General Public License v2.0 | 5 votes |
private static String xform(final String xml, final String xsl) throws Exception { final TransformerFactory tf = TransformerFactory.newInstance(); final Source xslsrc = new StreamSource(new File(xsl)); final Templates tmpl = tf.newTemplates(xslsrc); final Transformer t = tmpl.newTransformer(); StringWriter writer = new StringWriter(); final Source src = new StreamSource(new File(xml)); final Result res = new StreamResult(writer); t.transform(src, res); return writer.toString(); }
Example 8
Source File: Transformers.java From proarc with GNU General Public License v3.0 | 5 votes |
private static Templates createTemplates(Format recordFormat) throws TransformerException { TransformerFactory factory = TransformerFactory.newInstance(); // factory.setAttribute("debug", true); SimpleResolver resolver = new SimpleResolver(); factory.setURIResolver(resolver); Templates templates = factory.newTemplates(getXsl(recordFormat, resolver)); return templates; }
Example 9
Source File: XPathNegativeZero.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 5 votes |
private static String xform(final String xml, final String xsl) throws Exception { final TransformerFactory tf = TransformerFactory.newInstance(); final Source xslsrc = new StreamSource(new File(xsl)); final Templates tmpl = tf.newTemplates(xslsrc); final Transformer t = tmpl.newTransformer(); StringWriter writer = new StringWriter(); final Source src = new StreamSource(new File(xml)); final Result res = new StreamResult(writer); t.transform(src, res); return writer.toString(); }
Example 10
Source File: XslSubstringTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
private String testTransform(String xsl) throws Exception { //Prepare sources for transormation Source src = new StreamSource(new StringReader(xml)); Source xslsrc = new StreamSource(new StringReader(xslPre + xsl + xslPost)); //Create factory, template and transformer TransformerFactory tf = TransformerFactory.newInstance(); Templates tmpl = tf.newTemplates(xslsrc); Transformer t = tmpl.newTransformer(); //Prepare output stream StringWriter xmlResultString = new StringWriter(); StreamResult xmlResultStream = new StreamResult(xmlResultString); //Transform t.transform(src, xmlResultStream); return xmlResultString.toString().trim(); }
Example 11
Source File: XMLUtil.java From developer-studio with Apache License 2.0 | 5 votes |
public static String prettify(OMElement wsdlElement) throws Exception { OutputStream out = new ByteArrayOutputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); wsdlElement.serialize(baos); 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)); return out.toString(); }
Example 12
Source File: Xml.java From Knowage-Server with GNU Affero General Public License v3.0 | 5 votes |
public static String xml2json(String xml) throws TransformerFactoryConfigurationError, TransformerException { String json = "{}"; if (xml != null && !"".equals(xml)) { // Fastest way to check if a big string is a JSONObject // don't do this at home... try { new JSONObject(xml); return xml; } catch (JSONException e) { } byte[] bytes = xml.getBytes(); InputStream inputStream = new ByteArrayInputStream(bytes); TransformerFactory factory = TransformerFactory.newInstance(); InputStream resourceAsStream = Thread.currentThread().getContextClassLoader() .getResourceAsStream("it/eng/spagobi/json/xml2Json.xslt"); StreamSource source = new StreamSource(resourceAsStream); Templates template = factory.newTemplates(source); Transformer transformer = template.newTransformer(); OutputStream os = new ByteArrayOutputStream(); transformer.transform(new StreamSource(inputStream), new StreamResult(os)); json = os.toString().replaceAll("\\p{Cntrl}", ""); } return json; }
Example 13
Source File: NamespacePrefixTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
@Test public void testReuseTemplates() throws Exception { final TransformerFactory tf = TransformerFactory.newInstance(); final Source xslsrc = new StreamSource(new StringReader(XSL)); final Templates tmpl = tf.newTemplates(xslsrc); for (int i = 0; i < TRANSF_COUNT; i++) { checkResult(doTransformation(tmpl.newTransformer())); } }
Example 14
Source File: XPathNegativeZero.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
private static String xform(final String xml, final String xsl) throws Exception { final TransformerFactory tf = TransformerFactory.newInstance(); final Source xslsrc = new StreamSource(new File(xsl)); final Templates tmpl = tf.newTemplates(xslsrc); final Transformer t = tmpl.newTransformer(); StringWriter writer = new StringWriter(); final Source src = new StreamSource(new File(xml)); final Result res = new StreamResult(writer); t.transform(src, res); return writer.toString(); }
Example 15
Source File: StyleServiceImpl.java From rice with Educational Community License v2.0 | 5 votes |
@Override public Templates getStyleAsTranslet(String name) throws TransformerConfigurationException { if (name == null) { return null; } Style style = getStyle(name); if (style == null) { return null; } boolean useXSLTC = CoreFrameworkServiceLocator.getParameterService().getParameterValueAsBoolean(KewApiConstants.KEW_NAMESPACE, KRADConstants.DetailTypes.EDOC_LITE_DETAIL_TYPE, KewApiConstants.EDL_USE_XSLTC_IND); if (useXSLTC) { LOG.info("using xsltc to compile stylesheet"); String key = "javax.xml.transform.TransformerFactory"; String value = "org.apache.xalan.xsltc.trax.TransformerFactoryImpl"; Properties props = System.getProperties(); props.put(key, value); System.setProperties(props); } TransformerFactory factory = TransformerFactory.newInstance(); factory.setURIResolver(new StyleUriResolver(this)); if (useXSLTC) { factory.setAttribute("translet-name",name); factory.setAttribute("generate-translet",Boolean.TRUE); String debugTransform = CoreFrameworkServiceLocator.getParameterService().getParameterValueAsString(KewApiConstants.KEW_NAMESPACE, KRADConstants.DetailTypes.EDOC_LITE_DETAIL_TYPE, KewApiConstants.EDL_DEBUG_TRANSFORM_IND); if (debugTransform.trim().equals("Y")) { factory.setAttribute("debug", Boolean.TRUE); } } return factory.newTemplates(new StreamSource(new StringReader(style.getXmlContent()))); }
Example 16
Source File: XslSubstringTest.java From jdk8u-jdk with GNU General Public License v2.0 | 5 votes |
private String testTransform(String xsl) throws Exception { //Prepare sources for transormation Source src = new StreamSource(new StringReader(xml)); Source xslsrc = new StreamSource(new StringReader(xslPre + xsl + xslPost)); //Create factory, template and transformer TransformerFactory tf = TransformerFactory.newInstance(); Templates tmpl = tf.newTemplates(xslsrc); Transformer t = tmpl.newTransformer(); //Prepare output stream StringWriter xmlResultString = new StringWriter(); StreamResult xmlResultStream = new StreamResult(xmlResultString); //Transform t.transform(src, xmlResultStream); return xmlResultString.toString().trim(); }
Example 17
Source File: XPathNegativeZero.java From hottub with GNU General Public License v2.0 | 5 votes |
private static String xform(final String xml, final String xsl) throws Exception { final TransformerFactory tf = TransformerFactory.newInstance(); final Source xslsrc = new StreamSource(new File(xsl)); final Templates tmpl = tf.newTemplates(xslsrc); final Transformer t = tmpl.newTransformer(); StringWriter writer = new StringWriter(); final Source src = new StreamSource(new File(xml)); final Result res = new StreamResult(writer); t.transform(src, res); return writer.toString(); }
Example 18
Source File: XslSubstringTest.java From dragonwell8_jdk with GNU General Public License v2.0 | 5 votes |
private String testTransform(String xsl) throws Exception { //Prepare sources for transormation Source src = new StreamSource(new StringReader(xml)); Source xslsrc = new StreamSource(new StringReader(xslPre + xsl + xslPost)); //Create factory, template and transformer TransformerFactory tf = TransformerFactory.newInstance(); Templates tmpl = tf.newTemplates(xslsrc); Transformer t = tmpl.newTransformer(); //Prepare output stream StringWriter xmlResultString = new StringWriter(); StreamResult xmlResultStream = new StreamResult(xmlResultString); //Transform t.transform(src, xmlResultStream); return xmlResultString.toString().trim(); }
Example 19
Source File: TransformerProvider.java From lucene-solr with Apache License 2.0 | 5 votes |
/** Return a Templates object for the given filename */ private Templates getTemplates(ResourceLoader loader, String filename,int cacheLifetimeSeconds) throws IOException { Templates result = null; 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); throw new IOException("Unable to initialize Templates '" + filename + "'", e); } lastFilename = filename; lastTemplates = result; cacheExpiresTimeout = new TimeOut(cacheLifetimeSeconds, TimeUnit.SECONDS, TimeSource.NANO_TIME); return result; }
Example 20
Source File: DiagnosticDataXmlDefiner.java From dss with GNU Lesser General Public License v2.1 | 4 votes |
private static Templates loadTemplates(String path) throws TransformerConfigurationException, IOException { try (InputStream is = DiagnosticDataXmlDefiner.class.getResourceAsStream(path)) { TransformerFactory transformerFactory = XmlDefinerUtils.getInstance().getSecureTransformerFactory(); return transformerFactory.newTemplates(new StreamSource(is)); } }