Author: remy.maucherat(a)jboss.com
Date: 2009-06-11 08:29:25 -0400 (Thu, 11 Jun 2009)
New Revision: 1105
Removed:
trunk/java/org/apache/jasper/JspC.java
trunk/java/org/apache/jasper/compiler/AntCompiler.java
trunk/java/org/apache/jasper/compiler/TldLocationsCache.java
Modified:
trunk/java/org/apache/jasper/EmbeddedServletOptions.java
trunk/java/org/apache/jasper/Options.java
trunk/java/org/apache/jasper/compiler/JspConfig.java
Log:
- Remove the legacy XML processing (still there for easy comparisons in the 2.1 branch).
- Remove jspc (which cannot work anymore with a Servlet 3.0 webapp).
Modified: trunk/java/org/apache/jasper/EmbeddedServletOptions.java
===================================================================
--- trunk/java/org/apache/jasper/EmbeddedServletOptions.java 2009-06-11 11:11:18 UTC (rev
1104)
+++ trunk/java/org/apache/jasper/EmbeddedServletOptions.java 2009-06-11 12:29:25 UTC (rev
1105)
@@ -28,7 +28,6 @@
import org.apache.jasper.compiler.JspConfig;
import org.apache.jasper.compiler.Localizer;
import org.apache.jasper.compiler.TagPluginManager;
-import org.apache.jasper.compiler.TldLocationsCache;
import org.apache.jasper.xmlparser.ParserUtils;
import org.jboss.logging.Logger;
@@ -151,11 +150,6 @@
private String compilerClassName = null;
/**
- * Cache for the TLD locations
- */
- private TldLocationsCache tldLocationsCache = null;
-
- /**
* Jsp config information
*/
private JspConfig jspConfig = null;
@@ -344,14 +338,6 @@
errorOnUseBeanInvalidClassAttribute = b;
}
- public TldLocationsCache getTldLocationsCache() {
- return tldLocationsCache;
- }
-
- public void setTldLocationsCache( TldLocationsCache tldC ) {
- tldLocationsCache = tldC;
- }
-
public String getJavaEncoding() {
return javaEncoding;
}
@@ -645,10 +631,6 @@
}
}
- // Setup the global Tag Libraries location cache for this
- // web-application.
- tldLocationsCache = new TldLocationsCache(context);
-
// Setup the jsp config info for this web app.
jspConfig = new JspConfig(context);
Deleted: trunk/java/org/apache/jasper/JspC.java
===================================================================
--- trunk/java/org/apache/jasper/JspC.java 2009-06-11 11:11:18 UTC (rev 1104)
+++ trunk/java/org/apache/jasper/JspC.java 2009-06-11 12:29:25 UTC (rev 1105)
@@ -1,1418 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- *
http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.jasper;
-
-import java.io.BufferedReader;
-import java.io.CharArrayWriter;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.FileReader;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.io.Writer;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.net.URLClassLoader;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.HashMap;
-import java.util.Stack;
-import java.util.StringTokenizer;
-import java.util.Vector;
-
-import org.apache.jasper.compiler.Compiler;
-import org.apache.jasper.compiler.JspConfig;
-import org.apache.jasper.compiler.JspRuntimeContext;
-import org.apache.jasper.compiler.Localizer;
-import org.apache.jasper.compiler.TagPluginManager;
-import org.apache.jasper.compiler.TldLocationsCache;
-import org.apache.jasper.servlet.JspCServletContext;
-
-import org.apache.tools.ant.AntClassLoader;
-import org.apache.tools.ant.Project;
-import org.apache.tools.ant.util.FileUtils;
-import org.jboss.logging.Logger;
-import org.jboss.logging.Logger;
-
-/**
- * Shell for the jspc compiler. Handles all options associated with the
- * command line and creates compilation contexts which it then compiles
- * according to the specified options.
- *
- * This version can process files from a _single_ webapp at once, i.e.
- * a single docbase can be specified.
- *
- * It can be used as an Ant task using:
- * <pre>
- * <taskdef classname="org.apache.jasper.JspC"
name="jasper2" >
- * <classpath>
- * <pathelement
location="${java.home}/../lib/tools.jar"/>
- * <fileset dir="${ENV.CATALINA_HOME}/server/lib">
- * <include name="*.jar"/>
- * </fileset>
- * <fileset dir="${ENV.CATALINA_HOME}/common/lib">
- * <include name="*.jar"/>
- * </fileset>
- * <path refid="myjars"/>
- * </classpath>
- * </taskdef>
- *
- * <jasper2 verbose="0"
- * package="my.package"
- * uriroot="${webapps.dir}/${webapp.name}"
- * webXmlFragment="${build.dir}/generated_web.xml"
- * outputDir="${webapp.dir}/${webapp.name}/WEB-INF/src/my/package"
/>
- * </pre>
- *
- * @author Danno Ferrin
- * @author Pierre Delisle
- * @author Costin Manolache
- * @author Yoav Shapira
- */
-public class JspC implements Options {
-
- public static final String DEFAULT_IE_CLASS_ID =
- "clsid:8AD9C840-044E-11D1-B3E9-00805F499D93";
-
- // Logger
- protected static Logger log = Logger.getLogger(JspC.class);
-
- protected static final String SWITCH_VERBOSE = "-v";
- protected static final String SWITCH_HELP = "-help";
- protected static final String SWITCH_OUTPUT_DIR = "-d";
- protected static final String SWITCH_PACKAGE_NAME = "-p";
- protected static final String SWITCH_CACHE = "-cache";
- protected static final String SWITCH_CLASS_NAME = "-c";
- protected static final String SWITCH_FULL_STOP = "--";
- protected static final String SWITCH_COMPILE = "-compile";
- protected static final String SWITCH_SOURCE = "-source";
- protected static final String SWITCH_TARGET = "-target";
- protected static final String SWITCH_URI_BASE = "-uribase";
- protected static final String SWITCH_URI_ROOT = "-uriroot";
- protected static final String SWITCH_FILE_WEBAPP = "-webapp";
- protected static final String SWITCH_WEBAPP_INC = "-webinc";
- protected static final String SWITCH_WEBAPP_XML = "-webxml";
- protected static final String SWITCH_MAPPED = "-mapped";
- protected static final String SWITCH_XPOWERED_BY = "-xpoweredBy";
- protected static final String SWITCH_TRIM_SPACES = "-trimSpaces";
- protected static final String SWITCH_CLASSPATH = "-classpath";
- protected static final String SWITCH_DIE = "-die";
- protected static final String SWITCH_POOLING = "-poolingEnabled";
- protected static final String SWITCH_ENCODING = "-javaEncoding";
- protected static final String SWITCH_SMAP = "-smap";
- protected static final String SWITCH_DUMP_SMAP = "-dumpsmap";
-
- protected static final String SHOW_SUCCESS ="-s";
- protected static final String LIST_ERRORS = "-l";
- protected static final int INC_WEBXML = 10;
- protected static final int ALL_WEBXML = 20;
- protected static final int DEFAULT_DIE_LEVEL = 1;
- protected static final int NO_DIE_LEVEL = 0;
-
- protected static final String[] insertBefore =
- { "</web-app>", "<servlet-mapping>",
"<session-config>",
- "<mime-mapping>", "<welcome-file-list>",
"<error-page>", "<taglib>",
- "<resource-env-ref>", "<resource-ref>",
"<security-constraint>",
- "<login-config>", "<security-role>",
"<env-entry>", "<ejb-ref>",
- "<ejb-local-ref>" };
-
- protected static int die;
- protected String classPath = null;
- protected URLClassLoader loader = null;
- protected boolean trimSpaces = false;
- protected boolean genStringAsCharArray = false;
- protected boolean xpoweredBy;
- protected boolean mappedFile = false;
- protected boolean poolingEnabled = true;
- protected File scratchDir;
- protected String ieClassId = DEFAULT_IE_CLASS_ID;
- protected String targetPackage;
- protected String targetClassName;
- protected String uriBase;
- protected String uriRoot;
- protected Project project;
- protected int dieLevel;
- protected boolean helpNeeded = false;
- protected boolean compile = false;
- protected boolean smapSuppressed = true;
- protected boolean smapDumped = false;
- protected boolean caching = true;
- protected Map cache = new HashMap();
-
- protected String compiler = null;
-
- protected String compilerTargetVM = "1.4";
- protected String compilerSourceVM = "1.4";
-
- protected boolean classDebugInfo = true;
-
- /**
- * Throw an exception if there's a compilation error, or swallow it.
- * Default is true to preserve old behavior.
- */
- protected boolean failOnError = true;
-
- /**
- * The file extensions to be handled as JSP files.
- * Default list is .jsp and .jspx.
- */
- protected List extensions;
-
- /**
- * The pages.
- */
- protected List pages = new Vector();
-
- /**
- * Needs better documentation, this data member does.
- * True by default.
- */
- protected boolean errorOnUseBeanInvalidClassAttribute = true;
-
- /**
- * The java file encoding. Default
- * is UTF-8. Added per bugzilla 19622.
- */
- protected String javaEncoding = "UTF-8";
-
- // Generation of web.xml fragments
- protected String webxmlFile;
- protected int webxmlLevel;
- protected boolean addWebXmlMappings = false;
-
- protected Writer mapout;
- protected CharArrayWriter servletout;
- protected CharArrayWriter mappingout;
-
- /**
- * The servlet context.
- */
- protected JspCServletContext context;
-
- /**
- * The runtime context.
- * Maintain a dummy JspRuntimeContext for compiling tag files.
- */
- protected JspRuntimeContext rctxt;
-
- /**
- * Cache for the TLD locations
- */
- protected TldLocationsCache tldLocationsCache = null;
-
- protected JspConfig jspConfig = null;
- protected TagPluginManager tagPluginManager = null;
-
- protected boolean verbose = false;
- protected boolean listErrors = false;
- protected boolean showSuccess = false;
- protected int argPos;
- protected boolean fullstop = false;
- protected String args[];
-
- public static void main(String arg[]) {
- if (arg.length == 0) {
- System.out.println(Localizer.getMessage("jspc.usage"));
- } else {
- try {
- JspC jspc = new JspC();
- jspc.setArgs(arg);
- if (jspc.helpNeeded) {
- System.out.println(Localizer.getMessage("jspc.usage"));
- } else {
- jspc.execute();
- }
- } catch (JasperException je) {
- System.err.println(je);
- if (die != NO_DIE_LEVEL) {
- System.exit(die);
- }
- }
- }
- }
-
- public void setArgs(String[] arg) throws JasperException {
- args = arg;
- String tok;
-
- dieLevel = NO_DIE_LEVEL;
- die = dieLevel;
-
- while ((tok = nextArg()) != null) {
- if (tok.equals(SWITCH_VERBOSE)) {
- verbose = true;
- showSuccess = true;
- listErrors = true;
- } else if (tok.equals(SWITCH_OUTPUT_DIR)) {
- tok = nextArg();
- setOutputDir( tok );
- } else if (tok.equals(SWITCH_PACKAGE_NAME)) {
- targetPackage = nextArg();
- } else if (tok.equals(SWITCH_COMPILE)) {
- compile=true;
- } else if (tok.equals(SWITCH_CLASS_NAME)) {
- targetClassName = nextArg();
- } else if (tok.equals(SWITCH_URI_BASE)) {
- uriBase=nextArg();
- } else if (tok.equals(SWITCH_URI_ROOT)) {
- setUriroot( nextArg());
- } else if (tok.equals(SWITCH_FILE_WEBAPP)) {
- setUriroot( nextArg());
- } else if ( tok.equals( SHOW_SUCCESS ) ) {
- showSuccess = true;
- } else if ( tok.equals( LIST_ERRORS ) ) {
- listErrors = true;
- } else if (tok.equals(SWITCH_WEBAPP_INC)) {
- webxmlFile = nextArg();
- if (webxmlFile != null) {
- webxmlLevel = INC_WEBXML;
- }
- } else if (tok.equals(SWITCH_WEBAPP_XML)) {
- webxmlFile = nextArg();
- if (webxmlFile != null) {
- webxmlLevel = ALL_WEBXML;
- }
- } else if (tok.equals(SWITCH_MAPPED)) {
- mappedFile = true;
- } else if (tok.equals(SWITCH_XPOWERED_BY)) {
- xpoweredBy = true;
- } else if (tok.equals(SWITCH_TRIM_SPACES)) {
- setTrimSpaces(true);
- } else if (tok.equals(SWITCH_CACHE)) {
- tok = nextArg();
- if ("false".equals(tok)) {
- caching = false;
- } else {
- caching = true;
- }
- } else if (tok.equals(SWITCH_CLASSPATH)) {
- setClassPath(nextArg());
- } else if (tok.startsWith(SWITCH_DIE)) {
- try {
- dieLevel = Integer.parseInt(
- tok.substring(SWITCH_DIE.length()));
- } catch (NumberFormatException nfe) {
- dieLevel = DEFAULT_DIE_LEVEL;
- }
- die = dieLevel;
- } else if (tok.equals(SWITCH_HELP)) {
- helpNeeded = true;
- } else if (tok.equals(SWITCH_POOLING)) {
- tok = nextArg();
- if ("false".equals(tok)) {
- poolingEnabled = false;
- } else {
- poolingEnabled = true;
- }
- } else if (tok.equals(SWITCH_ENCODING)) {
- setJavaEncoding(nextArg());
- } else if (tok.equals(SWITCH_SOURCE)) {
- setCompilerSourceVM(nextArg());
- } else if (tok.equals(SWITCH_TARGET)) {
- setCompilerTargetVM(nextArg());
- } else if (tok.equals(SWITCH_SMAP)) {
- smapSuppressed = false;
- } else if (tok.equals(SWITCH_DUMP_SMAP)) {
- smapDumped = true;
- } else {
- if (tok.startsWith("-")) {
- throw new JasperException("Unrecognized option: " + tok +
- ". Use -help for help.");
- }
- if (!fullstop) {
- argPos--;
- }
- // Start treating the rest as JSP Pages
- break;
- }
- }
-
- // Add all extra arguments to the list of files
- while( true ) {
- String file = nextFile();
- if( file==null ) {
- break;
- }
- pages.add( file );
- }
- }
-
- public boolean getKeepGenerated() {
- // isn't this why we are running jspc?
- return true;
- }
-
- public boolean getTrimSpaces() {
- return trimSpaces;
- }
-
- public void setTrimSpaces(boolean ts) {
- this.trimSpaces = ts;
- }
-
- public boolean isPoolingEnabled() {
- return poolingEnabled;
- }
-
- public void setPoolingEnabled(boolean poolingEnabled) {
- this.poolingEnabled = poolingEnabled;
- }
-
- public boolean isXpoweredBy() {
- return xpoweredBy;
- }
-
- public void setXpoweredBy(boolean xpoweredBy) {
- this.xpoweredBy = xpoweredBy;
- }
-
- public boolean getDisplaySourceFragment() {
- return true;
- }
-
- public boolean getErrorOnUseBeanInvalidClassAttribute() {
- return errorOnUseBeanInvalidClassAttribute;
- }
-
- public void setErrorOnUseBeanInvalidClassAttribute(boolean b) {
- errorOnUseBeanInvalidClassAttribute = b;
- }
-
- public int getTagPoolSize() {
- return Constants.MAX_POOL_SIZE;
- }
-
- /**
- * Are we supporting HTML mapped servlets?
- */
- public boolean getMappedFile() {
- return mappedFile;
- }
-
- // Off-line compiler, no need for security manager
- public Object getProtectionDomain() {
- return null;
- }
-
- public boolean getSendErrorToClient() {
- // implied send to System.err
- return true;
- }
-
- public void setClassDebugInfo( boolean b ) {
- classDebugInfo=b;
- }
-
- public boolean getClassDebugInfo() {
- // compile with debug info
- return classDebugInfo;
- }
-
- /**
- * @see Options#isCaching()
- */
- public boolean isCaching() {
- return caching;
- }
-
- /**
- * @see Options#isCaching()
- */
- public void setCaching(boolean caching) {
- this.caching = caching;
- }
-
- /**
- * @see Options#getCache()
- */
- public Map getCache() {
- return cache;
- }
-
- /**
- * Background compilation check intervals in seconds
- */
- public int getCheckInterval() {
- return 0;
- }
-
- /**
- * Modification test interval.
- */
- public int getModificationTestInterval() {
- return 0;
- }
-
- /**
- * Is Jasper being used in development mode?
- */
- public boolean getDevelopment() {
- return false;
- }
-
- /**
- * Is the generation of SMAP info for JSR45 debuggin suppressed?
- */
- public boolean isSmapSuppressed() {
- return smapSuppressed;
- }
-
- /**
- * Set smapSuppressed flag.
- */
- public void setSmapSuppressed(boolean smapSuppressed) {
- this.smapSuppressed = smapSuppressed;
- }
-
-
- /**
- * Should SMAP info for JSR45 debugging be dumped to a file?
- */
- public boolean isSmapDumped() {
- return smapDumped;
- }
-
- /**
- * Set smapSuppressed flag.
- */
- public void setSmapDumped(boolean smapDumped) {
- this.smapDumped = smapDumped;
- }
-
-
- /**
- * Determines whether text strings are to be generated as char arrays,
- * which improves performance in some cases.
- *
- * @param genStringAsCharArray true if text strings are to be generated as
- * char arrays, false otherwise
- */
- public void setGenStringAsCharArray(boolean genStringAsCharArray) {
- this.genStringAsCharArray = genStringAsCharArray;
- }
-
- /**
- * Indicates whether text strings are to be generated as char arrays.
- *
- * @return true if text strings are to be generated as char arrays, false
- * otherwise
- */
- public boolean genStringAsCharArray() {
- return genStringAsCharArray;
- }
-
- /**
- * Sets the class-id value to be sent to Internet Explorer when using
- * <jsp:plugin> tags.
- *
- * @param ieClassId Class-id value
- */
- public void setIeClassId(String ieClassId) {
- this.ieClassId = ieClassId;
- }
-
- /**
- * Gets the class-id value that is sent to Internet Explorer when using
- * <jsp:plugin> tags.
- *
- * @return Class-id value
- */
- public String getIeClassId() {
- return ieClassId;
- }
-
- public File getScratchDir() {
- return scratchDir;
- }
-
- public Class getJspCompilerPlugin() {
- // we don't compile, so this is meanlingless
- return null;
- }
-
- public String getJspCompilerPath() {
- // we don't compile, so this is meanlingless
- return null;
- }
-
- /**
- * Compiler to use.
- */
- public String getCompiler() {
- return compiler;
- }
-
- public void setCompiler(String c) {
- compiler=c;
- }
-
- /**
- * Compiler class name to use.
- */
- public String getCompilerClassName() {
- return null;
- }
-
- /**
- * @see Options#getCompilerTargetVM
- */
- public String getCompilerTargetVM() {
- return compilerTargetVM;
- }
-
- public void setCompilerTargetVM(String vm) {
- compilerTargetVM = vm;
- }
-
- /**
- * @see Options#getCompilerSourceVM()
- */
- public String getCompilerSourceVM() {
- return compilerSourceVM;
- }
-
- /**
- * @see Options#getCompilerSourceVM()
- */
- public void setCompilerSourceVM(String vm) {
- compilerSourceVM = vm;
- }
-
- public TldLocationsCache getTldLocationsCache() {
- return tldLocationsCache;
- }
-
- /**
- * Returns the encoding to use for
- * java files. The default is UTF-8.
- *
- * @return String The encoding
- */
- public String getJavaEncoding() {
- return javaEncoding;
- }
-
- /**
- * Sets the encoding to use for
- * java files.
- *
- * @param encodingName The name, e.g. "UTF-8"
- */
- public void setJavaEncoding(String encodingName) {
- javaEncoding = encodingName;
- }
-
- public boolean getFork() {
- return false;
- }
-
- public String getClassPath() {
- if( classPath != null )
- return classPath;
- return System.getProperty("java.class.path");
- }
-
- public void setClassPath(String s) {
- classPath=s;
- }
-
- /**
- * Returns the list of file extensions
- * that are treated as JSP files.
- *
- * @return The list of extensions
- */
- public List getExtensions() {
- return extensions;
- }
-
- /**
- * Adds the given file extension to the
- * list of extensions handled as JSP files.
- *
- * @param extension The extension to add, e.g. "myjsp"
- */
- protected void addExtension(final String extension) {
- if(extension != null) {
- if(extensions == null) {
- extensions = new Vector();
- }
-
- extensions.add(extension);
- }
- }
-
- /**
- * Sets the project.
- *
- * @param theProject The project
- */
- public void setProject(final Project theProject) {
- project = theProject;
- }
-
- /**
- * Returns the project: may be null if not running
- * inside an Ant project.
- *
- * @return The project
- */
- public Project getProject() {
- return project;
- }
-
- /**
- * Base dir for the webapp. Used to generate class names and resolve
- * includes
- */
- public void setUriroot( String s ) {
- if( s==null ) {
- uriRoot = s;
- return;
- }
- try {
- uriRoot = resolveFile(s).getCanonicalPath();
- } catch( Exception ex ) {
- uriRoot = s;
- }
- }
-
- /**
- * Parses comma-separated list of JSP files to be processed. If the argument
- * is null, nothing is done.
- *
- * <p>Each file is interpreted relative to uriroot, unless it is absolute,
- * in which case it must start with uriroot.</p>
- *
- * @param jspFiles Comma-separated list of JSP files to be processed
- */
- public void setJspFiles(final String jspFiles) {
- if(jspFiles == null) {
- return;
- }
-
- StringTokenizer tok = new StringTokenizer(jspFiles, ",");
- while (tok.hasMoreTokens()) {
- pages.add(tok.nextToken());
- }
- }
-
- /**
- * Sets the compile flag.
- *
- * @param b Flag value
- */
- public void setCompile( final boolean b ) {
- compile = b;
- }
-
- /**
- * Sets the verbosity level. The actual number doesn't
- * matter: if it's greater than zero, the verbose flag will
- * be true.
- *
- * @param level Positive means verbose
- */
- public void setVerbose( final int level ) {
- if (level > 0) {
- verbose = true;
- showSuccess = true;
- listErrors = true;
- }
- }
-
- public void setValidateXml( boolean b ) {
- org.apache.jasper.xmlparser.ParserUtils.validating=b;
- }
-
- public void setListErrors( boolean b ) {
- listErrors = b;
- }
-
- public void setOutputDir( String s ) {
- if( s!= null ) {
- scratchDir = resolveFile(s).getAbsoluteFile();
- } else {
- scratchDir=null;
- }
- }
-
- public void setPackage( String p ) {
- targetPackage=p;
- }
-
- /**
- * Class name of the generated file ( without package ).
- * Can only be used if a single file is converted.
- * XXX Do we need this feature ?
- */
- public void setClassName( String p ) {
- targetClassName=p;
- }
-
- /**
- * File where we generate a web.xml fragment with the class definitions.
- */
- public void setWebXmlFragment( String s ) {
- webxmlFile=resolveFile(s).getAbsolutePath();
- webxmlLevel=INC_WEBXML;
- }
-
- /**
- * File where we generate a complete web.xml with the class definitions.
- */
- public void setWebXml( String s ) {
- webxmlFile=resolveFile(s).getAbsolutePath();
- webxmlLevel=ALL_WEBXML;
- }
-
- public void setAddWebXmlMappings(boolean b) {
- addWebXmlMappings = b;
- }
-
- /**
- * Set the option that throws an exception in case of a compilation error.
- */
- public void setFailOnError(final boolean b) {
- failOnError = b;
- }
-
- public boolean getFailOnError() {
- return failOnError;
- }
-
- /**
- * Obtain JSP configuration informantion specified in web.xml.
- */
- public JspConfig getJspConfig() {
- return jspConfig;
- }
-
- public TagPluginManager getTagPluginManager() {
- return tagPluginManager;
- }
-
- public void generateWebMapping( String file, JspCompilationContext clctxt )
- throws IOException
- {
- if (log.isDebugEnabled()) {
- log.debug("Generating web mapping for file " + file
- + " using compilation context " + clctxt);
- }
-
- String className = clctxt.getServletClassName();
- String packageName = clctxt.getServletPackageName();
-
- String thisServletName;
- if ("".equals(packageName)) {
- thisServletName = className;
- } else {
- thisServletName = packageName + '.' + className;
- }
-
- if (servletout != null) {
- servletout.write("\n <servlet>\n
<servlet-name>");
- servletout.write(thisServletName);
- servletout.write("</servlet-name>\n
<servlet-class>");
- servletout.write(thisServletName);
- servletout.write("</servlet-class>\n
</servlet>\n");
- }
- if (mappingout != null) {
- mappingout.write("\n <servlet-mapping>\n
<servlet-name>");
- mappingout.write(thisServletName);
- mappingout.write("</servlet-name>\n
<url-pattern>");
- mappingout.write(file.replace('\\', '/'));
- mappingout.write("</url-pattern>\n
</servlet-mapping>\n");
-
- }
- }
-
- /**
- * Include the generated web.xml inside the webapp's web.xml.
- */
- protected void mergeIntoWebXml() throws IOException {
-
- File webappBase = new File(uriRoot);
- File webXml = new File(webappBase, "WEB-INF/web.xml");
- File webXml2 = new File(webappBase, "WEB-INF/web2.xml");
- String insertStartMarker =
- Localizer.getMessage("jspc.webinc.insertStart");
- String insertEndMarker =
- Localizer.getMessage("jspc.webinc.insertEnd");
-
- BufferedReader reader = new BufferedReader(new FileReader(webXml));
- BufferedReader fragmentReader =
- new BufferedReader(new FileReader(webxmlFile));
- PrintWriter writer = new PrintWriter(new FileWriter(webXml2));
-
- // Insert the <servlet> and <servlet-mapping> declarations
- int pos = -1;
- String line = null;
- while (true) {
- line = reader.readLine();
- if (line == null) {
- break;
- }
- // Skip anything previously generated by JSPC
- if (line.indexOf(insertStartMarker) >= 0) {
- while (true) {
- line = reader.readLine();
- if (line == null) {
- return;
- }
- if (line.indexOf(insertEndMarker) >= 0) {
- line = reader.readLine();
- line = reader.readLine();
- if (line == null) {
- return;
- }
- break;
- }
- }
- }
- for (int i = 0; i < insertBefore.length; i++) {
- pos = line.indexOf(insertBefore[i]);
- if (pos >= 0)
- break;
- }
- if (pos >= 0) {
- writer.print(line.substring(0, pos));
- break;
- } else {
- writer.println(line);
- }
- }
-
- writer.println(insertStartMarker);
- while (true) {
- String line2 = fragmentReader.readLine();
- if (line2 == null) {
- writer.println();
- break;
- }
- writer.println(line2);
- }
- writer.println(insertEndMarker);
- writer.println();
-
- for (int i = 0; i < pos; i++) {
- writer.print(" ");
- }
- writer.println(line.substring(pos));
-
- while (true) {
- line = reader.readLine();
- if (line == null) {
- break;
- }
- writer.println(line);
- }
- writer.close();
-
- reader.close();
- fragmentReader.close();
-
- FileInputStream fis = new FileInputStream(webXml2);
- FileOutputStream fos = new FileOutputStream(webXml);
-
- byte buf[] = new byte[512];
- while (true) {
- int n = fis.read(buf);
- if (n < 0) {
- break;
- }
- fos.write(buf, 0, n);
- }
-
- fis.close();
- fos.close();
-
- webXml2.delete();
- (new File(webxmlFile)).delete();
-
- }
-
- protected void processFile(String file)
- throws JasperException
- {
- if (log.isDebugEnabled()) {
- log.debug("Processing file: " + file);
- }
-
- ClassLoader originalClassLoader = null;
-
- try {
- // set up a scratch/output dir if none is provided
- if (scratchDir == null) {
- String temp = System.getProperty("java.io.tmpdir");
- if (temp == null) {
- temp = "";
- }
- scratchDir = new File(new File(temp).getAbsolutePath());
- }
-
- String jspUri=file.replace('\\','/');
- JspCompilationContext clctxt = new JspCompilationContext
- ( jspUri, false, this, context, null, rctxt );
-
- /* Override the defaults */
- if ((targetClassName != null) && (targetClassName.length() > 0))
{
- clctxt.setServletClassName(targetClassName);
- targetClassName = null;
- }
- if (targetPackage != null) {
- clctxt.setServletPackageName(targetPackage);
- }
-
- originalClassLoader = Thread.currentThread().getContextClassLoader();
- if( loader==null ) {
- initClassLoader( clctxt );
- }
- Thread.currentThread().setContextClassLoader(loader);
-
- clctxt.setClassLoader(loader);
- clctxt.setClassPath(classPath);
-
- Compiler clc = clctxt.createCompiler();
-
- // If compile is set, generate both .java and .class, if
- // .jsp file is newer than .class file;
- // Otherwise only generate .java, if .jsp file is newer than
- // the .java file
- if( clc.isOutDated(compile) ) {
- if (log.isDebugEnabled()) {
- log.debug(jspUri + " is out dated, compiling...");
- }
-
- clc.compile(compile, true);
- }
-
- // Generate mapping
- generateWebMapping( file, clctxt );
- if ( showSuccess ) {
- log.info( "Built File: " + file );
- }
-
- } catch (JasperException je) {
- Throwable rootCause = je;
- while (rootCause instanceof JasperException
- && ((JasperException) rootCause).getRootCause() != null) {
- rootCause = ((JasperException) rootCause).getRootCause();
- }
- if (rootCause != je) {
- log.error(Localizer.getMessage("jspc.error.generalException",
- file),
- rootCause);
- }
-
- // Bugzilla 35114.
- if(getFailOnError()) {
- throw je;
- } else {
- log.error(je.getMessage());
- }
-
- } catch (Exception e) {
- if (e instanceof FileNotFoundException) {
- log.warn(Localizer.getMessage("jspc.error.fileDoesNotExist",
- e.getMessage()));
- }
- throw new JasperException(e);
- } finally {
- if(originalClassLoader != null) {
- Thread.currentThread().setContextClassLoader(originalClassLoader);
- }
- }
- }
-
- /**
- * Locate all jsp files in the webapp. Used if no explicit
- * jsps are specified.
- */
- public void scanFiles( File base ) throws JasperException {
- Stack<String> dirs = new Stack<String>();
- dirs.push(base.toString());
-
- // Make sure default extensions are always included
- if ((getExtensions() == null) || (getExtensions().size() < 2)) {
- addExtension("jsp");
- addExtension("jspx");
- }
-
- while (!dirs.isEmpty()) {
- String s = dirs.pop();
- File f = new File(s);
- if (f.exists() && f.isDirectory()) {
- String[] files = f.list();
- String ext;
- for (int i = 0; (files != null) && i < files.length; i++) {
- File f2 = new File(s, files[i]);
- if (f2.isDirectory()) {
- dirs.push(f2.getPath());
- } else {
- String path = f2.getPath();
- String uri = path.substring(uriRoot.length());
- ext = files[i].substring(files[i].lastIndexOf('.') +1);
- if (getExtensions().contains(ext) ||
- jspConfig.isJspPage(uri)) {
- pages.add(path);
- }
- }
- }
- }
- }
- }
-
- /**
- * Executes the compilation.
- *
- * @throws JasperException If an error occurs
- */
- public void execute() throws JasperException {
- if(log.isDebugEnabled()) {
- log.debug("execute() starting for " + pages.size() + "
pages.");
- }
-
- try {
- if (uriRoot == null) {
- if( pages.size() == 0 ) {
- throw new JasperException(
- Localizer.getMessage("jsp.error.jspc.missingTarget"));
- }
- String firstJsp = (String) pages.get( 0 );
- File firstJspF = new File( firstJsp );
- if (!firstJspF.exists()) {
- throw new JasperException(
- Localizer.getMessage("jspc.error.fileDoesNotExist",
- firstJsp));
- }
- locateUriRoot( firstJspF );
- }
-
- if (uriRoot == null) {
- throw new JasperException(
- Localizer.getMessage("jsp.error.jspc.no_uriroot"));
- }
-
- if( context==null ) {
- initServletContext();
- }
-
- // No explicit pages, we'll process all .jsp in the webapp
- if (pages.size() == 0) {
- scanFiles( new File( uriRoot ));
- }
-
- File uriRootF = new File(uriRoot);
- if (!uriRootF.exists() || !uriRootF.isDirectory()) {
- throw new JasperException(
- Localizer.getMessage("jsp.error.jspc.uriroot_not_dir"));
- }
-
- initWebXml();
-
- Iterator iter = pages.iterator();
- while (iter.hasNext()) {
- String nextjsp = iter.next().toString();
- File fjsp = new File(nextjsp);
- if (!fjsp.isAbsolute()) {
- fjsp = new File(uriRootF, nextjsp);
- }
- if (!fjsp.exists()) {
- log.warn(Localizer.getMessage
- ("jspc.error.fileDoesNotExist", fjsp.toString()));
- continue;
- }
- String s = fjsp.getAbsolutePath();
- if (s.startsWith(uriRoot)) {
- nextjsp = s.substring(uriRoot.length());
- }
- if (nextjsp.startsWith("." + File.separatorChar)) {
- nextjsp = nextjsp.substring(2);
- }
- processFile(nextjsp);
- }
-
- completeWebXml();
-
- if (addWebXmlMappings) {
- mergeIntoWebXml();
- }
-
- } catch (IOException ioe) {
- throw new JasperException(ioe);
-
- } catch (JasperException je) {
- Throwable rootCause = je;
- while (rootCause instanceof JasperException
- && ((JasperException) rootCause).getRootCause() != null) {
- rootCause = ((JasperException) rootCause).getRootCause();
- }
- if (rootCause != je) {
- rootCause.printStackTrace();
- }
- throw je;
- }/* finally {
- if (loader != null) {
- Logger.release(loader);
- }
- }*/
- }
-
- // ==================== protected utility methods ====================
-
- protected String nextArg() {
- if ((argPos >= args.length)
- || (fullstop = SWITCH_FULL_STOP.equals(args[argPos]))) {
- return null;
- } else {
- return args[argPos++];
- }
- }
-
- protected String nextFile() {
- if (fullstop) argPos++;
- if (argPos >= args.length) {
- return null;
- } else {
- return args[argPos++];
- }
- }
-
- protected void initWebXml() {
- try {
- if (webxmlLevel >= INC_WEBXML) {
- File fmapings = new File(webxmlFile);
- mapout = new FileWriter(fmapings);
- servletout = new CharArrayWriter();
- mappingout = new CharArrayWriter();
- } else {
- mapout = null;
- servletout = null;
- mappingout = null;
- }
- if (webxmlLevel >= ALL_WEBXML) {
- mapout.write(Localizer.getMessage("jspc.webxml.header"));
- mapout.flush();
- } else if ((webxmlLevel>= INC_WEBXML) && !addWebXmlMappings) {
- mapout.write(Localizer.getMessage("jspc.webinc.header"));
- mapout.flush();
- }
- } catch (IOException ioe) {
- mapout = null;
- servletout = null;
- mappingout = null;
- }
- }
-
- protected void completeWebXml() {
- if (mapout != null) {
- try {
- servletout.writeTo(mapout);
- mappingout.writeTo(mapout);
- if (webxmlLevel >= ALL_WEBXML) {
- mapout.write(Localizer.getMessage("jspc.webxml.footer"));
- } else if ((webxmlLevel >= INC_WEBXML) && !addWebXmlMappings)
{
- mapout.write(Localizer.getMessage("jspc.webinc.footer"));
- }
- mapout.close();
- } catch (IOException ioe) {
- // noting to do if it fails since we are done with it
- }
- }
- }
-
- protected void initServletContext() {
- try {
- context =new JspCServletContext
- (new PrintWriter(System.out),
- new URL("file:" + uriRoot.replace('\\','/') +
'/'));
- tldLocationsCache = new TldLocationsCache(context, true);
- } catch (MalformedURLException me) {
- System.out.println("**" + me);
- }
- rctxt = new JspRuntimeContext(context, this);
- jspConfig = new JspConfig(context);
- tagPluginManager = new TagPluginManager(context);
- }
-
- /**
- * Initializes the classloader as/if needed for the given
- * compilation context.
- *
- * @param clctxt The compilation context
- * @throws IOException If an error occurs
- */
- protected void initClassLoader(JspCompilationContext clctxt)
- throws IOException {
-
- classPath = getClassPath();
-
- ClassLoader jspcLoader = getClass().getClassLoader();
- if (jspcLoader instanceof AntClassLoader) {
- classPath += File.pathSeparator
- + ((AntClassLoader) jspcLoader).getClasspath();
- }
-
- // Turn the classPath into URLs
- ArrayList<URL> urls = new ArrayList<URL>();
- StringTokenizer tokenizer = new StringTokenizer(classPath,
- File.pathSeparator);
- while (tokenizer.hasMoreTokens()) {
- String path = tokenizer.nextToken();
- try {
- File libFile = new File(path);
- urls.add(libFile.toURL());
- } catch (IOException ioe) {
- // Failing a toCanonicalPath on a file that
- // exists() should be a JVM regression test,
- // therefore we have permission to freak uot
- throw new RuntimeException(ioe.toString());
- }
- }
-
- File webappBase = new File(uriRoot);
- if (webappBase.exists()) {
- File classes = new File(webappBase, "/WEB-INF/classes");
- try {
- if (classes.exists()) {
- classPath = classPath + File.pathSeparator
- + classes.getCanonicalPath();
- urls.add(classes.getCanonicalFile().toURL());
- }
- } catch (IOException ioe) {
- // failing a toCanonicalPath on a file that
- // exists() should be a JVM regression test,
- // therefore we have permission to freak out
- throw new RuntimeException(ioe.toString());
- }
- File lib = new File(webappBase, "/WEB-INF/lib");
- if (lib.exists() && lib.isDirectory()) {
- String[] libs = lib.list();
- for (int i = 0; i < libs.length; i++) {
- if( libs[i].length() <5 ) continue;
- String ext=libs[i].substring( libs[i].length() - 4 );
- if (! ".jar".equalsIgnoreCase(ext)) {
- if (".tld".equalsIgnoreCase(ext)) {
- log.warn("TLD files should not be placed in "
- + "/WEB-INF/lib");
- }
- continue;
- }
- try {
- File libFile = new File(lib, libs[i]);
- classPath = classPath + File.pathSeparator
- + libFile.getAbsolutePath();
- urls.add(libFile.getAbsoluteFile().toURL());
- } catch (IOException ioe) {
- // failing a toCanonicalPath on a file that
- // exists() should be a JVM regression test,
- // therefore we have permission to freak out
- throw new RuntimeException(ioe.toString());
- }
- }
- }
- }
-
- // What is this ??
- urls.add(new
File(clctxt.getRealPath("/")).getCanonicalFile().toURL());
-
- URL urlsA[]=new URL[urls.size()];
- urls.toArray(urlsA);
- loader = new URLClassLoader(urlsA, this.getClass().getClassLoader());
-
- }
-
- /**
- * Find the WEB-INF dir by looking up in the directory tree.
- * This is used if no explicit docbase is set, but only files.
- * XXX Maybe we should require the docbase.
- */
- protected void locateUriRoot( File f ) {
- String tUriBase = uriBase;
- if (tUriBase == null) {
- tUriBase = "/";
- }
- try {
- if (f.exists()) {
- f = new File(f.getAbsolutePath());
- while (f != null) {
- File g = new File(f, "WEB-INF");
- if (g.exists() && g.isDirectory()) {
- uriRoot = f.getCanonicalPath();
- uriBase = tUriBase;
- if (log.isInfoEnabled()) {
- log.info(Localizer.getMessage(
- "jspc.implicit.uriRoot",
- uriRoot));
- }
- break;
- }
- if (f.exists() && f.isDirectory()) {
- tUriBase = "/" + f.getName() + "/" +
tUriBase;
- }
-
- String fParent = f.getParent();
- if (fParent == null) {
- break;
- } else {
- f = new File(fParent);
- }
-
- // If there is no acceptible candidate, uriRoot will
- // remain null to indicate to the CompilerContext to
- // use the current working/user dir.
- }
-
- if (uriRoot != null) {
- File froot = new File(uriRoot);
- uriRoot = froot.getCanonicalPath();
- }
- }
- } catch (IOException ioe) {
- // since this is an optional default and a null value
- // for uriRoot has a non-error meaning, we can just
- // pass straight through
- }
- }
-
- /**
- * Resolves the relative or absolute pathname correctly
- * in both Ant and command-line situations. If Ant launched
- * us, we should use the basedir of the current project
- * to resolve relative paths.
- *
- * See Bugzilla 35571.
- *
- * @param s The file
- * @return The file resolved
- */
- protected File resolveFile(final String s) {
- if(getProject() == null) {
- // Note FileUtils.getFileUtils replaces FileUtils.newFileUtils in Ant 1.6.3
- return FileUtils.newFileUtils().resolveFile(null, s);
- } else {
- return FileUtils.newFileUtils().resolveFile(getProject().getBaseDir(), s);
- }
- }
-}
Modified: trunk/java/org/apache/jasper/Options.java
===================================================================
--- trunk/java/org/apache/jasper/Options.java 2009-06-11 11:11:18 UTC (rev 1104)
+++ trunk/java/org/apache/jasper/Options.java 2009-06-11 12:29:25 UTC (rev 1105)
@@ -22,7 +22,6 @@
import org.apache.jasper.compiler.JspConfig;
import org.apache.jasper.compiler.TagPluginManager;
-import org.apache.jasper.compiler.TldLocationsCache;
/**
* A class to hold all init parameters specific to the JSP engine.
@@ -135,19 +134,6 @@
public String getCompilerClassName();
/**
- * The cache for the location of the TLD's
- * for the various tag libraries 'exposed'
- * by the web application.
- * A tag library is 'exposed' either explicitely in
- * web.xml or implicitely via the uri tag in the TLD
- * of a taglib deployed in a jar file (WEB-INF/lib).
- *
- * @return the instance of the TldLocationsCache
- * for the web-application.
- */
- public TldLocationsCache getTldLocationsCache();
-
- /**
* Java platform encoding to generate the JSP
* page servlet.
*/
Deleted: trunk/java/org/apache/jasper/compiler/AntCompiler.java
===================================================================
--- trunk/java/org/apache/jasper/compiler/AntCompiler.java 2009-06-11 11:11:18 UTC (rev
1104)
+++ trunk/java/org/apache/jasper/compiler/AntCompiler.java 2009-06-11 12:29:25 UTC (rev
1105)
@@ -1,492 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- *
http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.jasper.compiler;
-
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.PrintStream;
-import java.util.StringTokenizer;
-
-import org.apache.jasper.JasperException;
-import org.apache.tools.ant.BuildException;
-import org.apache.tools.ant.DefaultLogger;
-import org.apache.tools.ant.Project;
-import org.apache.tools.ant.taskdefs.Javac;
-import org.apache.tools.ant.types.Path;
-import org.apache.tools.ant.types.PatternSet;
-
-/**
- * Main JSP compiler class. This class uses Ant for compiling.
- *
- * @author Anil K. Vijendran
- * @author Mandar Raje
- * @author Pierre Delisle
- * @author Kin-man Chung
- * @author Remy Maucherat
- * @author Mark Roth
- */
-public class AntCompiler extends Compiler {
-
- protected static Object javacLock = new Object();
-
- static {
- System.setErr(new SystemLogHandler(System.err));
- }
-
- // ----------------------------------------------------- Instance Variables
-
- protected Project project = null;
- protected JasperAntLogger logger;
-
- // ------------------------------------------------------------ Constructor
-
- // Lazy eval - if we don't need to compile we probably don't need the
project
- protected Project getProject() {
-
- if (project != null)
- return project;
-
- // Initializing project
- project = new Project();
- logger = new JasperAntLogger();
- logger.setOutputPrintStream(System.out);
- logger.setErrorPrintStream(System.err);
- logger.setMessageOutputLevel(Project.MSG_INFO);
- project.addBuildListener( logger);
- if (System.getProperty("catalina.home") != null) {
- project.setBasedir( System.getProperty("catalina.home"));
- }
-
- if( options.getCompiler() != null ) {
- if( log.isDebugEnabled() )
- log.debug("Compiler " + options.getCompiler() );
- project.setProperty("build.compiler", options.getCompiler() );
- }
- project.init();
- return project;
- }
-
- public class JasperAntLogger extends DefaultLogger {
-
- protected StringBuffer reportBuf = new StringBuffer();
-
- protected void printMessage(final String message,
- final PrintStream stream,
- final int priority) {
- }
-
- protected void log(String message) {
- reportBuf.append(message);
- reportBuf.append(System.getProperty("line.separator"));
- }
-
- protected String getReport() {
- String report = reportBuf.toString();
- reportBuf.setLength(0);
- return report;
- }
- }
-
- // --------------------------------------------------------- Public Methods
-
-
- /**
- * Compile the servlet from .java file to .class file
- */
- protected void generateClass(String[] smap)
- throws FileNotFoundException, JasperException, Exception {
-
- long t1 = 0;
- if (log.isDebugEnabled()) {
- t1 = System.currentTimeMillis();
- }
-
- String javaEncoding = ctxt.getOptions().getJavaEncoding();
- String javaFileName = ctxt.getServletJavaFileName();
- String classpath = ctxt.getClassPath();
-
- String sep = System.getProperty("path.separator");
-
- StringBuffer errorReport = new StringBuffer();
-
- StringBuffer info=new StringBuffer();
- info.append("Compile: javaFileName=" + javaFileName + "\n"
);
- info.append(" classpath=" + classpath + "\n" );
-
- // Start capturing the System.err output for this thread
- SystemLogHandler.setThread();
-
- // Initializing javac task
- getProject();
- Javac javac = (Javac) project.createTask("javac");
-
- // Initializing classpath
- Path path = new Path(project);
- path.setPath(System.getProperty("java.class.path"));
- info.append(" cp=" + System.getProperty("java.class.path")
+ "\n");
- StringTokenizer tokenizer = new StringTokenizer(classpath, sep);
- while (tokenizer.hasMoreElements()) {
- String pathElement = tokenizer.nextToken();
- File repository = new File(pathElement);
- path.setLocation(repository);
- info.append(" cp=" + repository + "\n");
- }
-
- if( log.isDebugEnabled() )
- log.debug( "Using classpath: " +
System.getProperty("java.class.path") + sep
- + classpath);
-
- // Initializing sourcepath
- Path srcPath = new Path(project);
- srcPath.setLocation(options.getScratchDir());
-
- info.append(" work dir=" + options.getScratchDir() +
"\n");
-
- // Initialize and set java extensions
- String exts = System.getProperty("java.ext.dirs");
- if (exts != null) {
- Path extdirs = new Path(project);
- extdirs.setPath(exts);
- javac.setExtdirs(extdirs);
- info.append(" extension dir=" + exts + "\n");
- }
-
- // Add endorsed directories if any are specified and we're forking
- // See Bugzilla 31257
- if(ctxt.getOptions().getFork()) {
- String endorsed = System.getProperty("java.endorsed.dirs");
- if(endorsed != null) {
- Javac.ImplementationSpecificArgument endorsedArg =
- javac.createCompilerArg();
- endorsedArg.setLine("-J-Djava.endorsed.dirs=" +
quotePathList(endorsed));
- info.append(" endorsed dir=" + quotePathList(endorsed) +
"\n");
- } else {
- info.append(" no endorsed dirs specified\n");
- }
- }
-
- // Configure the compiler object
- javac.setEncoding(javaEncoding);
- javac.setClasspath(path);
- javac.setDebug(ctxt.getOptions().getClassDebugInfo());
- javac.setSrcdir(srcPath);
- javac.setTempdir(options.getScratchDir());
- javac.setOptimize(! ctxt.getOptions().getClassDebugInfo() );
- javac.setFork(ctxt.getOptions().getFork());
- info.append(" srcDir=" + srcPath + "\n" );
-
- // Set the Java compiler to use
- if (options.getCompiler() != null) {
- javac.setCompiler(options.getCompiler());
- info.append(" compiler=" + options.getCompiler() +
"\n");
- }
-
- if (options.getCompilerTargetVM() != null) {
- javac.setTarget(options.getCompilerTargetVM());
- info.append(" compilerTargetVM=" + options.getCompilerTargetVM()
+ "\n");
- }
-
- if (options.getCompilerSourceVM() != null) {
- javac.setSource(options.getCompilerSourceVM());
- info.append(" compilerSourceVM=" + options.getCompilerSourceVM()
+ "\n");
- }
-
- // Build includes path
- PatternSet.NameEntry includes = javac.createInclude();
-
- includes.setName(ctxt.getJavaPath());
- info.append(" include="+ ctxt.getJavaPath() + "\n" );
-
- BuildException be = null;
-
- try {
- if (ctxt.getOptions().getFork()) {
- javac.execute();
- } else {
- synchronized(javacLock) {
- javac.execute();
- }
- }
- } catch (BuildException e) {
- be = e;
- log.error(Localizer.getMessage("jsp.error.javac"), e);
- log.error(Localizer.getMessage("jsp.error.javac.env") +
info.toString());
- }
-
- errorReport.append(logger.getReport());
-
- // Stop capturing the System.err output for this thread
- String errorCapture = SystemLogHandler.unsetThread();
- if (errorCapture != null) {
- errorReport.append(System.getProperty("line.separator"));
- errorReport.append(errorCapture);
- }
-
- if (!ctxt.keepGenerated()) {
- File javaFile = new File(javaFileName);
- javaFile.delete();
- }
-
- if (be != null) {
- String errorReportString = errorReport.toString();
- log.error(Localizer.getMessage("jsp.error.compilation",
javaFileName, errorReportString));
- JavacErrorDetail[] javacErrors = ErrorDispatcher.parseJavacErrors(
- errorReportString, javaFileName, pageNodes);
- if (javacErrors != null) {
- errDispatcher.javacError(javacErrors);
- } else {
- errDispatcher.javacError(errorReportString, be);
- }
- }
-
- if( log.isDebugEnabled() ) {
- long t2 = System.currentTimeMillis();
- log.debug("Compiled " + ctxt.getServletJavaFileName() + "
"
- + (t2-t1) + "ms");
- }
-
- logger = null;
- project = null;
-
- if (ctxt.isPrototypeMode()) {
- return;
- }
-
- // JSR45 Support
- if (! options.isSmapSuppressed()) {
- SmapUtil.installSmap(smap);
- }
- }
-
-
- private String quotePathList(String list) {
- StringBuffer result = new StringBuffer(list.length() + 10);
- StringTokenizer st = new StringTokenizer(list, File.pathSeparator);
- while (st.hasMoreTokens()) {
- String token = st.nextToken();
- if (token.indexOf(' ') == -1) {
- result.append(token);
- } else {
- result.append('\"');
- result.append(token);
- result.append('\"');
- }
- if (st.hasMoreTokens()) {
- result.append(File.pathSeparatorChar);
- }
- }
- return result.toString();
- }
-
-
- protected static class SystemLogHandler extends PrintStream {
-
-
- // ----------------------------------------------------------- Constructors
-
-
- /**
- * Construct the handler to capture the output of the given steam.
- */
- public SystemLogHandler(PrintStream wrapped) {
- super(wrapped);
- this.wrapped = wrapped;
- }
-
-
- // ----------------------------------------------------- Instance Variables
-
-
- /**
- * Wrapped PrintStream.
- */
- protected PrintStream wrapped = null;
-
-
- /**
- * Thread <-> PrintStream associations.
- */
- protected static ThreadLocal streams = new ThreadLocal();
-
-
- /**
- * Thread <-> ByteArrayOutputStream associations.
- */
- protected static ThreadLocal data = new ThreadLocal();
-
-
- // --------------------------------------------------------- Public Methods
-
-
- public PrintStream getWrapped() {
- return wrapped;
- }
-
- /**
- * Start capturing thread's output.
- */
- public static void setThread() {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- data.set(baos);
- streams.set(new PrintStream(baos));
- }
-
-
- /**
- * Stop capturing thread's output and return captured data as a String.
- */
- public static String unsetThread() {
- ByteArrayOutputStream baos =
- (ByteArrayOutputStream) data.get();
- if (baos == null) {
- return null;
- }
- streams.set(null);
- data.set(null);
- return baos.toString();
- }
-
-
- // ------------------------------------------------------ Protected Methods
-
-
- /**
- * Find PrintStream to which the output must be written to.
- */
- protected PrintStream findStream() {
- PrintStream ps = (PrintStream) streams.get();
- if (ps == null) {
- ps = wrapped;
- }
- return ps;
- }
-
-
- // ---------------------------------------------------- PrintStream Methods
-
-
- public void flush() {
- findStream().flush();
- }
-
- public void close() {
- findStream().close();
- }
-
- public boolean checkError() {
- return findStream().checkError();
- }
-
- protected void setError() {
- //findStream().setError();
- }
-
- public void write(int b) {
- findStream().write(b);
- }
-
- public void write(byte[] b)
- throws IOException {
- findStream().write(b);
- }
-
- public void write(byte[] buf, int off, int len) {
- findStream().write(buf, off, len);
- }
-
- public void print(boolean b) {
- findStream().print(b);
- }
-
- public void print(char c) {
- findStream().print(c);
- }
-
- public void print(int i) {
- findStream().print(i);
- }
-
- public void print(long l) {
- findStream().print(l);
- }
-
- public void print(float f) {
- findStream().print(f);
- }
-
- public void print(double d) {
- findStream().print(d);
- }
-
- public void print(char[] s) {
- findStream().print(s);
- }
-
- public void print(String s) {
- findStream().print(s);
- }
-
- public void print(Object obj) {
- findStream().print(obj);
- }
-
- public void println() {
- findStream().println();
- }
-
- public void println(boolean x) {
- findStream().println(x);
- }
-
- public void println(char x) {
- findStream().println(x);
- }
-
- public void println(int x) {
- findStream().println(x);
- }
-
- public void println(long x) {
- findStream().println(x);
- }
-
- public void println(float x) {
- findStream().println(x);
- }
-
- public void println(double x) {
- findStream().println(x);
- }
-
- public void println(char[] x) {
- findStream().println(x);
- }
-
- public void println(String x) {
- findStream().println(x);
- }
-
- public void println(Object x) {
- findStream().println(x);
- }
-
- }
-
-}
Modified: trunk/java/org/apache/jasper/compiler/JspConfig.java
===================================================================
--- trunk/java/org/apache/jasper/compiler/JspConfig.java 2009-06-11 11:11:18 UTC (rev
1104)
+++ trunk/java/org/apache/jasper/compiler/JspConfig.java 2009-06-11 12:29:25 UTC (rev
1105)
@@ -71,8 +71,6 @@
public class JspConfig {
- private static final String WEB_XML = "/WEB-INF/web.xml";
-
// Logger
private Logger log = Logger.getLogger(JspConfig.class);
@@ -91,157 +89,6 @@
this.ctxt = ctxt;
}
- private double getVersion(TreeNode webApp) {
- String v = webApp.findAttribute("version");
- if (v != null) {
- try {
- return Double.parseDouble(v);
- } catch (NumberFormatException e) {
- }
- }
- return 2.3;
- }
-
- private void processWebDotXml(ServletContext ctxt) throws JasperException {
-
- InputStream is = null;
-
- try {
- URL uri = ctxt.getResource(WEB_XML);
- if (uri == null) {
- // no web.xml
- return;
- }
-
- is = uri.openStream();
- InputSource ip = new InputSource(is);
- ip.setSystemId(uri.toExternalForm());
-
- ParserUtils pu = new ParserUtils();
- TreeNode webApp = pu.parseXMLDocument(WEB_XML, ip);
-
- if (webApp == null
- || getVersion(webApp) < 2.4) {
- defaultIsELIgnored = "true";
- return;
- }
- TreeNode jspConfig = webApp.findChild("jsp-config");
- if (jspConfig == null) {
- return;
- }
-
- jspProperties = new ArrayList<JspPropertyGroup>();
- Iterator jspPropertyList =
jspConfig.findChildren("jsp-property-group");
- while (jspPropertyList.hasNext()) {
-
- TreeNode element = (TreeNode) jspPropertyList.next();
- Iterator list = element.findChildren();
-
- ArrayList<String> urlPatterns = new ArrayList<String>();
- String pageEncoding = null;
- String scriptingInvalid = null;
- String elIgnored = null;
- String isXml = null;
- ArrayList<String> includePrelude = new ArrayList<String>();
- ArrayList<String> includeCoda = new ArrayList<String>();
- String deferredSyntaxAllowedAsLiteral = null;
- String trimDirectiveWhitespaces = null;
-
- while (list.hasNext()) {
-
- element = (TreeNode) list.next();
- String tname = element.getName();
-
- if ("url-pattern".equals(tname))
- urlPatterns.add( element.getBody() );
- else if ("page-encoding".equals(tname))
- pageEncoding = element.getBody();
- else if ("is-xml".equals(tname))
- isXml = element.getBody();
- else if ("el-ignored".equals(tname))
- elIgnored = element.getBody();
- else if ("scripting-invalid".equals(tname))
- scriptingInvalid = element.getBody();
- else if ("include-prelude".equals(tname))
- includePrelude.add(element.getBody());
- else if ("include-coda".equals(tname))
- includeCoda.add(element.getBody());
- else if
("deferred-syntax-allowed-as-literal".equals(tname))
- deferredSyntaxAllowedAsLiteral = element.getBody();
- else if ("trim-directive-whitespaces".equals(tname))
- trimDirectiveWhitespaces = element.getBody();
- }
-
- if (urlPatterns.size() == 0) {
- continue;
- }
-
- // Add one JspPropertyGroup for each URL Pattern. This makes
- // the matching logic easier.
- for( int p = 0; p < urlPatterns.size(); p++ ) {
- String urlPattern = urlPatterns.get(p);
- String path = null;
- String extension = null;
-
- if (urlPattern.indexOf('*') < 0) {
- // Exact match
- path = urlPattern;
- } else {
- int i = urlPattern.lastIndexOf('/');
- String file;
- if (i >= 0) {
- path = urlPattern.substring(0,i+1);
- file = urlPattern.substring(i+1);
- } else {
- file = urlPattern;
- }
-
- // pattern must be "*", or of the form
"*.jsp"
- if (file.equals("*")) {
- extension = "*";
- } else if (file.startsWith("*.")) {
- extension = file.substring(file.indexOf('.')+1);
- }
-
- // The url patterns are reconstructed as the follwoing:
- // path != null, extension == null: / or /foo/bar.ext
- // path == null, extension != null: *.ext
- // path != null, extension == "*": /foo/*
- boolean isStar = "*".equals(extension);
- if ((path == null && (extension == null || isStar))
- || (path != null && !isStar)) {
- log.warn(Localizer.getMessage(
-
"jsp.warning.bad.urlpattern.propertygroup",
- urlPattern));
- continue;
- }
- }
-
- JspProperty property = new JspProperty(isXml,
- elIgnored,
- scriptingInvalid,
- pageEncoding,
- includePrelude,
- includeCoda,
- deferredSyntaxAllowedAsLiteral,
- trimDirectiveWhitespaces);
- JspPropertyGroup propertyGroup =
- new JspPropertyGroup(path, extension, property);
-
- jspProperties.add(propertyGroup);
- }
- }
- } catch (Exception ex) {
- throw new JasperException(ex);
- } finally {
- if (is != null) {
- try {
- is.close();
- } catch (Throwable t) {}
- }
- }
- }
-
private void init() throws JasperException {
if (!initialized) {
Deleted: trunk/java/org/apache/jasper/compiler/TldLocationsCache.java
===================================================================
--- trunk/java/org/apache/jasper/compiler/TldLocationsCache.java 2009-06-11 11:11:18 UTC
(rev 1104)
+++ trunk/java/org/apache/jasper/compiler/TldLocationsCache.java 2009-06-11 12:29:25 UTC
(rev 1105)
@@ -1,547 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- *
http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.jasper.compiler;
-
-import java.io.InputStream;
-import java.net.JarURLConnection;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.net.URLClassLoader;
-import java.net.URLConnection;
-import java.util.Enumeration;
-import java.util.Hashtable;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Set;
-import java.util.StringTokenizer;
-import java.util.jar.JarEntry;
-import java.util.jar.JarFile;
-import org.xml.sax.InputSource;
-
-import javax.servlet.ServletContext;
-
-import org.apache.jasper.Constants;
-import org.apache.jasper.JasperException;
-import org.apache.jasper.xmlparser.ParserUtils;
-import org.apache.jasper.xmlparser.TreeNode;
-import org.jboss.logging.Logger;
-import org.jboss.logging.Logger;
-
-/**
- * A container for all tag libraries that are defined "globally"
- * for the web application.
- *
- * Tag Libraries can be defined globally in one of two ways:
- * 1. Via <taglib> elements in web.xml:
- * the uri and location of the tag-library are specified in
- * the <taglib> element.
- * 2. Via packaged jar files that contain .tld files
- * within the META-INF directory, or some subdirectory
- * of it. The taglib is 'global' if it has the <uri>
- * element defined.
- *
- * A mapping between the taglib URI and its associated TaglibraryInfoImpl
- * is maintained in this container.
- * Actually, that's what we'd like to do. However, because of the
- * way the classes TagLibraryInfo and TagInfo have been defined,
- * it is not currently possible to share an instance of TagLibraryInfo
- * across page invocations. A bug has been submitted to the spec lead.
- * In the mean time, all we do is save the 'location' where the
- * TLD associated with a taglib URI can be found.
- *
- * When a JSP page has a taglib directive, the mappings in this container
- * are first searched (see method getLocation()).
- * If a mapping is found, then the location of the TLD is returned.
- * If no mapping is found, then the uri specified
- * in the taglib directive is to be interpreted as the location for
- * the TLD of this tag library.
- *
- * @author Pierre Delisle
- * @author Jan Luehe
- */
-
-public class TldLocationsCache {
-
- // Logger
- private Logger log = Logger.getLogger(TldLocationsCache.class);
-
- /**
- * The types of URI one may specify for a tag library
- */
- public static final int ABS_URI = 0;
- public static final int ROOT_REL_URI = 1;
- public static final int NOROOT_REL_URI = 2;
-
- private static final String WEB_XML = "/WEB-INF/web.xml";
- private static final String FILE_PROTOCOL = "file:";
- private static final String JAR_FILE_SUFFIX = ".jar";
-
- // Names of JARs that are known not to contain any TLDs
- private static HashSet<String> noTldJars;
-
- /**
- * The mapping of the 'global' tag library URI to the location (resource
- * path) of the TLD associated with that tag library. The location is
- * returned as a String array:
- * [0] The location
- * [1] If the location is a jar file, this is the location of the tld.
- */
- private Hashtable mappings;
-
- private boolean initialized;
- private ServletContext ctxt;
- private boolean redeployMode;
-
- //*********************************************************************
- // Constructor and Initilizations
-
- /*
- * Initializes the set of JARs that are known not to contain any TLDs
- */
- static {
- noTldJars = new HashSet<String>();
- // Bootstrap JARs
- noTldJars.add("bootstrap.jar");
- noTldJars.add("commons-daemon.jar");
- noTldJars.add("tomcat-juli.jar");
- // Main JARs
- noTldJars.add("annotations-api.jar");
- noTldJars.add("catalina.jar");
- noTldJars.add("catalina-ant.jar");
- noTldJars.add("catalina-ha.jar");
- noTldJars.add("catalina-tribes.jar");
- noTldJars.add("el-api.jar");
- noTldJars.add("jasper.jar");
- noTldJars.add("jasper-el.jar");
- noTldJars.add("jasper-jdt.jar");
- noTldJars.add("jsp-api.jar");
- noTldJars.add("servlet-api.jar");
- noTldJars.add("tomcat-coyote.jar");
- noTldJars.add("tomcat-dbcp.jar");
- // i18n JARs
- noTldJars.add("tomcat-i18n-en.jar");
- noTldJars.add("tomcat-i18n-es.jar");
- noTldJars.add("tomcat-i18n-fr.jar");
- noTldJars.add("tomcat-i18n-ja.jar");
- // Misc JARs not included with Tomcat
- noTldJars.add("ant.jar");
- noTldJars.add("commons-dbcp.jar");
- noTldJars.add("commons-beanutils.jar");
- noTldJars.add("commons-fileupload-1.0.jar");
- noTldJars.add("commons-pool.jar");
- noTldJars.add("commons-digester.jar");
- noTldJars.add("commons-logging.jar");
- noTldJars.add("commons-collections.jar");
- noTldJars.add("jmx.jar");
- noTldJars.add("jmx-tools.jar");
- noTldJars.add("xercesImpl.jar");
- noTldJars.add("xmlParserAPIs.jar");
- noTldJars.add("xml-apis.jar");
- // JARs from J2SE runtime
- noTldJars.add("sunjce_provider.jar");
- noTldJars.add("ldapsec.jar");
- noTldJars.add("localedata.jar");
- noTldJars.add("dnsns.jar");
- noTldJars.add("tools.jar");
- noTldJars.add("sunpkcs11.jar");
- }
-
- public TldLocationsCache(ServletContext ctxt) {
- this(ctxt, true);
- }
-
- /** Constructor.
- *
- * @param ctxt the servlet context of the web application in which Jasper
- * is running
- * @param redeployMode if true, then the compiler will allow redeploying
- * a tag library from the same jar, at the expense of slowing down the
- * server a bit. Note that this may only work on JDK 1.3.1_01a and later,
- * because of JDK bug 4211817 fixed in this release.
- * If redeployMode is false, a faster but less capable mode will be used.
- */
- public TldLocationsCache(ServletContext ctxt, boolean redeployMode) {
- this.ctxt = ctxt;
- this.redeployMode = redeployMode;
- mappings = new Hashtable();
- initialized = false;
- }
-
- /**
- * Sets the list of JARs that are known not to contain any TLDs.
- *
- * @param jarNames List of comma-separated names of JAR files that are
- * known not to contain any TLDs
- */
- public static void setNoTldJars(String jarNames) {
- if (jarNames != null) {
- noTldJars.clear();
- StringTokenizer tokenizer = new StringTokenizer(jarNames, ",");
- while (tokenizer.hasMoreElements()) {
- noTldJars.add(tokenizer.nextToken());
- }
- }
- }
-
- /**
- * Gets the 'location' of the TLD associated with the given taglib
'uri'.
- *
- * Returns null if the uri is not associated with any tag library 'exposed'
- * in the web application. A tag library is 'exposed' either explicitly in
- * web.xml or implicitly via the uri tag in the TLD of a taglib deployed
- * in a jar file (WEB-INF/lib).
- *
- * @param uri The taglib uri
- *
- * @return An array of two Strings: The first element denotes the real
- * path to the TLD. If the path to the TLD points to a jar file, then the
- * second element denotes the name of the TLD entry in the jar file.
- * Returns null if the uri is not associated with any tag library 'exposed'
- * in the web application.
- */
- public String[] getLocation(String uri) throws JasperException {
- if (!initialized) {
- init();
- }
- return (String[]) mappings.get(uri);
- }
-
- /**
- * Returns the type of a URI:
- * ABS_URI
- * ROOT_REL_URI
- * NOROOT_REL_URI
- */
- public static int uriType(String uri) {
- if (uri.indexOf(':') != -1) {
- return ABS_URI;
- } else if (uri.startsWith("/")) {
- return ROOT_REL_URI;
- } else {
- return NOROOT_REL_URI;
- }
- }
-
- private void init() throws JasperException {
- if (initialized) return;
- try {
- processWebDotXml();
- scanJars();
- processTldsInFileSystem("/WEB-INF/");
- initialized = true;
- } catch (Exception ex) {
- throw new JasperException(Localizer.getMessage(
- "jsp.error.internal.tldinit", ex.getMessage()));
- }
- }
-
- /*
- * Populates taglib map described in web.xml.
- */
- private void processWebDotXml() throws Exception {
-
- InputStream is = null;
-
- try {
- // Acquire input stream to web application deployment descriptor
- String altDDName = (String)ctxt.getAttribute(
- Constants.ALT_DD_ATTR);
- URL uri = null;
- if (altDDName != null) {
- try {
- uri = new URL(FILE_PROTOCOL+altDDName.replace('\\',
'/'));
- } catch (MalformedURLException e) {
- log.warn(Localizer.getMessage(
- "jsp.error.internal.filenotfound",
- altDDName));
- }
- } else {
- uri = ctxt.getResource(WEB_XML);
- if (uri == null) {
- log.warn(Localizer.getMessage(
- "jsp.error.internal.filenotfound",
- WEB_XML));
- }
- }
-
- if (uri == null) {
- return;
- }
- is = uri.openStream();
- InputSource ip = new InputSource(is);
- ip.setSystemId(uri.toExternalForm());
-
- // Parse the web application deployment descriptor
- TreeNode webtld = null;
- // altDDName is the absolute path of the DD
- if (altDDName != null) {
- webtld = new ParserUtils().parseXMLDocument(altDDName, ip);
- } else {
- webtld = new ParserUtils().parseXMLDocument(WEB_XML, ip);
- }
-
- // Allow taglib to be an element of the root or jsp-config (JSP2.0)
- TreeNode jspConfig = webtld.findChild("jsp-config");
- if (jspConfig != null) {
- webtld = jspConfig;
- }
- Iterator taglibs = webtld.findChildren("taglib");
- while (taglibs.hasNext()) {
-
- // Parse the next <taglib> element
- TreeNode taglib = (TreeNode) taglibs.next();
- String tagUri = null;
- String tagLoc = null;
- TreeNode child = taglib.findChild("taglib-uri");
- if (child != null)
- tagUri = child.getBody();
- child = taglib.findChild("taglib-location");
- if (child != null)
- tagLoc = child.getBody();
-
- // Save this location if appropriate
- if (tagLoc == null)
- continue;
- if (uriType(tagLoc) == NOROOT_REL_URI)
- tagLoc = "/WEB-INF/" + tagLoc;
- String tagLoc2 = null;
- if (tagLoc.endsWith(JAR_FILE_SUFFIX)) {
- tagLoc = ctxt.getResource(tagLoc).toString();
- tagLoc2 = "META-INF/taglib.tld";
- }
- mappings.put(tagUri, new String[] { tagLoc, tagLoc2 });
- }
- } finally {
- if (is != null) {
- try {
- is.close();
- } catch (Throwable t) {}
- }
- }
- }
-
- /**
- * Scans the given JarURLConnection for TLD files located in META-INF
- * (or a subdirectory of it), adding an implicit map entry to the taglib
- * map for any TLD that has a <uri> element.
- *
- * @param conn The JarURLConnection to the JAR file to scan
- * @param ignore true if any exceptions raised when processing the given
- * JAR should be ignored, false otherwise
- */
- private void scanJar(JarURLConnection conn, boolean ignore)
- throws JasperException {
-
- JarFile jarFile = null;
- String resourcePath = conn.getJarFileURL().toString();
- try {
- if (redeployMode) {
- conn.setUseCaches(false);
- }
- jarFile = conn.getJarFile();
- Enumeration entries = jarFile.entries();
- while (entries.hasMoreElements()) {
- JarEntry entry = (JarEntry) entries.nextElement();
- String name = entry.getName();
- if (!name.startsWith("META-INF/")) continue;
- if (!name.endsWith(".tld")) continue;
- InputStream stream = jarFile.getInputStream(entry);
- try {
- String uri = getUriFromTld(resourcePath, stream);
- // Add implicit map entry only if its uri is not already
- // present in the map
- if (uri != null && mappings.get(uri) == null) {
- mappings.put(uri, new String[]{ resourcePath, name });
- }
- } finally {
- if (stream != null) {
- try {
- stream.close();
- } catch (Throwable t) {
- // do nothing
- }
- }
- }
- }
- } catch (Exception ex) {
- if (!redeployMode) {
- // if not in redeploy mode, close the jar in case of an error
- if (jarFile != null) {
- try {
- jarFile.close();
- } catch (Throwable t) {
- // ignore
- }
- }
- }
- if (!ignore) {
- throw new JasperException(ex);
- }
- } finally {
- if (redeployMode) {
- // if in redeploy mode, always close the jar
- if (jarFile != null) {
- try {
- jarFile.close();
- } catch (Throwable t) {
- // ignore
- }
- }
- }
- }
- }
-
- /*
- * Searches the filesystem under /WEB-INF for any TLD files, and adds
- * an implicit map entry to the taglib map for any TLD that has a <uri>
- * element.
- */
- private void processTldsInFileSystem(String startPath)
- throws Exception {
-
- Set dirList = ctxt.getResourcePaths(startPath);
- if (dirList != null) {
- Iterator it = dirList.iterator();
- while (it.hasNext()) {
- String path = (String) it.next();
- if (path.endsWith("/")) {
- processTldsInFileSystem(path);
- }
- if (!path.endsWith(".tld")) {
- continue;
- }
- InputStream stream = ctxt.getResourceAsStream(path);
- String uri = null;
- try {
- uri = getUriFromTld(path, stream);
- } finally {
- if (stream != null) {
- try {
- stream.close();
- } catch (Throwable t) {
- // do nothing
- }
- }
- }
- // Add implicit map entry only if its uri is not already
- // present in the map
- if (uri != null && mappings.get(uri) == null) {
- mappings.put(uri, new String[] { path, null });
- }
- }
- }
- }
-
- /*
- * Returns the value of the uri element of the given TLD, or null if the
- * given TLD does not contain any such element.
- */
- private String getUriFromTld(String resourcePath, InputStream in)
- throws JasperException
- {
- // Parse the tag library descriptor at the specified resource path
- TreeNode tld = new ParserUtils().parseXMLDocument(resourcePath, in);
- TreeNode uri = tld.findChild("uri");
- if (uri != null) {
- String body = uri.getBody();
- if (body != null)
- return body;
- }
-
- return null;
- }
-
- /*
- * Scans all JARs accessible to the webapp's classloader and its
- * parent classloaders for TLDs.
- *
- * The list of JARs always includes the JARs under WEB-INF/lib, as well as
- * all shared JARs in the classloader delegation chain of the webapp's
- * classloader.
- *
- * Considering JARs in the classloader delegation chain constitutes a
- * Tomcat-specific extension to the TLD search
- * order defined in the JSP spec. It allows tag libraries packaged as JAR
- * files to be shared by web applications by simply dropping them in a
- * location that all web applications have access to (e.g.,
- * <CATALINA_HOME>/common/lib).
- *
- * The set of shared JARs to be scanned for TLDs is narrowed down by
- * the <tt>noTldJars</tt> class variable, which contains the names of
JARs
- * that are known not to contain any TLDs.
- */
- private void scanJars() throws Exception {
-
- ClassLoader webappLoader
- = Thread.currentThread().getContextClassLoader();
- ClassLoader loader = webappLoader;
-
- while (loader != null) {
- if (loader instanceof URLClassLoader) {
- URL[] urls = ((URLClassLoader) loader).getURLs();
- for (int i=0; i<urls.length; i++) {
- URLConnection conn = urls[i].openConnection();
- if (conn instanceof JarURLConnection) {
- if (needScanJar(loader, webappLoader,
- ((JarURLConnection)
conn).getJarFile().getName())) {
- scanJar((JarURLConnection) conn, true);
- }
- } else {
- String urlStr = urls[i].toString();
- if (urlStr.startsWith(FILE_PROTOCOL)
- && urlStr.endsWith(JAR_FILE_SUFFIX)
- && needScanJar(loader, webappLoader, urlStr)) {
- URL jarURL = new URL("jar:" + urlStr +
"!/");
- scanJar((JarURLConnection) jarURL.openConnection(),
- true);
- }
- }
- }
- }
-
- loader = loader.getParent();
- }
- }
-
- /*
- * Determines if the JAR file with the given <tt>jarPath</tt> needs to
be
- * scanned for TLDs.
- *
- * @param loader The current classloader in the parent chain
- * @param webappLoader The webapp classloader
- * @param jarPath The JAR file path
- *
- * @return TRUE if the JAR file identified by <tt>jarPath</tt> needs to
be
- * scanned for TLDs, FALSE otherwise
- */
- private boolean needScanJar(ClassLoader loader, ClassLoader webappLoader,
- String jarPath) {
- if (loader == webappLoader) {
- // JARs under WEB-INF/lib must be scanned unconditionally according
- // to the spec.
- return true;
- } else {
- String jarName = jarPath;
- int slash = jarPath.lastIndexOf('/');
- if (slash >= 0) {
- jarName = jarPath.substring(slash + 1);
- }
- return (!noTldJars.contains(jarName));
- }
- }
-}