javax.xml.transform.Transformer#setParameter ( )源码实例Demo

下面列出了javax.xml.transform.Transformer#setParameter ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: fix-orchestra   文件: RepositoryXslTransformer.java
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);
}
 
源代码2 项目: tds   文件: XsltForHtmlView.java
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());
  }
}
 
源代码3 项目: kogito-runtimes   文件: RuleFlowMigrator.java
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);
}
 
源代码4 项目: studio   文件: AbstractXsltFileUpgradeOperation.java
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);
    }
}
 
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);
}
 
源代码6 项目: openjdk-jdk9   文件: AbstractFilterFactory.java
@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;
}
 
源代码7 项目: teamengine   文件: HtmlReport.java
/**
 * 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;
}
 
源代码8 项目: proarc   文件: Transformers.java
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();
}
 
源代码9 项目: sonar-flow-plugin   文件: FlowActionHandler.java
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));

}
 
源代码10 项目: openjdk-jdk9   文件: AbstractFilterFactory.java
@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;
}
 
源代码11 项目: teamengine   文件: EarlToHtmlTransformation.java
/**
 * 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 );
    }
}
 
源代码12 项目: openjdk-jdk9   文件: TfClearParamTest.java
/**
 * 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);
}
 
源代码13 项目: openjdk-jdk9   文件: TfClearParamTest.java
/**
 * 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);
}
 
源代码14 项目: Leo   文件: ExportReportHtml.java
/**
 * 根据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;
	}
}
 
源代码15 项目: openjdk-jdk9   文件: TfClearParamTest.java
/**
 * 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);
    }
}
 
源代码16 项目: ph-schematron   文件: SCHTransformerCustomizer.java
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);
  }
}
 
@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;
}
 
源代码18 项目: yes-cart   文件: AbstractFopReportGenerator.java
/**
 * {@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);
    }

}
 
源代码19 项目: teamengine   文件: XSLTransformationParser.java
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;
}
 
源代码20 项目: lutece-core   文件: XmlTransformer.java
/**
 * 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( );
}