Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * 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 static org.jboss.web.JasperMessages.MESSAGES;
 
 import java.io.File;
 import java.net.URL;
 import java.util.Map;
 import java.util.Set;
 
 
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(s):
Anil K. Vijendran
Harish Prabandham
Pierre Delisle
Costin Manolache
Kin-man Chung
 
 public class JspCompilationContext {
 
     protected Map<StringURLtagFileJarUrls;
     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 ServletWriter writer;
     protected Options options;
     protected JspServletWrapper jsw;
     protected Compiler jspCompiler;
     protected String classPath;
 
     protected String baseURI;
     protected String outputDir;
     protected ServletContext context;
     protected ClassLoader loader;
 
     protected JspRuntimeContext rctxt;
 
     protected int removed = 0;
 
     protected URLClassLoader jspLoader;
     protected URL baseUrl;
     protected Class servletClass;
 
     protected boolean isTagFile;
     protected boolean protoTypeMode;
     protected TagInfo tagInfo;
     protected URL tagFileJarUrl;
 
 
     // jspURI _must_ be relative to the context
     public JspCompilationContext(String jspUri,
                                  boolean isErrPage,
                                 Options options,
                                 ServletContext context,
                                 JspServletWrapper jsw,
                                 JspRuntimeContext rctxt) {
        this. = canonicalURI(jspUri);
        this. = isErrPage;
        this. = options;
        this. = jsw;
        this. = context;
        this. = jspUri.substring(0, jspUri.lastIndexOf('/') + 1);
        // hack fix for resolveRelativeURI
        if ( == null) {
             = "/";
        } else if (.charAt(0) != '/') {
            // strip the basde slash since it will be combined with the
            // uriBase to generate a file
             = "/" + ;
        }
        if (.charAt(.length() - 1) != '/') {
             += '/';
        }
        this. = rctxt;
        this. = new HashMap<StringURL>();
            context.getAttribute(.);
        if ( == null) {
            // FIXME: error message, Jasper needs TLD data
            throw new IllegalStateException();
        }
    }
    public JspCompilationContext(String tagfile,
                                 TagInfo tagInfo
                                 Options options,
                                 ServletContext context,
                                 JspServletWrapper jsw,
                                 JspRuntimeContext rctxt,
                                 URL tagFileJarUrl) {
        this(tagfilefalseoptionscontextjswrctxt);
        this. = true;
        this. = tagInfo;
        this. = tagFileJarUrl;
        if (tagFileJarUrl != null) {
             = true;
        }
    }
    /* ==================== Methods to override ==================== */
    
    
---------- Class path and loader ----------


    
The classpath that is passed off to the Java compiler.
    public String getClassPath() {
        if != null )
            return ;
        return .getClassPath();
    }

    
The classpath that is passed off to the Java compiler.
    public void setClassPath(String classPath) {
        this. = classPath;
    }

    
What class loader to use for loading classes while compiling this JSP?
    public ClassLoader getClassLoader() {
        if != null )
            return ;
        return .getParentClassLoader();
    }
    public void setClassLoader(ClassLoader loader) {
        this. = loader;
    }
    public ClassLoader getJspLoader() {
        if == null ) {
             = new JasperLoader
            (new URL[] {},
                    getClassLoader(),
                    .getPermissionCollection(),
                    .getCodeSource());
        }
        return ;
    }

    
---------- Input/Output ----------

    
    
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.
    public String getOutputDir() {
	if ( == null) {
	    createOutputDir();
	}
        return ;
    }

    
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.
    public Compiler createCompiler() throws JasperException {
        if ( != null ) {
            return ;
        }
         = null;
        if (.getCompilerClassName() != null) {
        } else {
            if (.getCompiler() == null) {
                 = createCompiler("org.apache.jasper.compiler.JDTCompiler");
                if ( == null) {
                     = createCompiler("org.apache.jasper.compiler.AntCompiler");
                }
            } else if (.getCompiler().startsWith("jci:")) {
                 = createCompiler("org.apache.jasper.compiler.JCICompiler");
                if ( == null) {
                     = createCompiler("org.apache.jasper.compiler.JDTCompiler");
                }
            } else {
                 = createCompiler("org.apache.jasper.compiler.AntCompiler");
                if ( == null) {
                     = createCompiler("org.apache.jasper.compiler.JDTCompiler");
                }
            }
        }
        if ( == null) {
            throw .noJavaCompiler();
        }
        .init(this);
        return ;
    }
    protected Compiler createCompiler(String className) {
        Compiler compiler = null
        try {
            compiler = (Compiler) Class.forName(className).newInstance();
        } catch (InstantiationException e) {
            ..failedLoadingJavaCompiler(classNamee);
        } catch (IllegalAccessException e) {
            ..failedLoadingJavaCompiler(classNamee);
        } catch (NoClassDefFoundError e) {
            ..failedLoadingJavaCompiler(classNamee);
        } catch (ClassNotFoundException e) {
            ..failedLoadingJavaCompiler(classNamee);
        }
        return compiler;
    }
    
    public Compiler getCompiler() {
        return ;
    }

    
---------- Access resources in the webapp ----------


    
Get the full value of a URI relative to this compilations context uses current file as the base.
    public String resolveRelativeUri(String uri) {
        // sometimes we get uri's massaged from File(String), so check for
        // a root directory deperator char
        if (uri.startsWith("/") || uri.startsWith(.)) {
            return uri;
        } else {
            return  + uri;
        }
    }

    
Gets a resource as a stream, relative to the meanings of this context's implementation.

Returns:
a null if the resource cannot be found or represented as an InputStream.
    public java.io.InputStream getResourceAsStream(String res) {
        return .getResourceAsStream(canonicalURI(res));
    }
    public URL getResource(String resthrows MalformedURLException {
        URL result = null;
        if (res.startsWith("/META-INF/")) {
            // This is a tag file packaged in a jar that is being compiled
            URL jarUrl = .get(res);
            if (jarUrl == null) {
                jarUrl = ;
            }
            if (jarUrl != null) {
                result = new URL(jarUrl.toExternalForm() + res.substring(1));
            } else {
                // May not be in a JAR in some IDE environments
                result = .getResource(canonicalURI(res));
            }
        } else if (res.startsWith("jar:file:")) {
            // This is a tag file packaged in a jar that is being checked
            // for a dependency
            result = new URL(res);
        } else {
            result = .getResource(canonicalURI(res));
        }
        return result;
    }
    public Set getResourcePaths(String path) {
        return .getResourcePaths(canonicalURI(path));
    }

    
Gets the actual path of a URI relative to the context of the compilation.
    public String getRealPath(String path) {
        if ( != null) {
            return .getRealPath(path);
        }
        return path;
    }

    
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.
    public URL getTagFileJarUrl(String tagFile) {
        return this..get(tagFile);
    }
    public void setTagFileJarUrl(String tagFileURL tagFileURL) {
        this..put(tagFiletagFileURL);
    }

    
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.
    public URL getTagFileJarUrl() {
        return this.;
    }
    /* ==================== Common implementation ==================== */

    
Just the class name (does not include package name) of the generated class.
    public String getServletClassName() {
        if ( != null) {
            return ;
        }
        if () {
             = .getTagClassName();
            int lastIndex = .lastIndexOf('.');
            if (lastIndex != -1) {
                 = .substring(lastIndex + 1);
            }
        } else {
            int iSep = .lastIndexOf('/') + 1;
             = JspUtil.makeJavaIdentifier(.substring(iSep));
        }
        return ;
    }
    public void setServletClassName(String className) {
        this. = className;
    }
    
    
Path of the JSP URI. Note that this is not a file name. This is the context rooted URI of the JSP file.
    public String getJspFile() {
        return ;
    }

    
Are we processing something that has been declared as an errorpage?
    public boolean isErrorPage() {
        return ;
    }
    public void setErrorPage(boolean isErrPage) {
        this. = isErrPage;
    }
    public boolean isTagFile() {
        return ;
    }
    public TagInfo getTagInfo() {
        return ;
    }
    public void setTagInfo(TagInfo tagi) {
         = tagi;
    }

    
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.
    public boolean isPrototypeMode() {
        return ;
    }
    public void setPrototypeMode(boolean pm) {
         = pm;
    }

    
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.
    public String getServletPackageName() {
        if (isTagFile()) {
            String className = .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 ;
            }
            return  + '.' + getDerivedPackageName();
        }
    }
    protected String getDerivedPackageName() {
        if ( == null) {
            int iSep = .lastIndexOf('/');
             = (iSep > 0) ?
                    JspUtil.makeJavaPackage(.substring(1,iSep)) : "";
        }
        return ;
    }
    
    
The package name into which the servlet class is generated.
    public void setServletPackageName(String servletPackageName) {
        this. = servletPackageName;
    }

    
Full path name of the Java file into which the servlet is being generated.
    public String getServletJavaFileName() {
        if ( == null) {
             = getOutputDir() + getServletClassName() + ".java";
        }
        return ;
    }

    
Get hold of the Options object for this context.
    public Options getOptions() {
        return ;
    }
    public ServletContext getServletContext() {
        return ;
    }
        return ;
    }

    
Path of the Java file relative to the work directory.
    public String getJavaPath() {
        if ( != null) {
            return ;
        }
        if (isTagFile()) {
	    String tagName = .getTagClassName();
             = tagName.replace('.''/') + ".java";
        } else {
             = getServletPackageName().replace('.''/') + '/' +
                       getServletClassName() + ".java";
	}
        return ;
    }
    public String getClassFileName() {
        if ( == null) {
             = getOutputDir() + getServletClassName() + ".class";
        }
        return ;
    }

    
Get the content type of this JSP. Content type includes content type and encoding.
    public String getContentType() {
        return ;
    }
    public void setContentType(String contentType) {
        this. = contentType;
    }

    
Where is the servlet being generated?
    public ServletWriter getWriter() {
        return ;
    }
    public void setWriter(ServletWriter writer) {
        this. = writer;
    }

    
Gets the 'location' of the TLD associated with the given taglib 'uri'.

Returns:
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.
    public String[] getTldLocation(String urithrows JasperException {
        org.apache.catalina.deploy.jsp.TagLibraryInfo tagLibraryInfo = .get(uri);
        if (tagLibraryInfo == null) {
            return null;
        } else {
            String[] location = new String[2];
            if (tagLibraryInfo.getLocation() == null) {
                location[0] = tagLibraryInfo.getPath();
            } else {
                location[0] = tagLibraryInfo.getLocation();
                location[1] = tagLibraryInfo.getPath();
            }
            return location;
        }
    }

    
Are we keeping generated code around?
    public boolean keepGenerated() {
        return getOptions().getKeepGenerated();
    }
    // ==================== Removal ==================== 
    public void incrementRemoved() {
        if ( == 0 &&  != null) {
            .removeWrapper();
        }
        ++;
    }
    public boolean isRemoved() {
        if ( > 1 ) {
            return true;
        }
        return false;
    }
    // ==================== Compile and reload ====================
    
    public void compile() throws JasperExceptionFileNotFoundException {
        createCompiler();
        if (.isOutDated()) {
            try {
                .removeGeneratedFiles();
                 = null;
                .compile();
                .setReload(true);
                .setCompilationException(null);
            } catch (JasperException ex) {
                // Cache compilation exception
                .setCompilationException(ex);
                if (.getDevelopment() && .getRecompileOnFail()) {
                    // Force a recompilation attempt on next access
                    .setLastModificationTest(-1);
                }
                throw ex;
            } catch (Exception ex) {
                JasperException je = new JasperException(.failedClassCompilation(),
                            ex);
                // Cache compilation exception
                .setCompilationException(je);
                throw je;
            }
        }
    }
    // ==================== Manipulating the class ====================
    public Class load() 
        throws JasperExceptionFileNotFoundException
    {
        try {
            getJspLoader();
            
            String name = getFQCN();
             = .loadClass(name);
        } catch (ClassNotFoundException cex) {
            throw new JasperException(.failedClassLoading(),
                                      cex);
        } catch (Exception ex) {
            throw new JasperException(.failedClassCompilation(),
                                      ex);
        }
         = 0;
        return ;
    }
    public String getFQCN() {
        String name;
        if (isTagFile()) {
            name = .getTagClassName();
        } else {
            name = getServletPackageName() + "." + getServletClassName();
        }
        return name;
    }
    // ==================== protected methods ==================== 
    static Object outputDirLock = new Object();
    public void checkOutputDir() {
        if ( != null) {
            if (!(new File()).exists()) {
                makeOutputDir();
            }
        } else {
            createOutputDir();
        }
    }
        
    protected boolean makeOutputDir() {
        synchronized() {
            File outDirFile = new File();
            return (outDirFile.exists() || outDirFile.mkdirs());
        }
    }
    protected void createOutputDir() {
        String path = null;
        if (isTagFile()) {
            String tagName = .getTagClassName();
            path = tagName.replace('.'.);
            path = path.substring(0, path.lastIndexOf(.));
        } else {
            path = getServletPackageName().replace('.',.);
        }
            // Append servlet or tag handler path to scratch dir
            try {
                File base = .getScratchDir();
                 = base.toURI().toURL();
                 = base.getAbsolutePath() + . + path + .;
                if (!makeOutputDir()) {
                    throw new IllegalStateException(.noOutputFolder());
                }
            } catch (MalformedURLException e) {
                throw new IllegalStateException(.badOutputFolderUrl(e));
            }
    }
    
    protected static final boolean isPathSeparator(char c) {
       return (c == '/' || c == '\\');
    }
    protected static final String canonicalURI(String s) {
       if (s == nullreturn null;
       StringBuilder result = new StringBuilder();
       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 >= lenbreak;
                   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();
    }
New to GrepCode? Check out our FAQ X