Java Code Examples for javax.xml.transform.Transformer#setParameter()
The following examples show how to use
javax.xml.transform.Transformer#setParameter() .
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: RepositoryXslTransformer.java From fix-orchestra with Apache License 2.0 | 6 votes |
public void transform(File xsltFile, File inputXml, File outputXml, String[] parameters) throws TransformerException { outputXml.getParentFile().mkdirs(); final Source xmlSource = new javax.xml.transform.stream.StreamSource(inputXml); final Source xsltSource = new javax.xml.transform.stream.StreamSource(xsltFile); final Result result = new javax.xml.transform.stream.StreamResult(outputXml); final TransformerFactory transFact = new TransformerFactoryImpl(); final Transformer trans = transFact.newTransformer(xsltSource); for (int i = 0; i < parameters.length; i++) { final String[] parts = parameters[i].split("="); trans.setParameter(parts[0], parts[1]); } trans.transform(xmlSource, result); }
Example 2
Source File: Unified2OrchestraTransformer.java From fix-orchestra with Apache License 2.0 | 6 votes |
public void transform(File inputXml, File phrasesFile, File outputXml) throws TransformerException { final File parentFile = outputXml.getParentFile(); if (parentFile != null) { parentFile.mkdirs(); } final Source xmlSource = new javax.xml.transform.stream.StreamSource(inputXml); final InputStream xsltFile = getClass().getClassLoader().getResourceAsStream("xsl/unified2orchestra.xslt"); final Source xsltSource = new javax.xml.transform.stream.StreamSource(xsltFile); final Result result = new javax.xml.transform.stream.StreamResult(outputXml); final TransformerFactory transFact = new TransformerFactoryImpl(); final Transformer trans = transFact.newTransformer(xsltSource); trans.setParameter("phrases-file", phrasesFile.toURI().toString()); trans.transform(xmlSource, result); }
Example 3
Source File: AbstractXsltFileUpgradeOperation.java From studio with GNU General Public License v3.0 | 6 votes |
protected void executeTemplate(String site, String path, OutputStream os) throws UpgradeException { if(contentRepository.contentExists(site, path)) { try(InputStream templateIs = template.getInputStream()) { // Saxon is used to support XSLT 2.0 Transformer transformer = TransformerFactory.newInstance(SAXON_CLASS, null) .newTransformer(new StreamSource(templateIs)); logger.info("Applying XSLT template {0} to file {1} for site {2}", template, path, site); try(InputStream sourceIs = contentRepository.getContent(site, path)) { transformer.setParameter(PARAM_KEY_SITE, site); transformer.setParameter(PARAM_KEY_VERSION, nextVersion); transformer.setURIResolver(getURIResolver(site)); transformer.transform(new StreamSource(sourceIs), new StreamResult(os)); } } catch (Exception e) { throw new UpgradeException("Error processing file", e); } } else { logger.warn("Source file {0} does not exist in site {1}", path, site); } }
Example 4
Source File: RuleFlowMigrator.java From kogito-runtimes with Apache License 2.0 | 6 votes |
public static void transform(String stylesheet, Source src, Result res, HashMap<String, String> params) throws Exception { Transformer transformer = getTransformer(stylesheet); transformer.clearParameters(); if (params != null && params.size() > 0) { Iterator<String> itKeys = params.keySet().iterator(); while (itKeys.hasNext()) { String key = itKeys.next(); String value = params.get(key); transformer.setParameter(key, value); } } transformer.transform(src, res); }
Example 5
Source File: XsltForHtmlView.java From tds with BSD 3-Clause "New" or "Revised" License | 6 votes |
protected void renderMergedOutputModel(Map model, HttpServletRequest req, HttpServletResponse res) throws Exception { res.setContentType(getContentType()); Document doc = (Document) model.get("Document"); String transform = (String) model.get("Transform"); String resourceName = "/resources/xsl/" + transform; Resource resource = new ClassPathResource(resourceName); try (InputStream is = resource.getInputStream()) { Transformer transformer = TransformerFactory.newInstance().newTransformer(new StreamSource(is)); transformer.setParameter("tdsContext", req.getContextPath()); JDOMSource in = new JDOMSource(doc); JDOMResult out = new JDOMResult(); transformer.transform(in, out); Document html = out.getDocument(); if (html == null) throw new IllegalStateException("Bad XSLT=" + resourceName); XMLOutputter fmt = new XMLOutputter(Format.getPrettyFormat()); fmt.output(html, res.getOutputStream()); } }
Example 6
Source File: HtmlReport.java From teamengine with Apache License 2.0 | 5 votes |
/** * Convert EARL result into HTML report. * * @param outputDir * Location of the test result. * @return * Return the output file. * @throws FileNotFoundException * Throws exception if file is not available. */ public static File earlHtmlReport( String outputDir ) throws FileNotFoundException { ClassLoader cl = Thread.currentThread().getContextClassLoader(); String resourceDir = cl.getResource( "com/occamlab/te/earl/lib" ).getPath(); String earlXsl = cl.getResource( "com/occamlab/te/earl_html_report.xsl" ).toString(); File htmlOutput = new File( outputDir, "result" ); htmlOutput.mkdir(); LOGR.fine( "HTML output is written to directory " + htmlOutput ); File earlResult = new File( outputDir, "earl-results.rdf" ); try { TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer( new StreamSource( earlXsl ) ); transformer.setParameter( "outputDir", htmlOutput ); File indexHtml = new File( htmlOutput, "index.html" ); indexHtml.createNewFile(); FileOutputStream outputStream = new FileOutputStream( indexHtml ); transformer.transform( new StreamSource( earlResult ), new StreamResult( outputStream ) ); // Foritfy Mod: Close the outputStream releasing its resources outputStream.close(); FileUtils.copyDirectory( new File( resourceDir ), htmlOutput ); } catch ( Exception e ) { LOGR.log( Level.SEVERE, "Transformation of EARL to HTML failed.", e ); throw new RuntimeException( e ); } if ( !htmlOutput.exists() ) { throw new FileNotFoundException( "HTML results not found at " + htmlOutput.getAbsolutePath() ); } return htmlOutput; }
Example 7
Source File: Transformers.java From proarc with GNU General Public License v3.0 | 5 votes |
public byte[] transformAsBytes(Source input, Format format, Map<String, Object> params) throws TransformerException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); Result output = new StreamResult(buffer); Transformer t = createTransformer(format); for (Map.Entry<String, Object> param : params.entrySet()) { t.setParameter(param.getKey(), param.getValue()); } t.transform(input, output); return buffer.toByteArray(); }
Example 8
Source File: FlowActionHandler.java From sonar-flow-plugin with GNU Lesser General Public License v3.0 | 5 votes |
private void convertRawToFlow(byte[] in, OutputStream out, String type, boolean full, String flowname) throws Exception { XMLReader xmlReader = XMLReaderFactory.createXMLReader(); LocationFilter locationFilter = new LocationFilter(xmlReader); Transformer transformer = type.equals("html") ? htmlTransformer : (full ? jsonFullTransformer : jsonTransformer); transformer.setParameter("full", String.valueOf(full)); transformer.setParameter("flowname", flowname); SAXSource saxSource = new SAXSource( locationFilter, new InputSource(new ByteArrayInputStream(in))); transformer.transform(saxSource, new StreamResult(out)); }
Example 9
Source File: AbstractFilterFactory.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
@Override public TransformerHandler newStellarTypeFilter(String type) throws TransformerConfigurationException, SAXException, ParserConfigurationException, IOException { TransformerHandler retval = getTransformerHandler(getStellarXsl()); Transformer xformer = retval.getTransformer(); xformer.setParameter("type", type); return retval; }
Example 10
Source File: EarlToHtmlTransformation.java From teamengine with Apache License 2.0 | 5 votes |
/** * Transform EARL result into HTML report using XSLT. * * @param outputDir */ public void earlHtmlReport( String outputDir ) { ClassLoader cl = Thread.currentThread().getContextClassLoader(); String resourceDir = cl.getResource( "com/occamlab/te/earl/lib" ).getPath(); String earlXsl = cl.getResource( "com/occamlab/te/earl_html_report.xsl" ).toString(); File htmlOutput = new File( outputDir, "result" ); htmlOutput.mkdir(); File earlResult = findEarlResultFile( outputDir ); LOGR.log( FINE, "Try to transform earl result file '" + earlResult + "' to directory " + htmlOutput ); try { if ( earlResult != null && earlResult.exists() ) { Transformer transformer = TransformerFactory.newInstance().newTransformer( new StreamSource( earlXsl ) ); transformer.setParameter( "outputDir", htmlOutput ); File indexHtml = new File( htmlOutput, "index.html" ); indexHtml.createNewFile(); // Fortify Mod: Make sure the FileOutputStream is closed when we are done with it. // transformer.transform( new StreamSource( earlResult ), // new StreamResult( new FileOutputStream( indexHtml ) ) ); FileOutputStream fo = new FileOutputStream( indexHtml ); transformer.transform( new StreamSource( earlResult ), new StreamResult( fo ) ); fo.close(); FileUtils.copyDirectory( new File( resourceDir ), htmlOutput ); } } catch ( Exception e ) { LOGR.log( SEVERE, "Transformation of EARL to HTML failed.", e ); } }
Example 11
Source File: TfClearParamTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
/** * Obtains transformer's parameter with a short name that set before. Value * should be same as set one. * @throws TransformerConfigurationException If for some reason the * TransformerHandler can not be created. */ @Test public void clear03() throws TransformerConfigurationException { TransformerFactory tfactory = TransformerFactory.newInstance(); Transformer transformer = tfactory.newTransformer(); transformer.setParameter(SHORT_PARAM_NAME, PARAM_VALUE); assertEquals(transformer.getParameter(SHORT_PARAM_NAME).toString(), PARAM_VALUE); }
Example 12
Source File: AbstractFilterFactory.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
@Override public TransformerHandler newRAFilter(double min, double max) throws TransformerConfigurationException, SAXException, ParserConfigurationException, IOException { TransformerHandler retval = getTransformerHandler(getRAXsl()); Transformer xformer = retval.getTransformer(); xformer.setParameter("ra_min_hr", String.valueOf(min)); xformer.setParameter("ra_max_hr", String.valueOf(max)); return retval; }
Example 13
Source File: TfClearParamTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
/** * Obtains transformer's parameter whose initiated with a stream source with * the a name that set before. Value should be same as set one. * @throws TransformerConfigurationException If for some reason the * TransformerHandler can not be created. */ @Test public void clear05() throws TransformerConfigurationException { Transformer transformer = TransformerFactory.newInstance(). newTransformer(new StreamSource(new File(XSL_FILE))); transformer.setParameter(LONG_PARAM_NAME, PARAM_VALUE); assertEquals(transformer.getParameter(LONG_PARAM_NAME), PARAM_VALUE); }
Example 14
Source File: ExportReportHtml.java From Leo with Apache License 2.0 | 5 votes |
/** * 根据TestNG结果输出的xml文件,优化生成html格式测试报告 * @param tngOutFilePath TestNG的结果xml文件路径 * @param htmlReportPath html报告的目录 * @param htmlReportTitle 测试报告标题 * @return boolean 创建成功返回true */ public static boolean createHtmlReport(String tngOutFilePath,String htmlReportPath,String htmlReportTitle) { if (!FileUtil.isExist(tngOutFilePath) ) { log.error("生成Html报告出错-testng输出的xml文件不存在:"+tngOutFilePath); return false; } if (!FileUtil.createDictory(htmlReportPath)){ log.error("生成Html报告出错-输出目录创建失败:"+htmlReportPath); return false; } try { Source xml = new javax.xml.transform.stream.StreamSource(tngOutFilePath); Source xsl = new javax.xml.transform.stream.StreamSource(DispatchConf.TestNGXsltFile); Result out = new StreamResult(new BufferedOutputStream(new FileOutputStream(htmlReportPath+"/index.html"))); // 创建转换器工厂 TransformerFactory tfactory = TransformerFactory.newInstance(); // 创建 XSL 转换器 Transformer transformer = tfactory.newTransformer(xsl); //参数设置 transformer.setParameter("testNgXslt.outputDir",htmlReportPath); //transformer.setParameter("testNgXslt.showRuntimeTotals", true); transformer.setParameter("testNgXslt.reportTitle", htmlReportTitle); transformer.transform(xml, out); log.info("生成Html测试报告成功:"+htmlReportPath+"/index.html"); return true; } catch (Exception e) { log.error("生成Html报告出错-xml转换异常:"+e.getMessage()); return false; } }
Example 15
Source File: TfClearParamTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
/** * Obtains transformer's parameter whose initiated with a sax source with * the a name that set before. Value should be same as set one. * @throws Exception If any errors occur. */ @Test public void clear07() throws Exception { try (FileInputStream fis = new FileInputStream(XSL_FILE)) { SAXSource saxSource = new SAXSource(); saxSource.setInputSource(new InputSource(fis)); Transformer transformer = TransformerFactory.newInstance().newTransformer(saxSource); transformer.setParameter(LONG_PARAM_NAME, PARAM_VALUE); assertEquals(transformer.getParameter(LONG_PARAM_NAME), PARAM_VALUE); } }
Example 16
Source File: SCHTransformerCustomizer.java From ph-schematron with Apache License 2.0 | 5 votes |
public void customize (@Nonnull final EStep eStep, @Nonnull final Transformer aTransformer) { // Ensure an error listener is present if (m_aCustomErrorListener != null) aTransformer.setErrorListener (m_aCustomErrorListener); else aTransformer.setErrorListener (new LoggingTransformErrorListener (Locale.US)); // Set the optional URI Resolver if (m_aCustomURIResolver != null) aTransformer.setURIResolver (m_aCustomURIResolver); // Set all custom parameters if (m_aCustomParameters != null) for (final Map.Entry <String, ?> aEntry : m_aCustomParameters.entrySet ()) aTransformer.setParameter (aEntry.getKey (), aEntry.getValue ()); if (eStep == EStep.SCH2XSLT_3) { // On the last step, set the respective Schematron parameters as the // last action to avoid they are overwritten by a custom parameter. if (m_sPhase != null) aTransformer.setParameter ("phase", m_sPhase); if (m_sLanguageCode != null) aTransformer.setParameter ("langCode", m_sLanguageCode); } }
Example 17
Source File: AbstractSchematronXSLTBasedResource.java From ph-schematron with Apache License 2.0 | 4 votes |
@Nullable public final Document applySchematronValidation (@Nonnull final Node aXMLNode, @Nullable final String sBaseURI) throws TransformerException { ValueEnforcer.notNull (aXMLNode, "XMLNode"); final ISchematronXSLTBasedProvider aXSLTProvider = getXSLTProvider (); if (aXSLTProvider == null || !aXSLTProvider.isValidSchematron ()) { // We cannot progress because of invalid Schematron return null; } // Debug print the created XSLT document if (SchematronDebug.isShowCreatedXSLT ()) LOGGER.info ("Created XSLT document: " + XMLWriter.getNodeAsString (aXSLTProvider.getXSLTDocument ())); // Create result document final Document ret = XMLFactory.newDocument (); // Create the transformer object from the templates specified in the // constructor final Transformer aTransformer = aXSLTProvider.getXSLTTransformer (); // Apply customizations // Ensure an error listener is present if (m_aCustomErrorListener != null) aTransformer.setErrorListener (m_aCustomErrorListener); else aTransformer.setErrorListener (new LoggingTransformErrorListener (Locale.US)); // Set the optional URI Resolver if (m_aCustomURIResolver != null) aTransformer.setURIResolver (m_aCustomURIResolver); // Set all custom parameters if (m_aCustomParameters != null) for (final Map.Entry <String, ?> aEntry : m_aCustomParameters.entrySet ()) aTransformer.setParameter (aEntry.getKey (), aEntry.getValue ()); if (LOGGER.isDebugEnabled ()) LOGGER.debug ("Applying Schematron XSLT on XML [start]"); // Enable this for hardcore Saxon debugging only if (false) if (aTransformer.getClass ().getName ().equals ("net.sf.saxon.jaxp.TransformerImpl")) { final XsltTransformer aXT = ((TransformerImpl) aTransformer).getUnderlyingXsltTransformer (); aXT.setMessageListener ( (a, b, c, d) -> LOGGER.info ("MessageListener2: " + a + ", " + b + ", " + c + ", " + d)); aXT.setTraceFunctionDestination (new StandardLogger (System.err)); if (false) aXT.getUnderlyingController ().setTraceListener (new XSLTTraceListener ()); if (false) { final XSLTTraceListener aTL = new XSLTTraceListener (); aTL.setOutputDestination (new StandardLogger (System.err)); aXT.getUnderlyingController ().setTraceListener (TraceEventMulticaster.add (aTL, null)); } if (false) System.out.println ("mode=" + aXT.getInitialMode ()); if (false) System.out.println ("temp=" + aXT.getInitialTemplate ()); if (false) System.out.println (aTransformer.getOutputProperties ()); } // Do the main transformation { final DOMSource aSource = new DOMSource (aXMLNode); aSource.setSystemId (sBaseURI); aTransformer.transform (aSource, new DOMResult (ret)); } if (LOGGER.isDebugEnabled ()) LOGGER.debug ("Applying Schematron XSLT on XML [end]"); // Debug print the created SVRL document if (SchematronDebug.isShowCreatedSVRL ()) LOGGER.info ("Created SVRL:\n" + XMLWriter.getNodeAsString (ret)); return ret; }
Example 18
Source File: AbstractFopReportGenerator.java From yes-cart with Apache License 2.0 | 4 votes |
/** * {@inheritDoc} */ @Override public void generateReport(final ReportDescriptor descriptor, final Map<String, Object> parameters, final Object data, final String lang, final OutputStream outputStream) { if (data == null || data instanceof Collection && ((Collection) data).isEmpty()) { LOG.debug("No data, no report will be generated"); return; } try { final InputStream config = getFopUserConfigInputStream(descriptor, parameters, data, lang); if (config == null) { LOG.error("FOP config file not found, " + "please put the fop-userconfig.xml file into the classpath of the server, UTF-8 characters won't be displayed correctly"); return; } final URI base = getBaseReportURI(descriptor, parameters, data, lang); final ResourceResolver rr = ResourceResolverFactory.createTempAwareResourceResolver( getTempResourceResolver(descriptor, parameters, data, lang), getResourceResolver(descriptor, parameters, data, lang) ); final FopFactoryBuilder confBuilder = new FopConfParser( config, EnvironmentalProfileFactory.createRestrictedIO(base, rr) ).getFopFactoryBuilder(); final Source xsltfile = getXsltFile(descriptor, parameters, data, lang); if (xsltfile == null) { LOG.error("Unable to read XSLT-FO file for {} in {}", descriptor, lang); return; } // configure fopFactory as desired final FopFactory fopFactory = confBuilder.build(); final FOUserAgent foUserAgent = fopFactory.newFOUserAgent(); final Source source = convertToSource(descriptor, parameters, data, lang); // Construct fop with desired output format final String mime = getOutputMimeType(descriptor, parameters, data, lang); final Fop fop = fopFactory.newFop(mime, foUserAgent, outputStream); // Setup XSLT 2.0 final TransformerFactory factory = TransformerFactory.newInstance("net.sf.saxon.TransformerFactoryImpl", null); final Transformer transformer = factory.newTransformer(xsltfile); // Set the value of a <param> in the stylesheet transformer.setParameter("versionParam", "2.0"); transformer.setOutputProperty("encoding", "UTF-8"); // Resulting SAX events (the generated FO) must be piped through to FOP final Result res = new SAXResult(fop.getDefaultHandler()); // Start XSLT transformation and FOP processing transformer.transform(source, res); } catch (Exception exp) { LOG.error("Unable to generate report for " + descriptor + " in " + lang, exp); } }
Example 19
Source File: XSLTransformationParser.java From teamengine with Apache License 2.0 | 4 votes |
public Document parse(URLConnection uc, Element instruction, PrintWriter logger) throws Exception { HashMap<String, String> properties = new HashMap<String, String>(); properties.putAll(defaultProperties); HashMap<String, String> params = new HashMap<String, String>(); params.putAll(defaultParams); Boolean ignoreErrors = defaultIgnoreErrors; Boolean ignoreWarnings = defaultIgnoreWarnings; Templates templates = parseInstruction(instruction, properties, params, ignoreErrors, ignoreWarnings); Transformer t = null; if (templates != null) { t = templates.newTransformer(); } else if (defaultTemplates != null) { t = defaultTemplates.newTransformer(); } else { t = tf.newTransformer(); } for (Entry<String, String> prop : properties.entrySet()) { t.setOutputProperty(prop.getKey(), prop.getValue()); } for (Entry<String, String> param : params.entrySet()) { t.setParameter(param.getKey(), param.getValue()); } XSLTransformationErrorHandler el = new XSLTransformationErrorHandler( logger, ignoreErrors, ignoreWarnings); t.setErrorListener(el); Document doc = db.newDocument(); InputStream is = null; try { if (LOGR.isLoggable(Level.FINER)) { String msg = String .format("Attempting to transform source from %s using instruction set:%n %s", uc.getURL(), DomUtils.serializeNode(instruction)); LOGR.finer(msg); } // may return error stream is = URLConnectionUtils.getInputStream(uc); t.transform(new StreamSource(is), new DOMResult(doc)); } catch (TransformerException e) { el.error(e); } finally { if (null != is) is.close(); } if (el.getErrorCount() > 0 && !ignoreErrors) { return null; } if (el.getWarningCount() > 0 && !ignoreWarnings) { return null; } return doc; }
Example 20
Source File: XmlTransformer.java From lutece-core with BSD 3-Clause "New" or "Revised" License | 4 votes |
/** * Transform XML documents using XSLT with cache * * @param source * The XML document content * @param stylesheet * The XSL source * @param strStyleSheetId * The StyleSheet Id * @param params * Parameters that can be used by the XSL StyleSheet * @param outputProperties * Properties to use for the XSL transform. Will overload the XSL output definition. * @return The output document * @throws TransformerException * The exception */ public String transform( Source source, Source stylesheet, String strStyleSheetId, Map<String, String> params, Properties outputProperties ) throws TransformerException { Templates templates = this.getTemplates( stylesheet, strStyleSheetId ); Transformer transformer = templates.newTransformer( ); if ( outputProperties != null ) { transformer.setOutputProperties( outputProperties ); } if ( params != null ) { transformer.clearParameters( ); for ( Entry<String, String> entry : params.entrySet( ) ) { transformer.setParameter( entry.getKey( ), entry.getValue( ) ); } } StringWriter sw = new StringWriter( ); Result result = new StreamResult( sw ); try { transformer.transform( source, result ); } catch( TransformerException e ) { String strMessage = "strStyleSheetId = " + strStyleSheetId + " " + e.getMessage( ); if ( e.getLocationAsString( ) != null ) { strMessage += ( " - location : " + e.getLocationAsString( ) ); } throw new TransformerException( ERROR_MESSAGE_XLST + strMessage, e.getCause( ) ); } finally { this.releaseTemplates( templates, strStyleSheetId ); } return sw.toString( ); }