List of usage examples for javax.xml.transform Transformer setParameter
public abstract void setParameter(String name, Object value);
From source file:com.manydesigns.elements.pdf.TableFormPdfExporter.java
public void export(OutputStream outputStream) throws FOPException, IOException, TransformerException { FopFactory fopFactory = FopFactory.newInstance(); Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, outputStream); // Setup XSLT TransformerFactory Factory = TransformerFactory.newInstance(); Transformer transformer = Factory.newTransformer(xsltSource); // Set the value of a <param> in the stylesheet transformer.setParameter("versionParam", "2.0"); // Setup input for XSLT transformation Reader reader = composeXml(); Source src = new StreamSource(reader); // Resulting SAX events (the generated FO) must be piped through to // FOP// w w w . j a v a 2 s . c o m Result res = new SAXResult(fop.getDefaultHandler()); // Start XSLT transformation and FOP processing transformer.transform(src, res); reader.close(); outputStream.flush(); }
From source file:gov.nih.nci.cabig.caaers.api.BasePDFGenerator.java
public synchronized void generatePdf(String xml, String pdfOutFileName, String XSLFile) throws Exception { FopFactory fopFactory = FopFactory.newInstance(); FOUserAgent foUserAgent = fopFactory.newFOUserAgent(); // configure foUserAgent as desired // Setup output OutputStream out = new java.io.FileOutputStream(pdfOutFileName); out = new java.io.BufferedOutputStream(out); try {/*from w w w. j a v a 2 s . c om*/ // Construct fop with desired output format Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out); // Setup XSLT TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = null; transformer = factory.newTransformer( new StreamSource(BasePDFGenerator.class.getClassLoader().getResourceAsStream(XSLFile))); // Set the value of a <param> in the stylesheet transformer.setParameter("versionParam", "2.0"); // Setup XML String as input for XSLT transformation Source src = new StreamSource(new ByteArrayInputStream(xml.getBytes("UTF-8"))); // 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); } finally { out.close(); } }
From source file:eionet.gdem.conversion.converters.ConvertStrategy.java
/** * Method transforms XML source using XSL stream. * @param in InputStream containing source XML. * @param xslStream InputStream containing XSL content. * @param out OutputStream for conversion result. * @throws GDEMException In case of unexpected XML or XSL errors. *///from w w w .ja v a2 s .co m protected void runXslTransformation(InputStream in, InputStream xslStream, OutputStream out) throws GDEMException { try { TransformerFactory tFactory = transform.getTransformerFactoryInstance(); TransformerErrorListener errors = new TransformerErrorListener(); tFactory.setErrorListener(errors); StreamSource transformerSource = new StreamSource(xslStream); if (getXslPath() != null) { transformerSource.setSystemId(getXslPath()); } Transformer transformer = tFactory.newTransformer(transformerSource); transformer.setErrorListener(errors); transformer.setParameter(DD_DOMAIN_PARAM, Properties.ddURL); setTransformerParameters(transformer); long l = System.currentTimeMillis(); transformer.transform(new StreamSource(in), new StreamResult(out)); if (LOGGER.isDebugEnabled()) { LOGGER.debug((new StringBuilder()).append("generate: transformation needed ") .append(System.currentTimeMillis() - l).append(" ms").toString()); } } catch (TransformerConfigurationException tce) { throw new GDEMException("Error transforming XML - incorrect stylesheet file: " + tce.toString(), tce); } catch (TransformerException tfe) { throw new GDEMException( "Error transforming XML - it's not probably well-formed xml file: " + tfe.toString(), tfe); } catch (Throwable th) { LOGGER.error("Error " + th.toString(), th); th.printStackTrace(System.out); throw new GDEMException("Error transforming XML: " + th.toString()); } }
From source file:lu.tudor.santec.dicom.gui.header.Dcm2Xml.java
private TransformerHandler getTransformerHandler() throws TransformerConfigurationException, IOException { SAXTransformerFactory tf = (SAXTransformerFactory) TransformerFactory.newInstance(); if (xslt == null) { return tf.newTransformerHandler(); }// w ww.ja v a2s.c om if (xsltInc) { tf.setAttribute("http://xml.apache.org/xalan/features/incremental", Boolean.TRUE); } TransformerHandler th = tf .newTransformerHandler(new StreamSource(xslt.openStream(), xslt.toExternalForm())); Transformer t = th.getTransformer(); if (xsltParams != null) { for (int i = 0; i + 1 < xsltParams.length; i++, i++) { t.setParameter(xsltParams[i], xsltParams[i + 1]); } } return th; }
From source file:com.predic8.membrane.core.interceptor.xslt.XSLTTransformer.java
public byte[] transform(Source xml, Map<String, String> parameters) throws Exception { log.debug("applying transformation: " + styleSheet); ByteArrayOutputStream baos = new ByteArrayOutputStream(); Transformer t = transformers.take(); try {//from w ww. j av a 2 s . com try { t.clearParameters(); } catch (NullPointerException e) { // do nothing } for (Map.Entry<String, String> e : parameters.entrySet()) { t.setParameter(e.getKey(), e.getValue()); } t.transform(xml, new StreamResult(baos)); } finally { transformers.put(t); } return baos.toByteArray(); }
From source file:jeeves.utils.Xml.java
/** * Transforms an xml tree putting the result to a stream with optional parameters. * * @param xml//from ww w .j av a 2 s . c om * @param styleSheetPath * @param result * @param params * @throws Exception */ public static void transform(Element xml, String styleSheetPath, Result result, Map<String, String> params) throws Exception { File styleSheet = new File(styleSheetPath); Source srcXml = new JDOMSource(new Document((Element) xml.detach())); Source srcSheet = new StreamSource(styleSheet); // Dear old saxon likes to yell loudly about each and every XSLT 1.0 // stylesheet so switch it off but trap any exceptions because this // code is run on transformers other than saxon TransformerFactory transFact = TransformerFactoryFactory.getTransformerFactory(); transFact.setURIResolver(new JeevesURIResolver()); try { transFact.setAttribute(FeatureKeys.VERSION_WARNING, false); transFact.setAttribute(FeatureKeys.LINE_NUMBERING, true); transFact.setAttribute(FeatureKeys.PRE_EVALUATE_DOC_FUNCTION, false); transFact.setAttribute(FeatureKeys.RECOVERY_POLICY, Configuration.RECOVER_SILENTLY); // Add the following to get timing info on xslt transformations //transFact.setAttribute(FeatureKeys.TIMING,true); } catch (IllegalArgumentException e) { Log.warning(Log.ENGINE, "WARNING: transformerfactory doesnt like saxon attributes!"); //e.printStackTrace(); } finally { Transformer t = transFact.newTransformer(srcSheet); if (params != null) { for (Map.Entry<String, String> param : params.entrySet()) { t.setParameter(param.getKey(), param.getValue()); } } t.transform(srcXml, result); } }
From source file:com.uttesh.pdfngreport.handler.PdfReportHandler.java
/** * This method generate the PDF report by report data and the report store * location. After the report generation it will remove the temp file * created by the generator i.e XML data file and chart image file. * * @param reportData/*ww w . j av a2 s .c o m*/ * @param reportFile * @throws FileNotFoundException * @throws FOPException * @throws TransformerConfigurationException * @throws TransformerException * @throws IOException * @throws InterruptedException * @throws URISyntaxException * * @see FileNotFoundException * @see FOPException * @see TransformerConfigurationException * @see TransformerException * @see IOException * @see InterruptedException * @see URISyntaxException * * {@link com.uttesh.pdfngreport.util.xml.ReportData#member ReportData} */ public void generatePdfReport(ReportData reportData, File reportFile) throws FileNotFoundException, FOPException, TransformerConfigurationException, TransformerException, IOException, InterruptedException, URISyntaxException { int fileName = generateXmlData(reportData); File xmlfile = null; if (reportData.getOsName().equalsIgnoreCase("w")) { xmlfile = new File(reportLocation + Constants.BACKWARD_SLASH + fileName + Constants.XML_EXTENSION); } else { xmlfile = new File(reportLocation + Constants.FORWARD_SLASH + fileName + Constants.XML_EXTENSION); } //File xsltfile = new File(getClass().getClassLoader().getResource(Constants.REPORT_XSL_TEMPLATE).toURI()); InputStream input = getClass().getClassLoader().getResourceAsStream(Constants.REPORT_XSL_TEMPLATE); File pdffile = reportFile; FopFactory fopFactory = FopFactory.newInstance(new File(".").toURI()); FOUserAgent foUserAgent = fopFactory.newFOUserAgent(); OutputStream out = new java.io.FileOutputStream(pdffile); out = new java.io.BufferedOutputStream(out); try { Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out); TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(new StreamSource(input)); transformer.setParameter("versionParam", "2.0"); Source src = new StreamSource(xmlfile); Result res = new SAXResult(fop.getDefaultHandler()); transformer.transform(src, res); } catch (Exception e) { e.printStackTrace(System.err); if (reportData.getOsName().equalsIgnoreCase("w")) { new File(reportLocation + Constants.BACKWARD_SLASH + fileName + Constants.XML_EXTENSION).delete(); } else { new File(reportLocation + Constants.FORWARD_SLASH + fileName + Constants.XML_EXTENSION).delete(); } System.exit(-1); } finally { out.close(); if (reportData.getOsName().equalsIgnoreCase("w")) { new File(reportLocation + Constants.BACKWARD_SLASH + fileName + Constants.XML_EXTENSION).delete(); new File(reportLocation + Constants.BACKWARD_SLASH + Constants.REPORT_CHART_FILE).delete(); } else { new File(reportLocation + Constants.FORWARD_SLASH + fileName + Constants.XML_EXTENSION).delete(); new File(reportLocation + Constants.FORWARD_SLASH + Constants.REPORT_CHART_FILE).delete(); } } }
From source file:eu.planets_project.pp.plato.action.ProjectExportAction.java
/** * Performs XSLT transformation to get the DATA into the PLANS *///from ww w. j ava2 s . c om private void addBinaryData(Document doc, OutputStream out, String aTempDir) throws TransformerException { URL xslPath = Thread.currentThread().getContextClassLoader().getResource("data/xslt/bytestreams.xsl"); InputStream xsl = Thread.currentThread().getContextClassLoader() .getResourceAsStream("data/xslt/bytestreams.xsl"); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(new StreamSource(xsl)); transformer.setParameter("tempDir", aTempDir); Source xmlSource = new DocumentSource(doc); Result outputTarget = new StreamResult(out); //new FileWriter(outFile)); log.debug("starting bytestream transformation ..."); transformer.transform(xmlSource, outputTarget); log.debug("FINISHED bytestream transformation!"); }
From source file:com.gargoylesoftware.htmlunit.activex.javascript.msxml.XSLProcessor.java
/** * @return {@link XMLDOMNode} or {@link String} */// ww w .ja va2 s . c o m private Object transform(final XMLDOMNode source) { try { Source xmlSource = new DOMSource(source.getDomNodeOrDie()); final Source xsltSource = new DOMSource(style_.getDomNodeOrDie()); final org.w3c.dom.Document containerDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder() .newDocument(); final org.w3c.dom.Element containerElement = containerDocument.createElement("container"); containerDocument.appendChild(containerElement); final DOMResult result = new DOMResult(containerElement); final Transformer transformer = TransformerFactory.newInstance().newTransformer(xsltSource); for (final Map.Entry<String, Object> entry : parameters_.entrySet()) { transformer.setParameter(entry.getKey(), entry.getValue()); } transformer.transform(xmlSource, result); final org.w3c.dom.Node transformedNode = result.getNode(); if (transformedNode.getFirstChild().getNodeType() == Node.ELEMENT_NODE) { return transformedNode; } //output is not DOM (text) xmlSource = new DOMSource(source.getDomNodeOrDie()); final StringWriter writer = new StringWriter(); final Result streamResult = new StreamResult(writer); transformer.transform(xmlSource, streamResult); return writer.toString(); } catch (final Exception e) { throw Context.reportRuntimeError("Exception: " + e); } }
From source file:dk.defxws.fedoragsearch.server.GTransformer.java
/** * /*w w w . j ava 2s. co m*/ * * @throws TransformerConfigurationException, TransformerException. */ public void transformToFile(String xsltName, StreamSource sourceStream, Object[] params, String filePath) throws Exception { logger.fine("xsltName=" + xsltName); Transformer transformer = getTransformer(xsltName); for (int i = 0; i < params.length; i = i + 2) { Object value = params[i + 1]; if (value == null) { value = ""; } transformer.setParameter((String) params[i], value); } transformer.setParameter("DATETIME", new Date()); StreamResult destStream = new StreamResult(new File(filePath)); try { transformer.transform(sourceStream, destStream); } catch (TransformerException e) { throw new Exception("transform " + xsltName + ".xslt:\n", e); } }