下面列出了怎么用javax.xml.transform.Templates的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
protected void renderMergedOutputModel(
Map<String, Object> model, HttpServletRequest request, HttpServletResponse response)
throws Exception {
Templates templates = this.cachedTemplates;
if (templates == null) {
templates = loadTemplates();
}
Transformer transformer = createTransformer(templates);
configureTransformer(model, response, transformer);
configureResponse(model, response, transformer);
Source source = null;
try {
source = locateSource(model);
if (source == null) {
throw new IllegalArgumentException("Unable to locate Source object in model: " + model);
}
transformer.transform(source, createResult(response));
}
finally {
closeSourceIfNecessary(source);
}
}
/**
* javax.xml.transform.sax.SAXTransformerFactory implementation.
* Create an XMLFilter that uses the given source as the
* transformation instructions.
*
* @param templates The source of the transformation instructions.
* @return An XMLFilter object, or null if this feature is not supported.
* @throws TransformerConfigurationException
*/
@Override
public XMLFilter newXMLFilter(Templates templates)
throws TransformerConfigurationException
{
try {
return new com.sun.org.apache.xalan.internal.xsltc.trax.TrAXFilter(templates);
}
catch (TransformerConfigurationException e1) {
if (_errorListener != null) {
try {
_errorListener.fatalError(e1);
return null;
}
catch (TransformerException e2) {
new TransformerConfigurationException(e2);
}
}
throw e1;
}
}
/**
* Create an XMLFilter that uses the given source as the
* transformation instructions. Uses
* com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactory.
*/
public XMLFilter newXMLFilter(Source src)
throws TransformerConfigurationException {
if (_xsltcFactory == null) {
createXSLTCTransformerFactory();
}
if (_errorlistener != null) {
_xsltcFactory.setErrorListener(_errorlistener);
}
if (_uriresolver != null) {
_xsltcFactory.setURIResolver(_uriresolver);
}
Templates templates = _xsltcFactory.newTemplates(src);
if (templates == null ) return null;
return newXMLFilter(templates);
}
@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());
}
public XMLFilter newXMLFilter(Templates templates)
throws TransformerConfigurationException {
try {
return new com.sun.org.apache.xalan.internal.xsltc.trax.TrAXFilter(templates);
}
catch(TransformerConfigurationException e1) {
if (_xsltcFactory == null) {
createXSLTCTransformerFactory();
}
ErrorListener errorListener = _xsltcFactory.getErrorListener();
if(errorListener != null) {
try {
errorListener.fatalError(e1);
return null;
}
catch( TransformerException e2) {
new TransformerConfigurationException(e2);
}
}
throw e1;
}
}
@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());
}
/**
* Create an XMLFilter that uses the given source as the
* transformation instructions. Uses
* com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactory.
*/
public XMLFilter newXMLFilter(Source src)
throws TransformerConfigurationException {
if (_xsltcFactory == null) {
createXSLTCTransformerFactory();
}
if (_errorlistener != null) {
_xsltcFactory.setErrorListener(_errorlistener);
}
if (_uriresolver != null) {
_xsltcFactory.setURIResolver(_uriresolver);
}
Templates templates = _xsltcFactory.newTemplates(src);
if (templates == null ) return null;
return newXMLFilter(templates);
}
public XMLFilter newXMLFilter(Templates templates)
throws TransformerConfigurationException {
try {
return new com.sun.org.apache.xalan.internal.xsltc.trax.TrAXFilter(templates);
}
catch(TransformerConfigurationException e1) {
if (_xsltcFactory == null) {
createXSLTCTransformerFactory();
}
ErrorListener errorListener = _xsltcFactory.getErrorListener();
if(errorListener != null) {
try {
errorListener.fatalError(e1);
return null;
}
catch( TransformerException e2) {
new TransformerConfigurationException(e2);
}
}
throw e1;
}
}
/**
* Create a Templates object that from the input stylesheet
* Uses the com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactory.
* @param source the stylesheet.
* @return A Templates object.
*/
public Templates newTemplates(Source source)
throws TransformerConfigurationException
{
if (_xsltcFactory == null) {
createXSLTCTransformerFactory();
}
if (_errorlistener != null) {
_xsltcFactory.setErrorListener(_errorlistener);
}
if (_uriresolver != null) {
_xsltcFactory.setURIResolver(_uriresolver);
}
_currFactory = _xsltcFactory;
return _currFactory.newTemplates(source);
}
@Override
protected void renderMergedOutputModel(
Map<String, Object> model, HttpServletRequest request, HttpServletResponse response)
throws Exception {
Templates templates = this.cachedTemplates;
if (templates == null) {
templates = loadTemplates();
}
Transformer transformer = createTransformer(templates);
configureTransformer(model, response, transformer);
configureResponse(model, response, transformer);
Source source = null;
try {
source = locateSource(model);
if (source == null) {
throw new IllegalArgumentException("Unable to locate Source object in model: " + model);
}
transformer.transform(source, createResult(response));
}
finally {
closeSourceIfNecessary(source);
}
}
/**
* javax.xml.transform.sax.SAXTransformerFactory implementation.
* Create an XMLFilter that uses the given source as the
* transformation instructions.
*
* @param templates The source of the transformation instructions.
* @return An XMLFilter object, or null if this feature is not supported.
* @throws TransformerConfigurationException
*/
@Override
public XMLFilter newXMLFilter(Templates templates)
throws TransformerConfigurationException
{
try {
return new com.sun.org.apache.xalan.internal.xsltc.trax.TrAXFilter(templates);
}
catch (TransformerConfigurationException e1) {
if (_errorListener != null) {
try {
_errorListener.fatalError(e1);
return null;
}
catch (TransformerException e2) {
new TransformerConfigurationException(e2);
}
}
throw e1;
}
}
/**
* Create a Templates object that from the input stylesheet
* Uses the com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactory.
* @param source the stylesheet.
* @return A Templates object.
*/
public Templates newTemplates(Source source)
throws TransformerConfigurationException
{
if (_xsltcFactory == null) {
createXSLTCTransformerFactory();
}
if (_errorlistener != null) {
_xsltcFactory.setErrorListener(_errorlistener);
}
if (_uriresolver != null) {
_xsltcFactory.setURIResolver(_uriresolver);
}
_currFactory = _xsltcFactory;
return _currFactory.newTemplates(source);
}
/**
* Create an XMLFilter that uses the given source as the
* transformation instructions. Uses
* com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactory.
*/
public XMLFilter newXMLFilter(Source src)
throws TransformerConfigurationException {
if (_xsltcFactory == null) {
createXSLTCTransformerFactory();
}
if (_errorlistener != null) {
_xsltcFactory.setErrorListener(_errorlistener);
}
if (_uriresolver != null) {
_xsltcFactory.setURIResolver(_uriresolver);
}
Templates templates = _xsltcFactory.newTemplates(src);
if (templates == null ) return null;
return newXMLFilter(templates);
}
public XMLFilter newXMLFilter(Templates templates)
throws TransformerConfigurationException {
try {
return new com.sun.org.apache.xalan.internal.xsltc.trax.TrAXFilter(templates);
}
catch(TransformerConfigurationException e1) {
if (_xsltcFactory == null) {
createXSLTCTransformerFactory();
}
ErrorListener errorListener = _xsltcFactory.getErrorListener();
if(errorListener != null) {
try {
errorListener.fatalError(e1);
return null;
}
catch( TransformerException e2) {
new TransformerConfigurationException(e2);
}
}
throw e1;
}
}
public Object getObject(final String... command) throws Exception {
final Object templates = Gadgets.createTemplatesImpl(command);
String zeroHashCodeStr = "f5a5a608";
HashMap map = new HashMap();
map.put(zeroHashCodeStr, "foo");
InvocationHandler tempHandler = (InvocationHandler) Reflections.getFirstCtor(Gadgets.ANN_INV_HANDLER_CLASS).newInstance(
Override.class, map);
Reflections.setFieldValue(tempHandler, "type", Templates.class);
Templates proxy = Gadgets.createProxy(tempHandler, Templates.class);
LinkedHashSet set = new LinkedHashSet(); // maintain order
set.add(templates);
set.add(proxy);
Reflections.setFieldValue(templates, "_auxClasses", null);
Reflections.setFieldValue(templates, "_class", null);
map.put(zeroHashCodeStr, templates); // swap in real object
return set;
}
/**
* Create an XMLFilter that uses the given source as the
* transformation instructions. Uses
* com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactory.
*/
public XMLFilter newXMLFilter(Source src)
throws TransformerConfigurationException {
if (_xsltcFactory == null) {
createXSLTCTransformerFactory();
}
if (_errorlistener != null) {
_xsltcFactory.setErrorListener(_errorlistener);
}
if (_uriresolver != null) {
_xsltcFactory.setURIResolver(_uriresolver);
}
Templates templates = _xsltcFactory.newTemplates(src);
if (templates == null ) return null;
return newXMLFilter(templates);
}
/**
* javax.xml.transform.sax.SAXTransformerFactory implementation.
* Create an XMLFilter that uses the given source as the
* transformation instructions.
*
* @param templates The source of the transformation instructions.
* @return An XMLFilter object, or null if this feature is not supported.
* @throws TransformerConfigurationException
*/
@Override
public XMLFilter newXMLFilter(Templates templates)
throws TransformerConfigurationException
{
try {
return new com.sun.org.apache.xalan.internal.xsltc.trax.TrAXFilter(templates);
}
catch (TransformerConfigurationException e1) {
if (_errorListener != null) {
try {
_errorListener.fatalError(e1);
return null;
}
catch (TransformerException e2) {
new TransformerConfigurationException(e2);
}
}
throw e1;
}
}
/**
* Create a Templates object that from the input stylesheet
* Uses the com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactory.
* @param source the stylesheet.
* @return A Templates object.
*/
public Templates newTemplates(Source source)
throws TransformerConfigurationException
{
if (_xsltcFactory == null) {
createXSLTCTransformerFactory();
}
if (_errorlistener != null) {
_xsltcFactory.setErrorListener(_errorlistener);
}
if (_uriresolver != null) {
_xsltcFactory.setURIResolver(_uriresolver);
}
_currFactory = _xsltcFactory;
return _currFactory.newTemplates(source);
}
/**
* Create an XMLFilter that uses the given source as the
* transformation instructions. Uses
* com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactory.
*/
public XMLFilter newXMLFilter(Source src)
throws TransformerConfigurationException {
if (_xsltcFactory == null) {
createXSLTCTransformerFactory();
}
if (_errorlistener != null) {
_xsltcFactory.setErrorListener(_errorlistener);
}
if (_uriresolver != null) {
_xsltcFactory.setURIResolver(_uriresolver);
}
Templates templates = _xsltcFactory.newTemplates(src);
if (templates == null ) return null;
return newXMLFilter(templates);
}
@OnScheduled
public void onScheduled(final ProcessContext context) {
final ComponentLog logger = getLogger();
final Integer cacheSize = context.getProperty(CACHE_SIZE).asInteger();
final Long cacheTTL = context.getProperty(CACHE_TTL_AFTER_LAST_ACCESS).asTimePeriod(TimeUnit.SECONDS);
if (cacheSize > 0) {
CacheBuilder cacheBuilder = CacheBuilder.newBuilder().maximumSize(cacheSize);
if (cacheTTL > 0) {
cacheBuilder = cacheBuilder.expireAfterAccess(cacheTTL, TimeUnit.SECONDS);
}
cache = cacheBuilder.build(
new CacheLoader<String, Templates>() {
public Templates load(String path) throws TransformerConfigurationException {
return newTemplates(path);
}
});
} else {
cache = null;
logger.warn("Stylesheet cache disabled because cache size is set to 0");
}
}
/**
* Load the {@link Templates} instance for the stylesheet at the configured location.
*/
private Templates loadTemplates() throws ApplicationContextException {
Source stylesheetSource = getStylesheetSource();
try {
Templates templates = getTransformerFactory().newTemplates(stylesheetSource);
return templates;
}
catch (TransformerConfigurationException ex) {
throw new ApplicationContextException("Can't load stylesheet from '" + getUrl() + "'", ex);
}
finally {
closeSourceIfNecessary(stylesheetSource);
}
}
/**
* javax.xml.transform.sax.TransformerFactory implementation.
* Process the Source into a Templates object, which is a a compiled
* representation of the source. Note that this method should not be
* used with XSLTC, as the time-consuming compilation is done for each
* and every transformation.
*
* @return A Templates object that can be used to create Transformers.
* @throws TransformerConfigurationException
*/
@Override
public Transformer newTransformer(Source source) throws
TransformerConfigurationException
{
final Templates templates = newTemplates(source);
final Transformer transformer = templates.newTransformer();
if (_uriResolver != null) {
transformer.setURIResolver(_uriResolver);
}
return(transformer);
}
public TrAXFilter(Templates templates) throws
TransformerConfigurationException
{
_templates = templates;
_transformer = (TransformerImpl) templates.newTransformer();
_transformerHandler = new TransformerHandlerImpl(_transformer);
_useServicesMechanism = _transformer.useServicesMechnism();
}
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();
}
/**
* Get a TransformerHandler object that can process SAX ContentHandler
* events based on a transformer specified by the stylesheet Source.
* Uses com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactory.
*/
public TransformerHandler newTransformerHandler(Templates templates)
throws TransformerConfigurationException
{
if (_xsltcFactory == null) {
createXSLTCTransformerFactory();
}
if (_errorlistener != null) {
_xsltcFactory.setErrorListener(_errorlistener);
}
if (_uriresolver != null) {
_xsltcFactory.setURIResolver(_uriresolver);
}
return _xsltcFactory.newTransformerHandler(templates);
}
/**
* Get a TransformerHandler object that can process SAX ContentHandler
* events based on a transformer specified by the stylesheet Source.
* Uses com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactory.
*/
public TransformerHandler newTransformerHandler(Templates templates)
throws TransformerConfigurationException
{
if (_xsltcFactory == null) {
createXSLTCTransformerFactory();
}
if (_errorlistener != null) {
_xsltcFactory.setErrorListener(_errorlistener);
}
if (_uriresolver != null) {
_xsltcFactory.setURIResolver(_uriresolver);
}
return _xsltcFactory.newTransformerHandler(templates);
}
@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()));
}
}
/**
* javax.xml.transform.sax.TransformerFactory implementation.
* Process the Source into a Templates object, which is a a compiled
* representation of the source. Note that this method should not be
* used with XSLTC, as the time-consuming compilation is done for each
* and every transformation.
*
* @return A Templates object that can be used to create Transformers.
* @throws TransformerConfigurationException
*/
@Override
public Transformer newTransformer(Source source) throws
TransformerConfigurationException
{
final Templates templates = newTemplates(source);
final Transformer transformer = templates.newTransformer();
if (_uriResolver != null) {
transformer.setURIResolver(_uriResolver);
}
return(transformer);
}
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();
}
@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()));
}
}