List of usage examples for javax.xml.transform TransformerFactory newTemplates
public abstract Templates newTemplates(Source source) throws TransformerConfigurationException;
From source file:org.fcrepo.localservices.saxon.SaxonServlet.java
/** * Maintain prepared stylesheets in memory for reuse *//* w w w .j a v a2 s .c o m*/ private Templates tryCache(String url) throws Exception { Templates x = (Templates) m_cache.get(url); if (x == null) { synchronized (m_cache) { if (!m_cache.containsKey(url)) { TransformerFactory factory = TransformerFactory.newInstance(); if (factory.getClass().getName().equals("net.sf.saxon.TransformerFactoryImpl")) { factory.setAttribute(FeatureKeys.VERSION_WARNING, Boolean.FALSE); } StreamSource ss = new StreamSource(getInputStream(url)); ss.setSystemId(url); x = factory.newTemplates(ss); m_cache.put(url, x); } } } return x; }
From source file:edu.unc.lib.dl.schematron.SchematronValidator.java
/** * Use this to initialize the configured schemas. Generate stylesheet * implementations of ISO Schematron files and preload them into Transformer * Templates for quick use./* w ww . j a v a 2s . co m*/ */ public void loadSchemas() { templates = new HashMap<String, Templates>(); // Load up a transformer and the ISO Schematron to XSL templates. Templates isoSVRLTemplates = null; ClassPathResource svrlRes = new ClassPathResource("/edu/unc/lib/dl/schematron/iso_svrl.xsl", SchematronValidator.class); Source svrlrc; try { svrlrc = new StreamSource(svrlRes.getInputStream()); } catch (IOException e1) { throw new Error("Cannot load iso_svrl.xsl", e1); } TransformerFactory factory = null; try { factory = new TransformerFactoryImpl(); // enable relative classpath-based URIs factory.setURIResolver(new URIResolver() { public Source resolve(String href, String base) throws TransformerException { ClassPathResource svrlRes = new ClassPathResource(href, SchematronValidator.class); Source result; try { result = new StreamSource(svrlRes.getInputStream()); } catch (IOException e1) { throw new TransformerException("Cannot resolve " + href, e1); } return result; } }); isoSVRLTemplates = factory.newTemplates(svrlrc); } catch (TransformerFactoryConfigurationError e) { log.error("Error setting up transformer factory.", e); throw new Error("Error setting up transformer factory", e); } catch (TransformerConfigurationException e) { log.error("Error setting up transformer.", e); throw new Error("Error setting up transformer", e); } // Get a transformer Transformer t = null; try { t = isoSVRLTemplates.newTransformer(); } catch (TransformerConfigurationException e) { throw new Error("There was a problem configuring the transformer.", e); } for (String schema : schemas.keySet()) { // make XSLT out of Schematron for each schema Resource resource = schemas.get(schema); Source schematron = null; try { schematron = new StreamSource(resource.getInputStream()); } catch (IOException e) { throw new Error("Cannot load resource for schema \"" + schema + "\" at " + resource.getDescription() + resource.toString()); } JDOMResult res = new JDOMResult(); try { t.transform(schematron, res); } catch (TransformerException e) { throw new Error("Schematron issue: There were problems transforming Schematron to XSL.", e); } // compile templates object for each profile try { Templates schemaTemplates = factory.newTemplates(new JDOMSource(res.getDocument())); templates.put(schema, schemaTemplates); } catch (TransformerConfigurationException e) { throw new Error("There was a problem configuring the transformer.", e); } } }
From source file:edu.unc.lib.dl.ingest.sip.METSPackageSIPProcessor.java
public METSPackageSIPProcessor() { try {/* w ww. j a v a 2s . c om*/ _countObjectsXpath = XPath.newInstance(countObjectsXpath); _countObjectsXpath.addNamespace(METS_NS); } catch (JDOMException e) { log.error("Bad Configuration for Mets2FoxmlFilter", e); throw new IllegalArgumentException("Bad Configuration for Mets2FoxmlFilter", e); } Source mets2foxsrc = new StreamSource( METSPackageSIPProcessor.class.getResourceAsStream(stylesheetPackage + "base-model.xsl")); // requires a Saxon 8 transformer factory try { TransformerFactory factory = TransformerFactory.newInstance(); // set a Resolver that can look in the classpath factory.setURIResolver(new URIResolver() { public Source resolve(String href, String base) throws TransformerException { Source result = null; if (href.startsWith("/")) result = new StreamSource(METSPackageSIPProcessor.class.getResourceAsStream(href)); else result = new StreamSource( METSPackageSIPProcessor.class.getResourceAsStream(stylesheetPackage + href)); return result; } }); mets2fox = factory.newTemplates(mets2foxsrc); } catch (TransformerFactoryConfigurationError e) { log.error("Error setting up transformer factory.", e); throw new Error("Error setting up transformer factory", e); } catch (TransformerConfigurationException e) { log.error("Error setting up transformer.", e); throw new Error("Error setting up transformer", e); } }
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);//from w w w .j a v a 2s. 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.ambraproject.article.service.XslIngestArchiveProcessor.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. *///from w ww .j a va 2 s. co m private Transformer getTranslet(Document doc) throws TransformerException, URISyntaxException { final TransformerFactory tFactory = TransformerFactory.newInstance(); // key is "" if the Attribute does not exist InputStream templateStream; String key = doc.getDocumentElement().getAttribute("dtd-version").trim(); if ((doc == null) || (!xslTemplateMap.containsKey(key)) || (key.equalsIgnoreCase(""))) { templateStream = xslDefaultTemplate; } else { String templateName = xslTemplateMap.get(key); templateStream = getAsStream(templateName); } Templates translet = tFactory.newTemplates(new StreamSource(templateStream)); return translet.newTransformer(); }
From source file:org.sakaiproject.sitestats.impl.report.ReportManagerImpl.java
public byte[] getReportAsPDF(Report report) { ByteArrayOutputStream out = null; try {/*from w w w.j ava 2 s .c om*/ // Setup a buffer to obtain the content length out = new ByteArrayOutputStream(); fopFactory.setURIResolver(new LibraryURIResolver()); FOUserAgent foUserAgent = fopFactory.newFOUserAgent(); // Construct fop with desired output format Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out); // Setup XSLT if (cachedXmlFoXSLT == null) { ClassPathResource xsltCPR = new ClassPathResource( "org/sakaiproject/sitestats/config/fop/" + XML_FO_XSL_FILE); InputStream xslt = xsltCPR.getInputStream(); TransformerFactory factory = TransformerFactory.newInstance(); cachedXmlFoXSLT = factory.newTemplates(new StreamSource(xslt)); } Transformer transformer = cachedXmlFoXSLT.newTransformer(); // Setup input for XSLT transformation Source src = new SAXSource(new ReportXMLReader(), new ReportInputSource(report)); // Resulting SAX events (the generated FO) must be piped through to FOP Result res = new SAXResult(fop.getDefaultHandler()); // Start XSLT transformation and FOP processing transformer.transform(src, res); } catch (TransformerConfigurationException e) { LOG.error("TransformerConfigurationException while writing SiteStats PDF report", e); } catch (FOPException e) { LOG.error("FOPException while writing SiteStats PDF report", e); } catch (TransformerException e) { LOG.error("TransformerException while writing SiteStats PDF report", e); } catch (Exception e) { LOG.error("Exception while generating SiteStats PDF report", e); } finally { try { if (out != null) { out.close(); return out.toByteArray(); } } catch (IOException e) { LOG.error("IOException while writing SiteStats PDF report", e); } } return null; }
From source file:org.sakaiproject.reports.logic.impl.ReportsManagerImpl.java
protected Templates createTemplate(String transformPath) throws MalformedURLException, TransformerConfigurationException { InputStream stream = getClass().getResourceAsStream(transformPath); URL url = getClass().getResource(transformPath); String urlPath = url.toString(); String systemId = urlPath.substring(0, urlPath.lastIndexOf('/') + 1); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Templates templates = transformerFactory.newTemplates(new StreamSource(stream, systemId)); return templates; }
From source file:net.wastl.webmail.storage.FileStorage.java
/** * Return the requested Stylesheet, precompiled and fitting to the locale and theme *//*from w w w . jav a 2 s . c o m*/ public Templates getStylesheet(String name, Locale locale, String theme) throws WebMailException { String key = locale.getLanguage() + "/" + theme; AttributedExpireableCache cache = stylesheet_cache.get(key); if (cache == null) { cache = new AttributedExpireableCache(file_cache_size); stylesheet_cache.put(key, cache); } Templates stylesheet = null; String basepath = getBasePath(locale, theme); File f = new File(basepath + name); if (!f.exists()) { throw new StylesheetNotFoundException( "The requested stylesheet " + name + " could not be found (path tried: " + basepath + "."); } if (cache.get(name) != null && ((Long) cache.getAttributes(name)).longValue() >= f.lastModified()) { // Keep statistics :-) cache.hit(); return (Templates) cache.get(name); } else { try { StreamSource msg_xsl = new StreamSource("file://" + basepath + name); TransformerFactory factory = TransformerFactory.newInstance(); stylesheet = factory.newTemplates(msg_xsl); cache.put(name, stylesheet, new Long(f.lastModified())); cache.miss(); } catch (Exception ex) { //log.error("Error while compiling stylesheet "+name+", language="+locale.getLanguage()+", theme="+theme+"."); throw new WebMailException("Error while compiling stylesheet " + name + ", language=" + locale.getLanguage() + ", theme=" + theme + ":\n" + ex.toString()); } return stylesheet; } }
From source file:nl.clockwork.mule.common.transformer.AbstractXSLTransformer.java
public void setXslFile(String xslFile) { try {/*from www.j a v a 2 s. co m*/ TransformerFactory factory = TransformerFactory.newInstance(); templates = factory.newTemplates(new StreamSource(this.getClass().getResourceAsStream(xslFile))); } catch (TransformerConfigurationException e) { logger.fatal("Error creating transformer using file: " + xslFile, e); throw new RuntimeException(e); } }