FileDocCategorySizeDatePackage
JspCompilationContext.javaAPI DocApache Tomcat 6.0.1423541Fri Jul 20 04:20:32 BST 2007org.apache.jasper

JspCompilationContext

public class JspCompilationContext extends Object
A place holder for various things that are used through out the JSP engine. This is a per-request/per-context data structure. Some of the instance variables are set at different points. Most of the path-related stuff is here - mangling names, versions, dirs, loading resources and dealing with uris.
author
Anil K. Vijendran
author
Harish Prabandham
author
Pierre Delisle
author
Costin Manolache
author
Kin-man Chung

Fields Summary
protected org.apache.juli.logging.Log
log
protected Map
tagFileJarUrls
protected boolean
isPackagedTagFile
protected String
className
protected String
jspUri
protected boolean
isErrPage
protected String
basePackageName
protected String
derivedPackageName
protected String
servletJavaFileName
protected String
javaPath
protected String
classFileName
protected String
contentType
protected org.apache.jasper.compiler.ServletWriter
writer
protected Options
options
protected org.apache.jasper.servlet.JspServletWrapper
jsw
protected org.apache.jasper.compiler.Compiler
jspCompiler
protected String
classPath
protected String
baseURI
protected String
outputDir
protected ServletContext
context
protected URLClassLoader
loader
protected org.apache.jasper.compiler.JspRuntimeContext
rctxt
protected int
removed
protected URLClassLoader
jspLoader
protected URL
baseUrl
protected Class
servletClass
protected boolean
isTagFile
protected boolean
protoTypeMode
protected javax.servlet.jsp.tagext.TagInfo
tagInfo
protected URL
tagFileJarUrl
static Object
outputDirLock
Constructors Summary
public JspCompilationContext(String jspUri, boolean isErrPage, Options options, ServletContext context, org.apache.jasper.servlet.JspServletWrapper jsw, org.apache.jasper.compiler.JspRuntimeContext rctxt)


    // jspURI _must_ be relative to the context
      
                                  
                                  
                                  
                                  
                                   

        this.jspUri = canonicalURI(jspUri);
        this.isErrPage = isErrPage;
        this.options = options;
        this.jsw = jsw;
        this.context = context;

        this.baseURI = jspUri.substring(0, jspUri.lastIndexOf('/") + 1);
        // hack fix for resolveRelativeURI
        if (baseURI == null) {
            baseURI = "/";
        } else if (baseURI.charAt(0) != '/") {
            // strip the basde slash since it will be combined with the
            // uriBase to generate a file
            baseURI = "/" + baseURI;
        }
        if (baseURI.charAt(baseURI.length() - 1) != '/") {
            baseURI += '/";
        }

        this.rctxt = rctxt;
        this.tagFileJarUrls = new HashMap<String, URL>();
        this.basePackageName = Constants.JSP_PACKAGE_NAME;
    
public JspCompilationContext(String tagfile, javax.servlet.jsp.tagext.TagInfo tagInfo, Options options, ServletContext context, org.apache.jasper.servlet.JspServletWrapper jsw, org.apache.jasper.compiler.JspRuntimeContext rctxt, URL tagFileJarUrl)

        this(tagfile, false, options, context, jsw, rctxt);
        this.isTagFile = true;
        this.tagInfo = tagInfo;
        this.tagFileJarUrl = tagFileJarUrl;
        if (tagFileJarUrl != null) {
            isPackagedTagFile = true;
        }
    
Methods Summary
protected static final java.lang.StringcanonicalURI(java.lang.String s)

       if (s == null) return null;
       StringBuffer result = new StringBuffer();
       final int len = s.length();
       int pos = 0;
       while (pos < len) {
           char c = s.charAt(pos);
           if ( isPathSeparator(c) ) {
               /*
                * multiple path separators.
                * 'foo///bar' -> 'foo/bar'
                */
               while (pos+1 < len && isPathSeparator(s.charAt(pos+1))) {
                   ++pos;
               }

               if (pos+1 < len && s.charAt(pos+1) == '.") {
                   /*
                    * a single dot at the end of the path - we are done.
                    */
                   if (pos+2 >= len) break;

                   switch (s.charAt(pos+2)) {
                       /*
                        * self directory in path
                        * foo/./bar -> foo/bar
                        */
                   case '/":
                   case '\\":
                       pos += 2;
                       continue;

                       /*
                        * two dots in a path: go back one hierarchy.
                        * foo/bar/../baz -> foo/baz
                        */
                   case '.":
                       // only if we have exactly _two_ dots.
                       if (pos+3 < len && isPathSeparator(s.charAt(pos+3))) {
                           pos += 3;
                           int separatorPos = result.length()-1;
                           while (separatorPos >= 0 && 
                                  ! isPathSeparator(result
                                                    .charAt(separatorPos))) {
                               --separatorPos;
                           }
                           if (separatorPos >= 0)
                               result.setLength(separatorPos);
                           continue;
                       }
                   }
               }
           }
           result.append(c);
           ++pos;
       }
       return result.toString();
    
public voidcheckOutputDir()


       
        if (outputDir != null) {
            if (!(new File(outputDir)).exists()) {
                makeOutputDir();
            }
        } else {
            createOutputDir();
        }
    
public voidcompile()

        createCompiler();
        if (isPackagedTagFile || jspCompiler.isOutDated()) {
            try {
                jspCompiler.removeGeneratedFiles();
                jspLoader = null;
                jspCompiler.compile();
                jsw.setReload(true);
                jsw.setCompilationException(null);
            } catch (JasperException ex) {
                // Cache compilation exception
                jsw.setCompilationException(ex);
                throw ex;
            } catch (Exception ex) {
                JasperException je = new JasperException(
                            Localizer.getMessage("jsp.error.unable.compile"),
                            ex);
                // Cache compilation exception
                jsw.setCompilationException(je);
                throw je;
            }
        }
    
protected org.apache.jasper.compiler.CompilercreateCompiler(java.lang.String className)

        Compiler compiler = null; 
        try {
            compiler = (Compiler) Class.forName(className).newInstance();
        } catch (InstantiationException e) {
            log.warn(Localizer.getMessage("jsp.error.compiler"), e);
        } catch (IllegalAccessException e) {
            log.warn(Localizer.getMessage("jsp.error.compiler"), e);
        } catch (NoClassDefFoundError e) {
            if (log.isDebugEnabled()) {
                log.debug(Localizer.getMessage("jsp.error.compiler"), e);
            }
        } catch (ClassNotFoundException e) {
            if (log.isDebugEnabled()) {
                log.debug(Localizer.getMessage("jsp.error.compiler"), e);
            }
        }
        return compiler;
    
public org.apache.jasper.compiler.CompilercreateCompiler()
Create a "Compiler" object based on some init param data. This is not done yet. Right now we're just hardcoding the actual compilers that are created.

        if (jspCompiler != null ) {
            return jspCompiler;
        }
        jspCompiler = null;
        if (options.getCompilerClassName() != null) {
            jspCompiler = createCompiler(options.getCompilerClassName());
        } else {
            if (options.getCompiler() == null) {
                jspCompiler = createCompiler("org.apache.jasper.compiler.JDTCompiler");
                if (jspCompiler == null) {
                    jspCompiler = createCompiler("org.apache.jasper.compiler.AntCompiler");
                }
            } else {
                jspCompiler = createCompiler("org.apache.jasper.compiler.AntCompiler");
                if (jspCompiler == null) {
                    jspCompiler = createCompiler("org.apache.jasper.compiler.JDTCompiler");
                }
            }
        }
        if (jspCompiler == null) {
            throw new IllegalStateException(Localizer.getMessage("jsp.error.compiler"));
        }
        jspCompiler.init(this, jsw);
        return jspCompiler;
    
protected voidcreateOutputDir()

        String path = null;
        if (isTagFile()) {
	    String tagName = tagInfo.getTagClassName();
            path = tagName.replace('.", '/");
	    path = path.substring(0, path.lastIndexOf('/"));
        } else {
            path = getServletPackageName().replace('.", '/");
	}

            // Append servlet or tag handler path to scratch dir
            try {
                baseUrl = options.getScratchDir().toURL();
                String outUrlString = baseUrl.toString() + '/" + path;
                URL outUrl = new URL(outUrlString);
                outputDir = outUrl.getFile() + File.separator;
                if (!makeOutputDir()) {
                    throw new IllegalStateException(Localizer.getMessage("jsp.error.outputfolder"));
                }
            } catch (MalformedURLException e) {
                throw new IllegalStateException(Localizer.getMessage("jsp.error.outputfolder"), e);
            }
    
public java.lang.StringgetClassFileName()

        if (classFileName == null) {
            classFileName = getOutputDir() + getServletClassName() + ".class";
        }
        return classFileName;
    
public java.lang.ClassLoadergetClassLoader()
What class loader to use for loading classes while compiling this JSP?

        if( loader != null )
            return loader;
        return rctxt.getParentClassLoader();
    
public java.lang.StringgetClassPath()
The classpath that is passed off to the Java compiler.

        if( classPath != null )
            return classPath;
        return rctxt.getClassPath();
    
public org.apache.jasper.compiler.CompilergetCompiler()

        return jspCompiler;
    
public java.lang.StringgetContentType()
Get the content type of this JSP. Content type includes content type and encoding.

        return contentType;
    
protected java.lang.StringgetDerivedPackageName()

        if (derivedPackageName == null) {
            int iSep = jspUri.lastIndexOf('/");
            derivedPackageName = (iSep > 0) ?
                    JspUtil.makeJavaPackage(jspUri.substring(1,iSep)) : "";
        }
        return derivedPackageName;
    
public java.lang.StringgetJavaPath()
Path of the Java file relative to the work directory.


        if (javaPath != null) {
            return javaPath;
        }

        if (isTagFile()) {
	    String tagName = tagInfo.getTagClassName();
            javaPath = tagName.replace('.", '/") + ".java";
        } else {
            javaPath = getServletPackageName().replace('.", '/") + '/" +
                       getServletClassName() + ".java";
	}
        return javaPath;
    
public java.lang.StringgetJspFile()
Path of the JSP URI. Note that this is not a file name. This is the context rooted URI of the JSP file.

        return jspUri;
    
public java.lang.ClassLoadergetJspLoader()

        if( jspLoader == null ) {
            jspLoader = new JasperLoader
            (new URL[] {baseUrl},
                    getClassLoader(),
                    rctxt.getPermissionCollection(),
                    rctxt.getCodeSource());
        }
        return jspLoader;
    
public OptionsgetOptions()
Get hold of the Options object for this context.

        return options;
    
public java.lang.StringgetOutputDir()
The output directory to generate code into. The output directory is make up of the scratch directory, which is provide in Options, plus the directory derived from the package name.

	if (outputDir == null) {
	    createOutputDir();
	}

        return outputDir;
    
public java.lang.StringgetRealPath(java.lang.String path)
Gets the actual path of a URI relative to the context of the compilation.

        if (context != null) {
            return context.getRealPath(path);
        }
        return path;
    
public java.net.URLgetResource(java.lang.String res)

        return context.getResource(canonicalURI(res));
    
public java.io.InputStreamgetResourceAsStream(java.lang.String res)
Gets a resource as a stream, relative to the meanings of this context's implementation.

return
a null if the resource cannot be found or represented as an InputStream.

        return context.getResourceAsStream(canonicalURI(res));
    
public java.util.SetgetResourcePaths(java.lang.String path)

        return context.getResourcePaths(canonicalURI(path));
    
public org.apache.jasper.compiler.JspRuntimeContextgetRuntimeContext()

        return rctxt;
    
public java.lang.StringgetServletClassName()
Just the class name (does not include package name) of the generated class.


        if (className != null) {
            return className;
        }

        if (isTagFile) {
            className = tagInfo.getTagClassName();
            int lastIndex = className.lastIndexOf('.");
            if (lastIndex != -1) {
                className = className.substring(lastIndex + 1);
            }
        } else {
            int iSep = jspUri.lastIndexOf('/") + 1;
            className = JspUtil.makeJavaIdentifier(jspUri.substring(iSep));
        }
        return className;
    
public javax.servlet.ServletContextgetServletContext()

        return context;
    
public java.lang.StringgetServletJavaFileName()
Full path name of the Java file into which the servlet is being generated.

        if (servletJavaFileName == null) {
            servletJavaFileName = getOutputDir() + getServletClassName() + ".java";
        }
        return servletJavaFileName;
    
public java.lang.StringgetServletPackageName()
Package name for the generated class is make up of the base package name, which is user settable, and the derived package name. The derived package name directly mirrors the file heirachy of the JSP page.

        if (isTagFile()) {
            String className = tagInfo.getTagClassName();
            int lastIndex = className.lastIndexOf('.");
            String pkgName = "";
            if (lastIndex != -1) {
                pkgName = className.substring(0, lastIndex);
            }
            return pkgName;
        } else {
            String dPackageName = getDerivedPackageName();
            if (dPackageName.length() == 0) {
                return basePackageName;
            }
            return basePackageName + '." + getDerivedPackageName();
        }
    
public java.net.URLgetTagFileJarUrl(java.lang.String tagFile)
Returns the tag-file-name-to-JAR-file map of this compilation unit, which maps tag file names to the JAR files in which the tag files are packaged. The map is populated when parsing the tag-file elements of the TLDs of any imported taglibs.

        return this.tagFileJarUrls.get(tagFile);
    
public java.net.URLgetTagFileJarUrl()
Returns the JAR file in which the tag file for which this JspCompilationContext was created is packaged, or null if this JspCompilationContext does not correspond to a tag file, or if the corresponding tag file is not packaged in a JAR.

        return this.tagFileJarUrl;
    
public javax.servlet.jsp.tagext.TagInfogetTagInfo()

        return tagInfo;
    
public java.lang.String[]getTldLocation(java.lang.String uri)
Gets the 'location' of the TLD associated with the given 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 given uri is not associated with any tag library 'exposed' in the web application.

        String[] location = 
            getOptions().getTldLocationsCache().getLocation(uri);
        return location;
    
public org.apache.jasper.compiler.ServletWritergetWriter()
Where is the servlet being generated?

        return writer;
    
public voidincrementRemoved()

        if (removed == 0 && rctxt != null) {
            rctxt.removeWrapper(jspUri);
        }
        removed++;
    
public booleanisErrorPage()
Are we processing something that has been declared as an errorpage?

        return isErrPage;
    
protected static final booleanisPathSeparator(char c)

       return (c == '/" || c == '\\");
    
public booleanisPrototypeMode()
True if we are compiling a tag file in prototype mode. ie we only generate codes with class for the tag handler with empty method bodies.

        return protoTypeMode;
    
public booleanisRemoved()

        if (removed > 1 ) {
            return true;
        }
        return false;
    
public booleanisTagFile()

        return isTagFile;
    
public booleankeepGenerated()
Are we keeping generated code around?

        return getOptions().getKeepGenerated();
    
public java.lang.Classload()

        try {
            getJspLoader();
            
            String name;
            if (isTagFile()) {
                name = tagInfo.getTagClassName();
            } else {
                name = getServletPackageName() + "." + getServletClassName();
            }
            servletClass = jspLoader.loadClass(name);
        } catch (ClassNotFoundException cex) {
            throw new JasperException(Localizer.getMessage("jsp.error.unable.load"),
                                      cex);
        } catch (Exception ex) {
            throw new JasperException(Localizer.getMessage("jsp.error.unable.compile"),
                                      ex);
        }
        removed = 0;
        return servletClass;
    
protected booleanmakeOutputDir()

        synchronized(outputDirLock) {
            File outDirFile = new File(outputDir);
            return (outDirFile.exists() || outDirFile.mkdirs());
        }
    
public java.lang.StringresolveRelativeUri(java.lang.String uri)
Get the full value of a URI relative to this compilations context uses current file as the base.

        // sometimes we get uri's massaged from File(String), so check for
        // a root directory deperator char
        if (uri.startsWith("/") || uri.startsWith(File.separator)) {
            return uri;
        } else {
            return baseURI + uri;
        }
    
public voidsetClassLoader(java.net.URLClassLoader loader)

        this.loader = loader;
    
public voidsetClassPath(java.lang.String classPath)
The classpath that is passed off to the Java compiler.

        this.classPath = classPath;
    
public voidsetContentType(java.lang.String contentType)

        this.contentType = contentType;
    
public voidsetErrorPage(boolean isErrPage)

        this.isErrPage = isErrPage;
    
public voidsetPrototypeMode(boolean pm)

        protoTypeMode = pm;
    
public voidsetServletClassName(java.lang.String className)

        this.className = className;
    
public voidsetServletPackageName(java.lang.String servletPackageName)
The package name into which the servlet class is generated.

        this.basePackageName = servletPackageName;
    
public voidsetTagFileJarUrl(java.lang.String tagFile, java.net.URL tagFileURL)

        this.tagFileJarUrls.put(tagFile, tagFileURL);
    
public voidsetTagInfo(javax.servlet.jsp.tagext.TagInfo tagi)

        tagInfo = tagi;
    
public voidsetWriter(org.apache.jasper.compiler.ServletWriter writer)

        this.writer = writer;