001/* 002// This software is subject to the terms of the Eclipse Public License v1.0 003// Agreement, available at the following URL: 004// http://www.eclipse.org/legal/epl-v10.html. 005// You must accept the terms of that agreement to use this software. 006// 007// Copyright (C) 2002-2005 Julian Hyde 008// Copyright (C) 2005-2009 Pentaho and others 009// All Rights Reserved. 010*/ 011package mondrian.web.taglib; 012 013import java.io.InputStream; 014import java.util.HashMap; 015import javax.servlet.ServletContext; 016import javax.servlet.ServletContextEvent; 017import javax.xml.transform.*; 018import javax.xml.transform.stream.StreamSource; 019 020/** 021 * Holds compiled stylesheets. 022 * 023 * @author Andreas Voss, 22 March, 2002 024 */ 025public class ApplResources implements Listener.ApplicationContext { 026 027 private static final String ATTRNAME = "mondrian.web.taglib.ApplResources"; 028 private ServletContext context; 029 030 /** 031 * Creates a <code>ApplResources</code>. Only {@link Listener} calls this; 032 * you should probably call {@link #getInstance}. 033 */ 034 public ApplResources() { 035 } 036 037 /** 038 * Retrieves the one and only instance of <code>ApplResources</code> in 039 * this servlet's context. 040 */ 041 public static ApplResources getInstance(ServletContext context) { 042 return (ApplResources)context.getAttribute(ATTRNAME); 043 } 044 045 private HashMap templatesCache = new HashMap(); 046 public Transformer getTransformer(String xsltURI, boolean useCache) { 047 try { 048 Templates templates = null; 049 if (useCache) { 050 templates = (Templates)templatesCache.get(xsltURI); 051 } 052 if (templates == null) { 053 TransformerFactory tf = TransformerFactory.newInstance(); 054 InputStream input = context.getResourceAsStream(xsltURI); 055 templates = tf.newTemplates(new StreamSource(input)); 056 if (useCache) { 057 templatesCache.put(xsltURI, templates); 058 } 059 } 060 return templates.newTransformer(); 061 } catch (TransformerConfigurationException e) { 062 e.printStackTrace(); 063 throw new RuntimeException(e.toString()); 064 } 065 } 066 067 // implement ApplicationContext 068 public void init(ServletContextEvent event) { 069 this.context = event.getServletContext(); 070 context.setAttribute(ATTRNAME, this); 071 } 072 073 public void destroy(ServletContextEvent ev) { 074 } 075 076 077} 078 079// End ApplResources.java