下面列出了javax.xml.transform.TransformerFactory#newTemplates ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 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;
}
}
/**
* 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);
}
}
@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());
}
@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());
}
/**
* 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();
}
}
/** 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;
}
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();
}
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();
}
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();
}
@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())));
}
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();
}
@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()));
}
}
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;
}
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();
}
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();
}
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();
}
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;
}
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();
}
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();
}
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));
}
}