Advertisement
Guest User

toomasr

a guest
Jan 13th, 2010
2,319
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 77.82 KB | None | 0 0
  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17.  
  18.  
  19. package org.apache.catalina.loader;
  20.  
  21. import java.io.ByteArrayInputStream;
  22. import java.io.File;
  23. import java.io.FileOutputStream;
  24. import java.io.FilePermission;
  25. import java.io.IOException;
  26. import java.io.InputStream;
  27. import java.lang.reflect.Field;
  28. import java.lang.reflect.Modifier;
  29. import java.net.MalformedURLException;
  30. import java.net.URL;
  31. import java.net.URLClassLoader;
  32. import java.security.AccessControlException;
  33. import java.security.AccessController;
  34. import java.security.CodeSource;
  35. import java.security.Permission;
  36. import java.security.PermissionCollection;
  37. import java.security.Policy;
  38. import java.security.PrivilegedAction;
  39. import java.sql.Driver;
  40. import java.sql.DriverManager;
  41. import java.sql.SQLException;
  42. import java.util.ArrayList;
  43. import java.util.Enumeration;
  44. import java.util.HashMap;
  45. import java.util.Iterator;
  46. import java.util.Vector;
  47. import java.util.jar.Attributes;
  48. import java.util.jar.JarEntry;
  49. import java.util.jar.JarFile;
  50. import java.util.jar.Manifest;
  51. import java.util.jar.Attributes.Name;
  52.  
  53. import javax.naming.NameClassPair;
  54. import javax.naming.NamingEnumeration;
  55. import javax.naming.NamingException;
  56. import javax.naming.directory.DirContext;
  57.  
  58. import org.apache.catalina.Globals;
  59. import org.apache.catalina.Lifecycle;
  60. import org.apache.catalina.LifecycleException;
  61. import org.apache.catalina.LifecycleListener;
  62. import org.apache.catalina.util.StringManager;
  63. import org.apache.naming.JndiPermission;
  64. import org.apache.naming.resources.Resource;
  65. import org.apache.naming.resources.ResourceAttributes;
  66. import org.apache.tomcat.util.IntrospectionUtils;
  67.  
  68. /**
  69.  * Specialized web application class loader.
  70.  * <p>
  71.  * This class loader is a full reimplementation of the
  72.  * <code>URLClassLoader</code> from the JDK. It is desinged to be fully
  73.  * compatible with a normal <code>URLClassLoader</code>, although its internal
  74.  * behavior may be completely different.
  75.  * <p>
  76.  * <strong>IMPLEMENTATION NOTE</strong> - This class loader faithfully follows
  77.  * the delegation model recommended in the specification. The system class
  78.  * loader will be queried first, then the local repositories, and only then
  79.  * delegation to the parent class loader will occur. This allows the web
  80.  * application to override any shared class except the classes from J2SE.
  81.  * Special handling is provided from the JAXP XML parser interfaces, the JNDI
  82.  * interfaces, and the classes from the servlet API, which are never loaded
  83.  * from the webapp repository.
  84.  * <p>
  85.  * <strong>IMPLEMENTATION NOTE</strong> - Due to limitations in Jasper
  86.  * compilation technology, any repository which contains classes from
  87.  * the servlet API will be ignored by the class loader.
  88.  * <p>
  89.  * <strong>IMPLEMENTATION NOTE</strong> - The class loader generates source
  90.  * URLs which include the full JAR URL when a class is loaded from a JAR file,
  91.  * which allows setting security permission at the class level, even when a
  92.  * class is contained inside a JAR.
  93.  * <p>
  94.  * <strong>IMPLEMENTATION NOTE</strong> - Local repositories are searched in
  95.  * the order they are added via the initial constructor and/or any subsequent
  96.  * calls to <code>addRepository()</code> or <code>addJar()</code>.
  97.  * <p>
  98.  * <strong>IMPLEMENTATION NOTE</strong> - No check for sealing violations or
  99.  * security is made unless a security manager is present.
  100.  *
  101.  * @author Remy Maucherat
  102.  * @author Craig R. McClanahan
  103.  * @version $Revision: 734579 $ $Date: 2009-01-15 01:26:00 +0100 (Thu, 15 Jan 2009) $
  104.  */
  105. public class WebappClassLoader
  106.     extends URLClassLoader
  107.     implements Reloader, Lifecycle
  108.  {
  109.  
  110.     protected static org.apache.juli.logging.Log log=
  111.         org.apache.juli.logging.LogFactory.getLog( WebappClassLoader.class );
  112.  
  113.     public static final boolean ENABLE_CLEAR_REFERENCES =
  114.         Boolean.valueOf(System.getProperty("org.apache.catalina.loader.WebappClassLoader.ENABLE_CLEAR_REFERENCES", "true")).booleanValue();
  115.    
  116.     protected class PrivilegedFindResource
  117.         implements PrivilegedAction {
  118.  
  119.         protected File file;
  120.         protected String path;
  121.  
  122.         PrivilegedFindResource(File file, String path) {
  123.             this.file = file;
  124.             this.path = path;
  125.         }
  126.  
  127.         public Object run() {
  128.             return findResourceInternal(file, path);
  129.         }
  130.  
  131.     }
  132.  
  133.    
  134.     protected final class PrivilegedGetClassLoader
  135.         implements PrivilegedAction<ClassLoader> {
  136.  
  137.         public Class<?> clazz;
  138.  
  139.         public PrivilegedGetClassLoader(Class<?> clazz){
  140.             this.clazz = clazz;
  141.         }
  142.  
  143.         public ClassLoader run() {      
  144.             return clazz.getClassLoader();
  145.         }          
  146.     }
  147.  
  148.    
  149.  
  150.  
  151.     // ------------------------------------------------------- Static Variables
  152.  
  153.  
  154.     /**
  155.      * The set of trigger classes that will cause a proposed repository not
  156.      * to be added if this class is visible to the class loader that loaded
  157.      * this factory class.  Typically, trigger classes will be listed for
  158.      * components that have been integrated into the JDK for later versions,
  159.      * but where the corresponding JAR files are required to run on
  160.      * earlier versions.
  161.      */
  162.     protected static final String[] triggers = {
  163.         "javax.servlet.Servlet"                     // Servlet API
  164.     };
  165.  
  166.  
  167.     /**
  168.      * Set of package names which are not allowed to be loaded from a webapp
  169.      * class loader without delegating first.
  170.      */
  171.     protected static final String[] packageTriggers = {
  172.     };
  173.  
  174.  
  175.     /**
  176.      * The string manager for this package.
  177.      */
  178.     protected static final StringManager sm =
  179.         StringManager.getManager(Constants.Package);
  180.  
  181.    
  182.     /**
  183.      * Use anti JAR locking code, which does URL rerouting when accessing
  184.      * resources.
  185.      */
  186.     boolean antiJARLocking = false;
  187.    
  188.  
  189.     // ----------------------------------------------------------- Constructors
  190.  
  191.  
  192.     /**
  193.      * Construct a new ClassLoader with no defined repositories and no
  194.      * parent ClassLoader.
  195.      */
  196.     public WebappClassLoader() {
  197.  
  198.         super(new URL[0]);
  199.         this.parent = getParent();
  200.         system = getSystemClassLoader();
  201.         securityManager = System.getSecurityManager();
  202.  
  203.         if (securityManager != null) {
  204.             refreshPolicy();
  205.         }
  206.  
  207.     }
  208.  
  209.  
  210.     /**
  211.      * Construct a new ClassLoader with no defined repositories and no
  212.      * parent ClassLoader.
  213.      */
  214.     public WebappClassLoader(ClassLoader parent) {
  215.  
  216.         super(new URL[0], parent);
  217.                
  218.         this.parent = getParent();
  219.        
  220.         system = getSystemClassLoader();
  221.         securityManager = System.getSecurityManager();
  222.  
  223.         if (securityManager != null) {
  224.             refreshPolicy();
  225.         }
  226.     }
  227.  
  228.  
  229.     // ----------------------------------------------------- Instance Variables
  230.  
  231.  
  232.     /**
  233.      * Associated directory context giving access to the resources in this
  234.      * webapp.
  235.      */
  236.     protected DirContext resources = null;
  237.  
  238.  
  239.     /**
  240.      * The cache of ResourceEntry for classes and resources we have loaded,
  241.      * keyed by resource name.
  242.      */
  243.     protected HashMap resourceEntries = new HashMap();
  244.  
  245.  
  246.     /**
  247.      * The list of not found resources.
  248.      */
  249.     protected HashMap notFoundResources = new HashMap();
  250.  
  251.  
  252.     /**
  253.      * Should this class loader delegate to the parent class loader
  254.      * <strong>before</strong> searching its own repositories (i.e. the
  255.      * usual Java2 delegation model)?  If set to <code>false</code>,
  256.      * this class loader will search its own repositories first, and
  257.      * delegate to the parent only if the class or resource is not
  258.      * found locally.
  259.      */
  260.     protected boolean delegate = false;
  261.  
  262.  
  263.     /**
  264.      * Last time a JAR was accessed.
  265.      */
  266.     protected long lastJarAccessed = 0L;
  267.  
  268.  
  269.     /**
  270.      * The list of local repositories, in the order they should be searched
  271.      * for locally loaded classes or resources.
  272.      */
  273.     protected String[] repositories = new String[0];
  274.  
  275.  
  276.      /**
  277.       * Repositories URLs, used to cache the result of getURLs.
  278.       */
  279.      protected URL[] repositoryURLs = null;
  280.  
  281.  
  282.     /**
  283.      * Repositories translated as path in the work directory (for Jasper
  284.      * originally), but which is used to generate fake URLs should getURLs be
  285.      * called.
  286.      */
  287.     protected File[] files = new File[0];
  288.  
  289.  
  290.     /**
  291.      * The list of JARs, in the order they should be searched
  292.      * for locally loaded classes or resources.
  293.      */
  294.     protected JarFile[] jarFiles = new JarFile[0];
  295.  
  296.  
  297.     /**
  298.      * The list of JARs, in the order they should be searched
  299.      * for locally loaded classes or resources.
  300.      */
  301.     protected File[] jarRealFiles = new File[0];
  302.  
  303.  
  304.     /**
  305.      * The path which will be monitored for added Jar files.
  306.      */
  307.     protected String jarPath = null;
  308.  
  309.  
  310.     /**
  311.      * The list of JARs, in the order they should be searched
  312.      * for locally loaded classes or resources.
  313.      */
  314.     protected String[] jarNames = new String[0];
  315.  
  316.  
  317.     /**
  318.      * The list of JARs last modified dates, in the order they should be
  319.      * searched for locally loaded classes or resources.
  320.      */
  321.     protected long[] lastModifiedDates = new long[0];
  322.  
  323.  
  324.     /**
  325.      * The list of resources which should be checked when checking for
  326.      * modifications.
  327.      */
  328.     protected String[] paths = new String[0];
  329.  
  330.  
  331.     /**
  332.      * A list of read File and Jndi Permission's required if this loader
  333.      * is for a web application context.
  334.      */
  335.     protected ArrayList permissionList = new ArrayList();
  336.  
  337.  
  338.     /**
  339.      * Path where resources loaded from JARs will be extracted.
  340.      */
  341.     protected File loaderDir = null;
  342.  
  343.  
  344.     /**
  345.      * The PermissionCollection for each CodeSource for a web
  346.      * application context.
  347.      */
  348.     protected HashMap loaderPC = new HashMap();
  349.  
  350.  
  351.     /**
  352.      * Instance of the SecurityManager installed.
  353.      */
  354.     protected SecurityManager securityManager = null;
  355.  
  356.  
  357.     /**
  358.      * The parent class loader.
  359.      */
  360.     protected ClassLoader parent = null;
  361.  
  362.  
  363.     /**
  364.      * The system class loader.
  365.      */
  366.     protected ClassLoader system = null;
  367.  
  368.  
  369.     /**
  370.      * Has this component been started?
  371.      */
  372.     protected boolean started = false;
  373.  
  374.  
  375.     /**
  376.      * Has external repositories.
  377.      */
  378.     protected boolean hasExternalRepositories = false;
  379.  
  380.     /**
  381.      * need conversion for properties files
  382.      */
  383.     protected boolean needConvert = false;
  384.  
  385.  
  386.     /**
  387.      * All permission.
  388.      */
  389.     protected Permission allPermission = new java.security.AllPermission();
  390.  
  391.  
  392.     // ------------------------------------------------------------- Properties
  393.  
  394.  
  395.     /**
  396.      * Get associated resources.
  397.      */
  398.     public DirContext getResources() {
  399.  
  400.         return this.resources;
  401.  
  402.     }
  403.  
  404.  
  405.     /**
  406.      * Set associated resources.
  407.      */
  408.     public void setResources(DirContext resources) {
  409.  
  410.         this.resources = resources;
  411.  
  412.     }
  413.  
  414.  
  415.     /**
  416.      * Return the "delegate first" flag for this class loader.
  417.      */
  418.     public boolean getDelegate() {
  419.  
  420.         return (this.delegate);
  421.  
  422.     }
  423.  
  424.  
  425.     /**
  426.      * Set the "delegate first" flag for this class loader.
  427.      *
  428.      * @param delegate The new "delegate first" flag
  429.      */
  430.     public void setDelegate(boolean delegate) {
  431.  
  432.         this.delegate = delegate;
  433.  
  434.     }
  435.  
  436.  
  437.     /**
  438.      * @return Returns the antiJARLocking.
  439.      */
  440.     public boolean getAntiJARLocking() {
  441.         return antiJARLocking;
  442.     }
  443.    
  444.    
  445.     /**
  446.      * @param antiJARLocking The antiJARLocking to set.
  447.      */
  448.     public void setAntiJARLocking(boolean antiJARLocking) {
  449.         this.antiJARLocking = antiJARLocking;
  450.     }
  451.  
  452.    
  453.     /**
  454.      * If there is a Java SecurityManager create a read FilePermission
  455.      * or JndiPermission for the file directory path.
  456.      *
  457.      * @param path file directory path
  458.      */
  459.     public void addPermission(String path) {
  460.         if (path == null) {
  461.             return;
  462.         }
  463.  
  464.         if (securityManager != null) {
  465.             Permission permission = null;
  466.             if( path.startsWith("jndi:") || path.startsWith("jar:jndi:") ) {
  467.                 if (!path.endsWith("/")) {
  468.                     path = path + "/";
  469.                 }
  470.                 permission = new JndiPermission(path + "*");
  471.                 addPermission(permission);
  472.             } else {
  473.                 if (!path.endsWith(File.separator)) {
  474.                     permission = new FilePermission(path, "read");
  475.                     addPermission(permission);
  476.                     path = path + File.separator;
  477.                 }
  478.                 permission = new FilePermission(path + "-", "read");
  479.                 addPermission(permission);
  480.             }
  481.         }
  482.     }
  483.  
  484.  
  485.     /**
  486.      * If there is a Java SecurityManager create a read FilePermission
  487.      * or JndiPermission for URL.
  488.      *
  489.      * @param url URL for a file or directory on local system
  490.      */
  491.     public void addPermission(URL url) {
  492.         if (url != null) {
  493.             addPermission(url.toString());
  494.         }
  495.     }
  496.  
  497.  
  498.     /**
  499.      * If there is a Java SecurityManager create a Permission.
  500.      *
  501.      * @param permission The permission
  502.      */
  503.     public void addPermission(Permission permission) {
  504.         if ((securityManager != null) && (permission != null)) {
  505.             permissionList.add(permission);
  506.         }
  507.     }
  508.  
  509.  
  510.     /**
  511.      * Return the JAR path.
  512.      */
  513.     public String getJarPath() {
  514.  
  515.         return this.jarPath;
  516.  
  517.     }
  518.  
  519.  
  520.     /**
  521.      * Change the Jar path.
  522.      */
  523.     public void setJarPath(String jarPath) {
  524.  
  525.         this.jarPath = jarPath;
  526.  
  527.     }
  528.  
  529.  
  530.     /**
  531.      * Change the work directory.
  532.      */
  533.     public void setWorkDir(File workDir) {
  534.         this.loaderDir = new File(workDir, "loader");
  535.     }
  536.  
  537.      /**
  538.       * Utility method for use in subclasses.
  539.       * Must be called before Lifecycle methods to have any effect.
  540.       */
  541.      protected void setParentClassLoader(ClassLoader pcl) {
  542.          parent = pcl;
  543.      }
  544.  
  545.     // ------------------------------------------------------- Reloader Methods
  546.  
  547.  
  548.     /**
  549.      * Add a new repository to the set of places this ClassLoader can look for
  550.      * classes to be loaded.
  551.      *
  552.      * @param repository Name of a source of classes to be loaded, such as a
  553.      *  directory pathname, a JAR file pathname, or a ZIP file pathname
  554.      *
  555.      * @exception IllegalArgumentException if the specified repository is
  556.      *  invalid or does not exist
  557.      */
  558.     public void addRepository(String repository) {
  559.  
  560.         // Ignore any of the standard repositories, as they are set up using
  561.         // either addJar or addRepository
  562.         if (repository.startsWith("/WEB-INF/lib")
  563.             || repository.startsWith("/WEB-INF/classes"))
  564.             return;
  565.  
  566.         // Add this repository to our underlying class loader
  567.         try {
  568.             URL url = new URL(repository);
  569.             super.addURL(url);
  570.             hasExternalRepositories = true;
  571.             repositoryURLs = null;
  572.         } catch (MalformedURLException e) {
  573.             IllegalArgumentException iae = new IllegalArgumentException
  574.                 ("Invalid repository: " + repository);
  575.             iae.initCause(e);
  576.             throw iae;
  577.         }
  578.  
  579.     }
  580.  
  581.  
  582.     /**
  583.      * Add a new repository to the set of places this ClassLoader can look for
  584.      * classes to be loaded.
  585.      *
  586.      * @param repository Name of a source of classes to be loaded, such as a
  587.      *  directory pathname, a JAR file pathname, or a ZIP file pathname
  588.      *
  589.      * @exception IllegalArgumentException if the specified repository is
  590.      *  invalid or does not exist
  591.      */
  592.     synchronized void addRepository(String repository, File file) {
  593.  
  594.         // Note : There should be only one (of course), but I think we should
  595.         // keep this a bit generic
  596.  
  597.         if (repository == null)
  598.             return;
  599.  
  600.         if (log.isDebugEnabled())
  601.             log.debug("addRepository(" + repository + ")");
  602.  
  603.         int i;
  604.  
  605.         // Add this repository to our internal list
  606.         String[] result = new String[repositories.length + 1];
  607.         for (i = 0; i < repositories.length; i++) {
  608.             result[i] = repositories[i];
  609.         }
  610.         result[repositories.length] = repository;
  611.         repositories = result;
  612.  
  613.         // Add the file to the list
  614.         File[] result2 = new File[files.length + 1];
  615.         for (i = 0; i < files.length; i++) {
  616.             result2[i] = files[i];
  617.         }
  618.         result2[files.length] = file;
  619.         files = result2;
  620.  
  621.     }
  622.  
  623.  
  624.     synchronized void addJar(String jar, JarFile jarFile, File file)
  625.         throws IOException {
  626.  
  627.         if (jar == null)
  628.             return;
  629.         if (jarFile == null)
  630.             return;
  631.         if (file == null)
  632.             return;
  633.  
  634.         if (log.isDebugEnabled())
  635.             log.debug("addJar(" + jar + ")");
  636.  
  637.         int i;
  638.  
  639.         if ((jarPath != null) && (jar.startsWith(jarPath))) {
  640.  
  641.             String jarName = jar.substring(jarPath.length());
  642.             while (jarName.startsWith("/"))
  643.                 jarName = jarName.substring(1);
  644.  
  645.             String[] result = new String[jarNames.length + 1];
  646.             for (i = 0; i < jarNames.length; i++) {
  647.                 result[i] = jarNames[i];
  648.             }
  649.             result[jarNames.length] = jarName;
  650.             jarNames = result;
  651.  
  652.         }
  653.  
  654.         try {
  655.  
  656.             // Register the JAR for tracking
  657.  
  658.             long lastModified =
  659.                 ((ResourceAttributes) resources.getAttributes(jar))
  660.                 .getLastModified();
  661.  
  662.             String[] result = new String[paths.length + 1];
  663.             for (i = 0; i < paths.length; i++) {
  664.                 result[i] = paths[i];
  665.             }
  666.             result[paths.length] = jar;
  667.             paths = result;
  668.  
  669.             long[] result3 = new long[lastModifiedDates.length + 1];
  670.             for (i = 0; i < lastModifiedDates.length; i++) {
  671.                 result3[i] = lastModifiedDates[i];
  672.             }
  673.             result3[lastModifiedDates.length] = lastModified;
  674.             lastModifiedDates = result3;
  675.  
  676.         } catch (NamingException e) {
  677.             // Ignore
  678.         }
  679.  
  680.         // If the JAR currently contains invalid classes, don't actually use it
  681.         // for classloading
  682.         if (!validateJarFile(file))
  683.             return;
  684.  
  685.         JarFile[] result2 = new JarFile[jarFiles.length + 1];
  686.         for (i = 0; i < jarFiles.length; i++) {
  687.             result2[i] = jarFiles[i];
  688.         }
  689.         result2[jarFiles.length] = jarFile;
  690.         jarFiles = result2;
  691.  
  692.         // Add the file to the list
  693.         File[] result4 = new File[jarRealFiles.length + 1];
  694.         for (i = 0; i < jarRealFiles.length; i++) {
  695.             result4[i] = jarRealFiles[i];
  696.         }
  697.         result4[jarRealFiles.length] = file;
  698.         jarRealFiles = result4;
  699.     }
  700.  
  701.  
  702.     /**
  703.      * Return a String array of the current repositories for this class
  704.      * loader.  If there are no repositories, a zero-length array is
  705.      * returned.For security reason, returns a clone of the Array (since
  706.      * String are immutable).
  707.      */
  708.     public String[] findRepositories() {
  709.  
  710.         return ((String[])repositories.clone());
  711.  
  712.     }
  713.  
  714.  
  715.     /**
  716.      * Have one or more classes or resources been modified so that a reload
  717.      * is appropriate?
  718.      */
  719.     public boolean modified() {
  720.  
  721.         if (log.isDebugEnabled())
  722.             log.debug("modified()");
  723.  
  724.         // Checking for modified loaded resources
  725.         int length = paths.length;
  726.  
  727.         // A rare race condition can occur in the updates of the two arrays
  728.         // It's totally ok if the latest class added is not checked (it will
  729.         // be checked the next time
  730.         int length2 = lastModifiedDates.length;
  731.         if (length > length2)
  732.             length = length2;
  733.  
  734.         for (int i = 0; i < length; i++) {
  735.             try {
  736.                 long lastModified =
  737.                     ((ResourceAttributes) resources.getAttributes(paths[i]))
  738.                     .getLastModified();
  739.                 if (lastModified != lastModifiedDates[i]) {
  740.                     if( log.isDebugEnabled() )
  741.                         log.debug("  Resource '" + paths[i]
  742.                                   + "' was modified; Date is now: "
  743.                                   + new java.util.Date(lastModified) + " Was: "
  744.                                   + new java.util.Date(lastModifiedDates[i]));
  745.                     return (true);
  746.                 }
  747.             } catch (NamingException e) {
  748.                 log.error("    Resource '" + paths[i] + "' is missing");
  749.                 return (true);
  750.             }
  751.         }
  752.  
  753.         length = jarNames.length;
  754.  
  755.         // Check if JARs have been added or removed
  756.         if (getJarPath() != null) {
  757.  
  758.             try {
  759.                 NamingEnumeration enumeration = resources.listBindings(getJarPath());
  760.                 int i = 0;
  761.                 while (enumeration.hasMoreElements() && (i < length)) {
  762.                     NameClassPair ncPair = (NameClassPair) enumeration.nextElement();
  763.                     String name = ncPair.getName();
  764.                     // Ignore non JARs present in the lib folder
  765.                     if (!name.endsWith(".jar"))
  766.                         continue;
  767.                     if (!name.equals(jarNames[i])) {
  768.                         // Missing JAR
  769.                         log.info("    Additional JARs have been added : '"
  770.                                  + name + "'");
  771.                         return (true);
  772.                     }
  773.                     i++;
  774.                 }
  775.                 if (enumeration.hasMoreElements()) {
  776.                     while (enumeration.hasMoreElements()) {
  777.                         NameClassPair ncPair =
  778.                             (NameClassPair) enumeration.nextElement();
  779.                         String name = ncPair.getName();
  780.                         // Additional non-JAR files are allowed
  781.                         if (name.endsWith(".jar")) {
  782.                             // There was more JARs
  783.                             log.info("    Additional JARs have been added");
  784.                             return (true);
  785.                         }
  786.                     }
  787.                 } else if (i < jarNames.length) {
  788.                     // There was less JARs
  789.                     log.info("    Additional JARs have been added");
  790.                     return (true);
  791.                 }
  792.             } catch (NamingException e) {
  793.                 if (log.isDebugEnabled())
  794.                     log.debug("    Failed tracking modifications of '"
  795.                         + getJarPath() + "'");
  796.             } catch (ClassCastException e) {
  797.                 log.error("    Failed tracking modifications of '"
  798.                           + getJarPath() + "' : " + e.getMessage());
  799.             }
  800.  
  801.         }
  802.  
  803.         // No classes have been modified
  804.         return (false);
  805.  
  806.     }
  807.  
  808.  
  809.     /**
  810.      * Render a String representation of this object.
  811.      */
  812.     public String toString() {
  813.  
  814.         StringBuffer sb = new StringBuffer("WebappClassLoader\r\n");
  815.         sb.append("  delegate: ");
  816.         sb.append(delegate);
  817.         sb.append("\r\n");
  818.         sb.append("  repositories:\r\n");
  819.         if (repositories != null) {
  820.             for (int i = 0; i < repositories.length; i++) {
  821.                 sb.append("    ");
  822.                 sb.append(repositories[i]);
  823.                 sb.append("\r\n");
  824.             }
  825.         }
  826.         if (this.parent != null) {
  827.             sb.append("----------> Parent Classloader:\r\n");
  828.             sb.append(this.parent.toString());
  829.             sb.append("\r\n");
  830.         }
  831.         return (sb.toString());
  832.  
  833.     }
  834.  
  835.  
  836.     // ---------------------------------------------------- ClassLoader Methods
  837.  
  838.  
  839.      /**
  840.       * Add the specified URL to the classloader.
  841.       */
  842.      protected void addURL(URL url) {
  843.          super.addURL(url);
  844.          hasExternalRepositories = true;
  845.          repositoryURLs = null;
  846.      }
  847.  
  848.  
  849.     /**
  850.      * Find the specified class in our local repositories, if possible.  If
  851.      * not found, throw <code>ClassNotFoundException</code>.
  852.      *
  853.      * @param name Name of the class to be loaded
  854.      *
  855.      * @exception ClassNotFoundException if the class was not found
  856.      */
  857.     public Class findClass(String name) throws ClassNotFoundException {
  858.  
  859.         if (log.isDebugEnabled())
  860.             log.debug("    findClass(" + name + ")");
  861.  
  862.         // Cannot load anything from local repositories if class loader is stopped
  863.         if (!started) {
  864.             throw new ClassNotFoundException(name);
  865.         }
  866.  
  867.         // (1) Permission to define this class when using a SecurityManager
  868.         if (securityManager != null) {
  869.             int i = name.lastIndexOf('.');
  870.             if (i >= 0) {
  871.                 try {
  872.                     if (log.isTraceEnabled())
  873.                         log.trace("      securityManager.checkPackageDefinition");
  874.                     securityManager.checkPackageDefinition(name.substring(0,i));
  875.                 } catch (Exception se) {
  876.                     if (log.isTraceEnabled())
  877.                         log.trace("      -->Exception-->ClassNotFoundException", se);
  878.                     throw new ClassNotFoundException(name, se);
  879.                 }
  880.             }
  881.         }
  882.  
  883.         // Ask our superclass to locate this class, if possible
  884.         // (throws ClassNotFoundException if it is not found)
  885.         Class clazz = null;
  886.         try {
  887.             if (log.isTraceEnabled())
  888.                 log.trace("      findClassInternal(" + name + ")");
  889.             try {
  890.                 clazz = findClassInternal(name);
  891.             } catch(ClassNotFoundException cnfe) {
  892.                 if (!hasExternalRepositories) {
  893.                     throw cnfe;
  894.                 }
  895.             } catch(AccessControlException ace) {
  896.                 throw new ClassNotFoundException(name, ace);
  897.             } catch (RuntimeException e) {
  898.                 if (log.isTraceEnabled())
  899.                     log.trace("      -->RuntimeException Rethrown", e);
  900.                 throw e;
  901.             }
  902.             if ((clazz == null) && hasExternalRepositories) {
  903.                 try {
  904.                     synchronized (this) {
  905.                         clazz = super.findClass(name);
  906.                     }
  907.                 } catch(AccessControlException ace) {
  908.                     throw new ClassNotFoundException(name, ace);
  909.                 } catch (RuntimeException e) {
  910.                     if (log.isTraceEnabled())
  911.                         log.trace("      -->RuntimeException Rethrown", e);
  912.                     throw e;
  913.                 }
  914.             }
  915.             if (clazz == null) {
  916.                 if (log.isDebugEnabled())
  917.                     log.debug("    --> Returning ClassNotFoundException");
  918.                 throw new ClassNotFoundException(name);
  919.             }
  920.         } catch (ClassNotFoundException e) {
  921.             if (log.isTraceEnabled())
  922.                 log.trace("    --> Passing on ClassNotFoundException");
  923.             throw e;
  924.         }
  925.  
  926.         // Return the class we have located
  927.         if (log.isTraceEnabled())
  928.             log.debug("      Returning class " + clazz);
  929.        
  930.         if ((log.isTraceEnabled()) && (clazz != null)) {
  931.             ClassLoader cl;
  932.             if (Globals.IS_SECURITY_ENABLED){
  933.                 cl = AccessController.doPrivileged(
  934.                     new PrivilegedGetClassLoader(clazz));
  935.             } else {
  936.                 cl = clazz.getClassLoader();
  937.             }
  938.             log.debug("      Loaded by " + cl.toString());
  939.         }
  940.         return (clazz);
  941.  
  942.     }
  943.  
  944.  
  945.     /**
  946.      * Find the specified resource in our local repository, and return a
  947.      * <code>URL</code> refering to it, or <code>null</code> if this resource
  948.      * cannot be found.
  949.      *
  950.      * @param name Name of the resource to be found
  951.      */
  952.     public URL findResource(final String name) {
  953.  
  954.         if (log.isDebugEnabled())
  955.             log.debug("    findResource(" + name + ")");
  956.  
  957.         URL url = null;
  958.  
  959.         ResourceEntry entry = (ResourceEntry) resourceEntries.get(name);
  960.         if (entry == null) {
  961.             entry = findResourceInternal(name, name);
  962.         }
  963.         if (entry != null) {
  964.             url = entry.source;
  965.         }
  966.  
  967.         if ((url == null) && hasExternalRepositories)
  968.             url = super.findResource(name);
  969.  
  970.         if (log.isDebugEnabled()) {
  971.             if (url != null)
  972.                 log.debug("    --> Returning '" + url.toString() + "'");
  973.             else
  974.                 log.debug("    --> Resource not found, returning null");
  975.         }
  976.         return (url);
  977.  
  978.     }
  979.  
  980.  
  981.     /**
  982.      * Return an enumeration of <code>URLs</code> representing all of the
  983.      * resources with the given name.  If no resources with this name are
  984.      * found, return an empty enumeration.
  985.      *
  986.      * @param name Name of the resources to be found
  987.      *
  988.      * @exception IOException if an input/output error occurs
  989.      */
  990.     public Enumeration findResources(String name) throws IOException {
  991.  
  992.         if (log.isDebugEnabled())
  993.             log.debug("    findResources(" + name + ")");
  994.  
  995.         Vector result = new Vector();
  996.  
  997.         int jarFilesLength = jarFiles.length;
  998.         int repositoriesLength = repositories.length;
  999.  
  1000.         int i;
  1001.  
  1002.         // Looking at the repositories
  1003.         for (i = 0; i < repositoriesLength; i++) {
  1004.             try {
  1005.                 String fullPath = repositories[i] + name;
  1006.                 resources.lookup(fullPath);
  1007.                 // Note : Not getting an exception here means the resource was
  1008.                 // found
  1009.                 try {
  1010.                     result.addElement(getURI(new File(files[i], name)));
  1011.                 } catch (MalformedURLException e) {
  1012.                     // Ignore
  1013.                 }
  1014.             } catch (NamingException e) {
  1015.             }
  1016.         }
  1017.  
  1018.         // Looking at the JAR files
  1019.         synchronized (jarFiles) {
  1020.             if (openJARs()) {
  1021.                 for (i = 0; i < jarFilesLength; i++) {
  1022.                     JarEntry jarEntry = jarFiles[i].getJarEntry(name);
  1023.                     if (jarEntry != null) {
  1024.                         try {
  1025.                             String jarFakeUrl = getURI(jarRealFiles[i]).toString();
  1026.                             jarFakeUrl = "jar:" + jarFakeUrl + "!/" + name;
  1027.                             result.addElement(new URL(jarFakeUrl));
  1028.                         } catch (MalformedURLException e) {
  1029.                             // Ignore
  1030.                         }
  1031.                     }
  1032.                 }
  1033.             }
  1034.         }
  1035.  
  1036.         // Adding the results of a call to the superclass
  1037.         if (hasExternalRepositories) {
  1038.  
  1039.             Enumeration otherResourcePaths = super.findResources(name);
  1040.  
  1041.             while (otherResourcePaths.hasMoreElements()) {
  1042.                 result.addElement(otherResourcePaths.nextElement());
  1043.             }
  1044.  
  1045.         }
  1046.  
  1047.         return result.elements();
  1048.  
  1049.     }
  1050.  
  1051.  
  1052.     /**
  1053.      * Find the resource with the given name.  A resource is some data
  1054.      * (images, audio, text, etc.) that can be accessed by class code in a
  1055.      * way that is independent of the location of the code.  The name of a
  1056.      * resource is a "/"-separated path name that identifies the resource.
  1057.      * If the resource cannot be found, return <code>null</code>.
  1058.      * <p>
  1059.      * This method searches according to the following algorithm, returning
  1060.      * as soon as it finds the appropriate URL.  If the resource cannot be
  1061.      * found, returns <code>null</code>.
  1062.      * <ul>
  1063.      * <li>If the <code>delegate</code> property is set to <code>true</code>,
  1064.      *     call the <code>getResource()</code> method of the parent class
  1065.      *     loader, if any.</li>
  1066.      * <li>Call <code>findResource()</code> to find this resource in our
  1067.      *     locally defined repositories.</li>
  1068.      * <li>Call the <code>getResource()</code> method of the parent class
  1069.      *     loader, if any.</li>
  1070.      * </ul>
  1071.      *
  1072.      * @param name Name of the resource to return a URL for
  1073.      */
  1074.     public URL getResource(String name) {
  1075.  
  1076.         if (log.isDebugEnabled())
  1077.             log.debug("getResource(" + name + ")");
  1078.         URL url = null;
  1079.  
  1080.         // (1) Delegate to parent if requested
  1081.         if (delegate) {
  1082.             if (log.isDebugEnabled())
  1083.                 log.debug("  Delegating to parent classloader " + parent);
  1084.             ClassLoader loader = parent;
  1085.             if (loader == null)
  1086.                 loader = system;
  1087.             url = loader.getResource(name);
  1088.             if (url != null) {
  1089.                 if (log.isDebugEnabled())
  1090.                     log.debug("  --> Returning '" + url.toString() + "'");
  1091.                 return (url);
  1092.             }
  1093.         }
  1094.  
  1095.         // (2) Search local repositories
  1096.         url = findResource(name);
  1097.         if (url != null) {
  1098.             // Locating the repository for special handling in the case
  1099.             // of a JAR
  1100.             if (antiJARLocking) {
  1101.                 ResourceEntry entry = (ResourceEntry) resourceEntries.get(name);
  1102.                 try {
  1103.                     String repository = entry.codeBase.toString();
  1104.                     if ((repository.endsWith(".jar"))
  1105.                             && (!(name.endsWith(".class")))) {
  1106.                         // Copy binary content to the work directory if not present
  1107.                         File resourceFile = new File(loaderDir, name);
  1108.                         url = getURI(resourceFile);
  1109.                     }
  1110.                 } catch (Exception e) {
  1111.                     // Ignore
  1112.                 }
  1113.             }
  1114.             if (log.isDebugEnabled())
  1115.                 log.debug("  --> Returning '" + url.toString() + "'");
  1116.             return (url);
  1117.         }
  1118.  
  1119.         // (3) Delegate to parent unconditionally if not already attempted
  1120.         if( !delegate ) {
  1121.             ClassLoader loader = parent;
  1122.             if (loader == null)
  1123.                 loader = system;
  1124.             url = loader.getResource(name);
  1125.             if (url != null) {
  1126.                 if (log.isDebugEnabled())
  1127.                     log.debug("  --> Returning '" + url.toString() + "'");
  1128.                 return (url);
  1129.             }
  1130.         }
  1131.  
  1132.         // (4) Resource was not found
  1133.         if (log.isDebugEnabled())
  1134.             log.debug("  --> Resource not found, returning null");
  1135.         return (null);
  1136.  
  1137.     }
  1138.  
  1139.  
  1140.     /**
  1141.      * Find the resource with the given name, and return an input stream
  1142.      * that can be used for reading it.  The search order is as described
  1143.      * for <code>getResource()</code>, after checking to see if the resource
  1144.      * data has been previously cached.  If the resource cannot be found,
  1145.      * return <code>null</code>.
  1146.      *
  1147.      * @param name Name of the resource to return an input stream for
  1148.      */
  1149.     public InputStream getResourceAsStream(String name) {
  1150.  
  1151.         if (log.isDebugEnabled())
  1152.             log.debug("getResourceAsStream(" + name + ")");
  1153.         InputStream stream = null;
  1154.  
  1155.         // (0) Check for a cached copy of this resource
  1156.         stream = findLoadedResource(name);
  1157.         if (stream != null) {
  1158.             if (log.isDebugEnabled())
  1159.                 log.debug("  --> Returning stream from cache");
  1160.             return (stream);
  1161.         }
  1162.  
  1163.         // (1) Delegate to parent if requested
  1164.         if (delegate) {
  1165.             if (log.isDebugEnabled())
  1166.                 log.debug("  Delegating to parent classloader " + parent);
  1167.             ClassLoader loader = parent;
  1168.             if (loader == null)
  1169.                 loader = system;
  1170.             stream = loader.getResourceAsStream(name);
  1171.             if (stream != null) {
  1172.                 // FIXME - cache???
  1173.                 if (log.isDebugEnabled())
  1174.                     log.debug("  --> Returning stream from parent");
  1175.                 return (stream);
  1176.             }
  1177.         }
  1178.  
  1179.         // (2) Search local repositories
  1180.         if (log.isDebugEnabled())
  1181.             log.debug("  Searching local repositories");
  1182.         URL url = findResource(name);
  1183.         if (url != null) {
  1184.             // FIXME - cache???
  1185.             if (log.isDebugEnabled())
  1186.                 log.debug("  --> Returning stream from local");
  1187.             stream = findLoadedResource(name);
  1188.             try {
  1189.                 if (hasExternalRepositories && (stream == null))
  1190.                     stream = url.openStream();
  1191.             } catch (IOException e) {
  1192.                 ; // Ignore
  1193.             }
  1194.             if (stream != null)
  1195.                 return (stream);
  1196.         }
  1197.  
  1198.         // (3) Delegate to parent unconditionally
  1199.         if (!delegate) {
  1200.             if (log.isDebugEnabled())
  1201.                 log.debug("  Delegating to parent classloader unconditionally " + parent);
  1202.             ClassLoader loader = parent;
  1203.             if (loader == null)
  1204.                 loader = system;
  1205.             stream = loader.getResourceAsStream(name);
  1206.             if (stream != null) {
  1207.                 // FIXME - cache???
  1208.                 if (log.isDebugEnabled())
  1209.                     log.debug("  --> Returning stream from parent");
  1210.                 return (stream);
  1211.             }
  1212.         }
  1213.  
  1214.         // (4) Resource was not found
  1215.         if (log.isDebugEnabled())
  1216.             log.debug("  --> Resource not found, returning null");
  1217.         return (null);
  1218.  
  1219.     }
  1220.  
  1221.  
  1222.     /**
  1223.      * Load the class with the specified name.  This method searches for
  1224.      * classes in the same manner as <code>loadClass(String, boolean)</code>
  1225.      * with <code>false</code> as the second argument.
  1226.      *
  1227.      * @param name Name of the class to be loaded
  1228.      *
  1229.      * @exception ClassNotFoundException if the class was not found
  1230.      */
  1231.     public Class loadClass(String name) throws ClassNotFoundException {
  1232.  
  1233.         return (loadClass(name, false));
  1234.  
  1235.     }
  1236.  
  1237.  
  1238.     /**
  1239.      * Load the class with the specified name, searching using the following
  1240.      * algorithm until it finds and returns the class.  If the class cannot
  1241.      * be found, returns <code>ClassNotFoundException</code>.
  1242.      * <ul>
  1243.      * <li>Call <code>findLoadedClass(String)</code> to check if the
  1244.      *     class has already been loaded.  If it has, the same
  1245.      *     <code>Class</code> object is returned.</li>
  1246.      * <li>If the <code>delegate</code> property is set to <code>true</code>,
  1247.      *     call the <code>loadClass()</code> method of the parent class
  1248.      *     loader, if any.</li>
  1249.      * <li>Call <code>findClass()</code> to find this class in our locally
  1250.      *     defined repositories.</li>
  1251.      * <li>Call the <code>loadClass()</code> method of our parent
  1252.      *     class loader, if any.</li>
  1253.      * </ul>
  1254.      * If the class was found using the above steps, and the
  1255.      * <code>resolve</code> flag is <code>true</code>, this method will then
  1256.      * call <code>resolveClass(Class)</code> on the resulting Class object.
  1257.      *
  1258.      * @param name Name of the class to be loaded
  1259.      * @param resolve If <code>true</code> then resolve the class
  1260.      *
  1261.      * @exception ClassNotFoundException if the class was not found
  1262.      */
  1263.     public Class loadClass(String name, boolean resolve)
  1264.         throws ClassNotFoundException {
  1265.  
  1266.         if (log.isDebugEnabled())
  1267.             log.debug("loadClass(" + name + ", " + resolve + ")");
  1268.         Class clazz = null;
  1269.  
  1270.         // Log access to stopped classloader
  1271.         if (!started) {
  1272.             try {
  1273.                 throw new IllegalStateException();
  1274.             } catch (IllegalStateException e) {
  1275.                 log.info(sm.getString("webappClassLoader.stopped", name), e);
  1276.             }
  1277.         }
  1278.  
  1279.         // (0) Check our previously loaded local class cache
  1280.         clazz = findLoadedClass0(name);
  1281.         if (clazz != null) {
  1282.             if (log.isDebugEnabled())
  1283.                 log.debug("  Returning class from cache");
  1284.             if (resolve)
  1285.                 resolveClass(clazz);
  1286.             return (clazz);
  1287.         }
  1288.  
  1289.         // (0.1) Check our previously loaded class cache
  1290.         clazz = findLoadedClass(name);
  1291.         if (clazz != null) {
  1292.             if (log.isDebugEnabled())
  1293.                 log.debug("  Returning class from cache");
  1294.             if (resolve)
  1295.                 resolveClass(clazz);
  1296.             return (clazz);
  1297.         }
  1298.  
  1299.         // (0.2) Try loading the class with the system class loader, to prevent
  1300.         //       the webapp from overriding J2SE classes
  1301.         try {
  1302.             clazz = system.loadClass(name);
  1303.             if (clazz != null) {
  1304.                 if (resolve)
  1305.                     resolveClass(clazz);
  1306.                 return (clazz);
  1307.             }
  1308.         } catch (ClassNotFoundException e) {
  1309.             // Ignore
  1310.         }
  1311.  
  1312.         // (0.5) Permission to access this class when using a SecurityManager
  1313.         if (securityManager != null) {
  1314.             int i = name.lastIndexOf('.');
  1315.             if (i >= 0) {
  1316.                 try {
  1317.                     securityManager.checkPackageAccess(name.substring(0,i));
  1318.                 } catch (SecurityException se) {
  1319.                     String error = "Security Violation, attempt to use " +
  1320.                         "Restricted Class: " + name;
  1321.                     log.info(error, se);
  1322.                     throw new ClassNotFoundException(error, se);
  1323.                 }
  1324.             }
  1325.         }
  1326.  
  1327.         boolean delegateLoad = delegate || filter(name);
  1328.  
  1329.         // (1) Delegate to our parent if requested
  1330.         if (delegateLoad) {
  1331.             if (log.isDebugEnabled())
  1332.                 log.debug("  Delegating to parent classloader1 " + parent);
  1333.             ClassLoader loader = parent;
  1334.             if (loader == null)
  1335.                 loader = system;
  1336.             try {
  1337.                 clazz = loader.loadClass(name);
  1338.                 if (clazz != null) {
  1339.                     if (log.isDebugEnabled())
  1340.                         log.debug("  Loading class from parent");
  1341.                     if (resolve)
  1342.                         resolveClass(clazz);
  1343.                     return (clazz);
  1344.                 }
  1345.             } catch (ClassNotFoundException e) {
  1346.                 ;
  1347.             }
  1348.         }
  1349.  
  1350.         // (2) Search local repositories
  1351.         if (log.isDebugEnabled())
  1352.             log.debug("  Searching local repositories");
  1353.         try {
  1354.             clazz = findClass(name);
  1355.             if (clazz != null) {
  1356.                 if (log.isDebugEnabled())
  1357.                     log.debug("  Loading class from local repository");
  1358.                 if (resolve)
  1359.                     resolveClass(clazz);
  1360.                 return (clazz);
  1361.             }
  1362.         } catch (ClassNotFoundException e) {
  1363.             ;
  1364.         }
  1365.  
  1366.         // (3) Delegate to parent unconditionally
  1367.         if (!delegateLoad) {
  1368.             if (log.isDebugEnabled())
  1369.                 log.debug("  Delegating to parent classloader at end: " + parent);
  1370.             ClassLoader loader = parent;
  1371.             if (loader == null)
  1372.                 loader = system;
  1373.             try {
  1374.                 clazz = loader.loadClass(name);
  1375.                 if (clazz != null) {
  1376.                     if (log.isDebugEnabled())
  1377.                         log.debug("  Loading class from parent");
  1378.                     if (resolve)
  1379.                         resolveClass(clazz);
  1380.                     return (clazz);
  1381.                 }
  1382.             } catch (ClassNotFoundException e) {
  1383.                 ;
  1384.             }
  1385.         }
  1386.  
  1387.         throw new ClassNotFoundException(name);
  1388.     }
  1389.  
  1390.  
  1391.     /**
  1392.      * Get the Permissions for a CodeSource.  If this instance
  1393.      * of WebappClassLoader is for a web application context,
  1394.      * add read FilePermission or JndiPermissions for the base
  1395.      * directory (if unpacked),
  1396.      * the context URL, and jar file resources.
  1397.      *
  1398.      * @param codeSource where the code was loaded from
  1399.      * @return PermissionCollection for CodeSource
  1400.      */
  1401.     protected PermissionCollection getPermissions(CodeSource codeSource) {
  1402.  
  1403.         String codeUrl = codeSource.getLocation().toString();
  1404.         PermissionCollection pc;
  1405.         if ((pc = (PermissionCollection)loaderPC.get(codeUrl)) == null) {
  1406.             pc = super.getPermissions(codeSource);
  1407.             if (pc != null) {
  1408.                 Iterator perms = permissionList.iterator();
  1409.                 while (perms.hasNext()) {
  1410.                     Permission p = (Permission)perms.next();
  1411.                     pc.add(p);
  1412.                 }
  1413.                 loaderPC.put(codeUrl,pc);
  1414.             }
  1415.         }
  1416.         return (pc);
  1417.  
  1418.     }
  1419.  
  1420.  
  1421.     /**
  1422.      * Returns the search path of URLs for loading classes and resources.
  1423.      * This includes the original list of URLs specified to the constructor,
  1424.      * along with any URLs subsequently appended by the addURL() method.
  1425.      * @return the search path of URLs for loading classes and resources.
  1426.      */
  1427.     public URL[] getURLs() {
  1428.  
  1429.         if (repositoryURLs != null) {
  1430.             return repositoryURLs;
  1431.         }
  1432.  
  1433.         URL[] external = super.getURLs();
  1434.  
  1435.         int filesLength = files.length;
  1436.         int jarFilesLength = jarRealFiles.length;
  1437.         int length = filesLength + jarFilesLength + external.length;
  1438.         int i;
  1439.  
  1440.         try {
  1441.  
  1442.             URL[] urls = new URL[length];
  1443.             for (i = 0; i < length; i++) {
  1444.                 if (i < filesLength) {
  1445.                     urls[i] = getURL(files[i], true);
  1446.                 } else if (i < filesLength + jarFilesLength) {
  1447.                     urls[i] = getURL(jarRealFiles[i - filesLength], true);
  1448.                 } else {
  1449.                     urls[i] = external[i - filesLength - jarFilesLength];
  1450.                 }
  1451.             }
  1452.  
  1453.             repositoryURLs = urls;
  1454.  
  1455.         } catch (MalformedURLException e) {
  1456.             repositoryURLs = new URL[0];
  1457.         }
  1458.  
  1459.         return repositoryURLs;
  1460.  
  1461.     }
  1462.  
  1463.  
  1464.     // ------------------------------------------------------ Lifecycle Methods
  1465.  
  1466.  
  1467.     /**
  1468.      * Add a lifecycle event listener to this component.
  1469.      *
  1470.      * @param listener The listener to add
  1471.      */
  1472.     public void addLifecycleListener(LifecycleListener listener) {
  1473.     }
  1474.  
  1475.  
  1476.     /**
  1477.      * Get the lifecycle listeners associated with this lifecycle. If this
  1478.      * Lifecycle has no listeners registered, a zero-length array is returned.
  1479.      */
  1480.     public LifecycleListener[] findLifecycleListeners() {
  1481.         return new LifecycleListener[0];
  1482.     }
  1483.  
  1484.  
  1485.     /**
  1486.      * Remove a lifecycle event listener from this component.
  1487.      *
  1488.      * @param listener The listener to remove
  1489.      */
  1490.     public void removeLifecycleListener(LifecycleListener listener) {
  1491.     }
  1492.  
  1493.  
  1494.     /**
  1495.      * Start the class loader.
  1496.      *
  1497.      * @exception LifecycleException if a lifecycle error occurs
  1498.      */
  1499.     public void start() throws LifecycleException {
  1500.  
  1501.         started = true;
  1502.         String encoding = null;
  1503.         try {
  1504.             encoding = System.getProperty("file.encoding");
  1505.         } catch (Exception e) {
  1506.             return;
  1507.         }
  1508.         if (encoding.indexOf("EBCDIC")!=-1) {
  1509.             needConvert = true;
  1510.         }
  1511.  
  1512.     }
  1513.  
  1514.  
  1515.     /**
  1516.      * Stop the class loader.
  1517.      *
  1518.      * @exception LifecycleException if a lifecycle error occurs
  1519.      */
  1520.     public void stop() throws LifecycleException {
  1521.  
  1522.         // Clearing references should be done before setting started to
  1523.         // false, due to possible side effects
  1524.         clearReferences();
  1525.  
  1526.         started = false;
  1527.  
  1528.         int length = files.length;
  1529.         for (int i = 0; i < length; i++) {
  1530.             files[i] = null;
  1531.         }
  1532.  
  1533.         length = jarFiles.length;
  1534.         for (int i = 0; i < length; i++) {
  1535.             try {
  1536.                 if (jarFiles[i] != null) {
  1537.                     jarFiles[i].close();
  1538.                 }
  1539.             } catch (IOException e) {
  1540.                 // Ignore
  1541.             }
  1542.             jarFiles[i] = null;
  1543.         }
  1544.  
  1545.         notFoundResources.clear();
  1546.         resourceEntries.clear();
  1547.         resources = null;
  1548.         repositories = null;
  1549.         repositoryURLs = null;
  1550.         files = null;
  1551.         jarFiles = null;
  1552.         jarRealFiles = null;
  1553.         jarPath = null;
  1554.         jarNames = null;
  1555.         lastModifiedDates = null;
  1556.         paths = null;
  1557.         hasExternalRepositories = false;
  1558.         parent = null;
  1559.  
  1560.         permissionList.clear();
  1561.         loaderPC.clear();
  1562.  
  1563.         if (loaderDir != null) {
  1564.             deleteDir(loaderDir);
  1565.         }
  1566.  
  1567.     }
  1568.  
  1569.  
  1570.     /**
  1571.      * Used to periodically signal to the classloader to release
  1572.      * JAR resources.
  1573.      */
  1574.     public void closeJARs(boolean force) {
  1575.         if (jarFiles.length > 0) {
  1576.                 synchronized (jarFiles) {
  1577.                     if (force || (System.currentTimeMillis()
  1578.                                   > (lastJarAccessed + 90000))) {
  1579.                         for (int i = 0; i < jarFiles.length; i++) {
  1580.                             try {
  1581.                                 if (jarFiles[i] != null) {
  1582.                                     jarFiles[i].close();
  1583.                                     jarFiles[i] = null;
  1584.                                 }
  1585.                             } catch (IOException e) {
  1586.                                 if (log.isDebugEnabled()) {
  1587.                                     log.debug("Failed to close JAR", e);
  1588.                                 }
  1589.                             }
  1590.                         }
  1591.                     }
  1592.                 }
  1593.         }
  1594.     }
  1595.  
  1596.  
  1597.     // ------------------------------------------------------ Protected Methods
  1598.  
  1599.    
  1600.     /**
  1601.      * Clear references.
  1602.      */
  1603.     protected void clearReferences() {
  1604.  
  1605.         // Unregister any JDBC drivers loaded by this classloader
  1606.         Enumeration drivers = DriverManager.getDrivers();
  1607.         while (drivers.hasMoreElements()) {
  1608.             Driver driver = (Driver) drivers.nextElement();
  1609.             if (driver.getClass().getClassLoader() == this) {
  1610.                 try {
  1611.                     DriverManager.deregisterDriver(driver);
  1612.                 } catch (SQLException e) {
  1613.                     log.warn("SQL driver deregistration failed", e);
  1614.                 }
  1615.             }
  1616.         }
  1617.        
  1618.         // Null out any static or final fields from loaded classes,
  1619.         // as a workaround for apparent garbage collection bugs
  1620.         if (ENABLE_CLEAR_REFERENCES) {
  1621.             Iterator loadedClasses = ((HashMap) resourceEntries.clone()).values().iterator();
  1622.             while (loadedClasses.hasNext()) {
  1623.                 ResourceEntry entry = (ResourceEntry) loadedClasses.next();
  1624.                 if (entry.loadedClass != null) {
  1625.                     Class clazz = entry.loadedClass;
  1626.                     try {
  1627.                         Field[] fields = clazz.getDeclaredFields();
  1628.                         for (int i = 0; i < fields.length; i++) {
  1629.                             Field field = fields[i];
  1630.                             int mods = field.getModifiers();
  1631.                             if (field.getType().isPrimitive()
  1632.                                     || (field.getName().indexOf("$") != -1)) {
  1633.                                 continue;
  1634.                             }
  1635.                             if (Modifier.isStatic(mods)) {
  1636.                                 try {
  1637.                                     field.setAccessible(true);
  1638.                                     if (Modifier.isFinal(mods)) {
  1639.                                         if (!((field.getType().getName().startsWith("java."))
  1640.                                                 || (field.getType().getName().startsWith("javax.")))) {
  1641.                                             nullInstance(field.get(null));
  1642.                                         }
  1643.                                     } else {
  1644.                                         field.set(null, null);
  1645.                                         if (log.isDebugEnabled()) {
  1646.                                             log.debug("Set field " + field.getName()
  1647.                                                     + " to null in class " + clazz.getName());
  1648.                                         }
  1649.                                     }
  1650.                                 } catch (Throwable t) {
  1651.                                     if (log.isDebugEnabled()) {
  1652.                                         log.debug("Could not set field " + field.getName()
  1653.                                                 + " to null in class " + clazz.getName(), t);
  1654.                                     }
  1655.                                 }
  1656.                             }
  1657.                         }
  1658.                     } catch (Throwable t) {
  1659.                         if (log.isDebugEnabled()) {
  1660.                             log.debug("Could not clean fields for class " + clazz.getName(), t);
  1661.                         }
  1662.                     }
  1663.                 }
  1664.             }
  1665.         }
  1666.        
  1667.          // Clear the IntrospectionUtils cache.
  1668.         IntrospectionUtils.clear();
  1669.        
  1670.         // Clear the classloader reference in common-logging
  1671.         org.apache.juli.logging.LogFactory.release(this);
  1672.        
  1673.         // Clear the classloader reference in the VM's bean introspector
  1674.         java.beans.Introspector.flushCaches();
  1675.  
  1676.     }
  1677.  
  1678.  
  1679.     protected void nullInstance(Object instance) {
  1680.         if (instance == null) {
  1681.             return;
  1682.         }
  1683.         Field[] fields = instance.getClass().getDeclaredFields();
  1684.         for (int i = 0; i < fields.length; i++) {
  1685.             Field field = fields[i];
  1686.             int mods = field.getModifiers();
  1687.             if (field.getType().isPrimitive()
  1688.                     || (field.getName().indexOf("$") != -1)) {
  1689.                 continue;
  1690.             }
  1691.             try {
  1692.                 field.setAccessible(true);
  1693.                 if (Modifier.isStatic(mods) && Modifier.isFinal(mods)) {
  1694.                     // Doing something recursively is too risky
  1695.                     continue;
  1696.                 } else {
  1697.                     Object value = field.get(instance);
  1698.                     if (null != value) {
  1699.                         Class valueClass = value.getClass();
  1700.                         if (!loadedByThisOrChild(valueClass)) {
  1701.                             if (log.isDebugEnabled()) {
  1702.                                 log.debug("Not setting field " + field.getName() +
  1703.                                         " to null in object of class " +
  1704.                                         instance.getClass().getName() +
  1705.                                         " because the referenced object was of type " +
  1706.                                         valueClass.getName() +
  1707.                                         " which was not loaded by this WebappClassLoader.");
  1708.                             }
  1709.                         } else {
  1710.                             field.set(instance, null);
  1711.                             if (log.isDebugEnabled()) {
  1712.                                 log.debug("Set field " + field.getName()
  1713.                                         + " to null in class " + instance.getClass().getName());
  1714.                             }
  1715.                         }
  1716.                     }
  1717.                 }
  1718.             } catch (Throwable t) {
  1719.                 if (log.isDebugEnabled()) {
  1720.                     log.debug("Could not set field " + field.getName()
  1721.                             + " to null in object instance of class "
  1722.                             + instance.getClass().getName(), t);
  1723.                 }
  1724.             }
  1725.         }
  1726.     }
  1727.  
  1728.  
  1729.     /**
  1730.      * Determine whether a class was loaded by this class loader or one of
  1731.      * its child class loaders.
  1732.      */
  1733.     protected boolean loadedByThisOrChild(Class clazz)
  1734.     {
  1735.         boolean result = false;
  1736.         for (ClassLoader classLoader = clazz.getClassLoader();
  1737.                 null != classLoader; classLoader = classLoader.getParent()) {
  1738.             if (classLoader.equals(this)) {
  1739.                 result = true;
  1740.                 break;
  1741.             }
  1742.         }
  1743.         return result;
  1744.     }    
  1745.  
  1746.  
  1747.     /**
  1748.      * Used to periodically signal to the classloader to release JAR resources.
  1749.      */
  1750.     protected boolean openJARs() {
  1751.         if (started && (jarFiles.length > 0)) {
  1752.             lastJarAccessed = System.currentTimeMillis();
  1753.             if (jarFiles[0] == null) {
  1754.                 for (int i = 0; i < jarFiles.length; i++) {
  1755.                     try {
  1756.                         jarFiles[i] = new JarFile(jarRealFiles[i]);
  1757.                     } catch (IOException e) {
  1758.                         if (log.isDebugEnabled()) {
  1759.                             log.debug("Failed to open JAR", e);
  1760.                         }
  1761.                         return false;
  1762.                     }
  1763.                 }
  1764.             }
  1765.         }
  1766.         return true;
  1767.     }
  1768.  
  1769.  
  1770.     /**
  1771.      * Find specified class in local repositories.
  1772.      *
  1773.      * @return the loaded class, or null if the class isn't found
  1774.      */
  1775.     protected Class findClassInternal(String name)
  1776.         throws ClassNotFoundException {
  1777.  
  1778.         if (!validate(name))
  1779.             throw new ClassNotFoundException(name);
  1780.  
  1781.         String tempPath = name.replace('.', '/');
  1782.         String classPath = tempPath + ".class";
  1783.  
  1784.         ResourceEntry entry = null;
  1785.  
  1786.         entry = findResourceInternal(name, classPath);
  1787.  
  1788.         if (entry == null)
  1789.             throw new ClassNotFoundException(name);
  1790.  
  1791.         Class clazz = entry.loadedClass;
  1792.         if (clazz != null)
  1793.             return clazz;
  1794.  
  1795.         synchronized (this) {
  1796.             clazz = entry.loadedClass;
  1797.             if (clazz != null)
  1798.                 return clazz;
  1799.  
  1800.             if (entry.binaryContent == null)
  1801.                 throw new ClassNotFoundException(name);
  1802.  
  1803.             // Looking up the package
  1804.            String packageName = null;
  1805.             int pos = name.lastIndexOf('.');
  1806.             if (pos != -1)
  1807.                 packageName = name.substring(0, pos);
  1808.        
  1809.             Package pkg = null;
  1810.        
  1811.             if (packageName != null) {
  1812.                 pkg = getPackage(packageName);
  1813.                 // Define the package (if null)
  1814.                 if (pkg == null) {
  1815.                     try {
  1816.                         if (entry.manifest == null) {
  1817.                             definePackage(packageName, null, null, null, null,
  1818.                                     null, null, null);
  1819.                         } else {
  1820.                             definePackage(packageName, entry.manifest,
  1821.                                     entry.codeBase);
  1822.                         }
  1823.                     } catch (IllegalArgumentException e) {
  1824.                         // Ignore: normal error due to dual definition of package
  1825.                     }
  1826.                     pkg = getPackage(packageName);
  1827.                 }
  1828.             }
  1829.    
  1830.             if (securityManager != null) {
  1831.  
  1832.                 // Checking sealing
  1833.                 if (pkg != null) {
  1834.                     boolean sealCheck = true;
  1835.                     if (pkg.isSealed()) {
  1836.                         sealCheck = pkg.isSealed(entry.codeBase);
  1837.                     } else {
  1838.                         sealCheck = (entry.manifest == null)
  1839.                             || !isPackageSealed(packageName, entry.manifest);
  1840.                     }
  1841.                     if (!sealCheck)
  1842.                         throw new SecurityException
  1843.                             ("Sealing violation loading " + name + " : Package "
  1844.                              + packageName + " is sealed.");
  1845.                 }
  1846.    
  1847.             }
  1848.  
  1849.             try {
  1850.                 clazz = defineClass(name, entry.binaryContent, 0,
  1851.                         entry.binaryContent.length,
  1852.                         new CodeSource(entry.codeBase, entry.certificates));
  1853.             } catch (UnsupportedClassVersionError ucve) {
  1854.                 throw new UnsupportedClassVersionError(
  1855.                         ucve.getLocalizedMessage() + " " +
  1856.                         sm.getString("webappClassLoader.wrongVersion",
  1857.                                 name));
  1858.             }
  1859.             entry.loadedClass = clazz;
  1860.             entry.binaryContent = null;
  1861.             entry.source = null;
  1862.             entry.codeBase = null;
  1863.             entry.manifest = null;
  1864.             entry.certificates = null;
  1865.         }
  1866.        
  1867.         return clazz;
  1868.  
  1869.     }
  1870.  
  1871.     /**
  1872.      * Find specified resource in local repositories. This block
  1873.      * will execute under an AccessControl.doPrivilege block.
  1874.      *
  1875.      * @return the loaded resource, or null if the resource isn't found
  1876.      */
  1877.     protected ResourceEntry findResourceInternal(File file, String path){
  1878.         ResourceEntry entry = new ResourceEntry();
  1879.         try {
  1880.             entry.source = getURI(new File(file, path));
  1881.             entry.codeBase = getURL(new File(file, path), false);
  1882.         } catch (MalformedURLException e) {
  1883.             return null;
  1884.         }  
  1885.         return entry;
  1886.     }
  1887.    
  1888.  
  1889.     /**
  1890.      * Find specified resource in local repositories.
  1891.      *
  1892.      * @return the loaded resource, or null if the resource isn't found
  1893.      */
  1894.     protected ResourceEntry findResourceInternal(String name, String path) {
  1895.  
  1896.         if (!started) {
  1897.             log.info(sm.getString("webappClassLoader.stopped", name));
  1898.             return null;
  1899.         }
  1900.  
  1901.         if ((name == null) || (path == null))
  1902.             return null;
  1903.  
  1904.         ResourceEntry entry = (ResourceEntry) resourceEntries.get(name);
  1905.         if (entry != null)
  1906.             return entry;
  1907.  
  1908.         int contentLength = -1;
  1909.         InputStream binaryStream = null;
  1910.  
  1911.         int jarFilesLength = jarFiles.length;
  1912.         int repositoriesLength = repositories.length;
  1913.  
  1914.         int i;
  1915.  
  1916.         Resource resource = null;
  1917.  
  1918.         boolean fileNeedConvert = false;
  1919.  
  1920.         for (i = 0; (entry == null) && (i < repositoriesLength); i++) {
  1921.             try {
  1922.  
  1923.                 String fullPath = repositories[i] + path;
  1924.  
  1925.                 Object lookupResult = resources.lookup(fullPath);
  1926.                 if (lookupResult instanceof Resource) {
  1927.                     resource = (Resource) lookupResult;
  1928.                 }
  1929.  
  1930.                 // Note : Not getting an exception here means the resource was
  1931.                 // found
  1932.                  if (securityManager != null) {
  1933.                     PrivilegedAction dp =
  1934.                         new PrivilegedFindResource(files[i], path);
  1935.                     entry = (ResourceEntry)AccessController.doPrivileged(dp);
  1936.                  } else {
  1937.                     entry = findResourceInternal(files[i], path);
  1938.                  }
  1939.  
  1940.                 ResourceAttributes attributes =
  1941.                     (ResourceAttributes) resources.getAttributes(fullPath);
  1942.                 contentLength = (int) attributes.getContentLength();
  1943.                 entry.lastModified = attributes.getLastModified();
  1944.  
  1945.                 if (resource != null) {
  1946.  
  1947.  
  1948.                     try {
  1949.                         binaryStream = resource.streamContent();
  1950.                     } catch (IOException e) {
  1951.                         return null;
  1952.                     }
  1953.  
  1954.                     if (needConvert) {
  1955.                         if (path.endsWith(".properties")) {
  1956.                             fileNeedConvert = true;
  1957.                         }
  1958.                     }
  1959.  
  1960.                     // Register the full path for modification checking
  1961.                     // Note: Only syncing on a 'constant' object is needed
  1962.                     synchronized (allPermission) {
  1963.  
  1964.                         int j;
  1965.  
  1966.                         long[] result2 =
  1967.                             new long[lastModifiedDates.length + 1];
  1968.                         for (j = 0; j < lastModifiedDates.length; j++) {
  1969.                             result2[j] = lastModifiedDates[j];
  1970.                         }
  1971.                         result2[lastModifiedDates.length] = entry.lastModified;
  1972.                         lastModifiedDates = result2;
  1973.  
  1974.                         String[] result = new String[paths.length + 1];
  1975.                         for (j = 0; j < paths.length; j++) {
  1976.                             result[j] = paths[j];
  1977.                         }
  1978.                         result[paths.length] = fullPath;
  1979.                         paths = result;
  1980.  
  1981.                     }
  1982.  
  1983.                 }
  1984.  
  1985.             } catch (NamingException e) {
  1986.             }
  1987.         }
  1988.  
  1989.         if ((entry == null) && (notFoundResources.containsKey(name)))
  1990.             return null;
  1991.  
  1992.         JarEntry jarEntry = null;
  1993.  
  1994.         synchronized (jarFiles) {
  1995.  
  1996.             if (!openJARs()) {
  1997.                 return null;
  1998.             }
  1999.             for (i = 0; (entry == null) && (i < jarFilesLength); i++) {
  2000.  
  2001.                 jarEntry = jarFiles[i].getJarEntry(path);
  2002.  
  2003.                 if (jarEntry != null) {
  2004.  
  2005.                     entry = new ResourceEntry();
  2006.                     try {
  2007.                         entry.codeBase = getURL(jarRealFiles[i], false);
  2008.                         String jarFakeUrl = getURI(jarRealFiles[i]).toString();
  2009.                         jarFakeUrl = "jar:" + jarFakeUrl + "!/" + path;
  2010.                         entry.source = new URL(jarFakeUrl);
  2011.                         entry.lastModified = jarRealFiles[i].lastModified();
  2012.                     } catch (MalformedURLException e) {
  2013.                         return null;
  2014.                     }
  2015.                     contentLength = (int) jarEntry.getSize();
  2016.                     try {
  2017.                         entry.manifest = jarFiles[i].getManifest();
  2018.                         binaryStream = jarFiles[i].getInputStream(jarEntry);
  2019.                     } catch (IOException e) {
  2020.                         return null;
  2021.                     }
  2022.  
  2023.                     // Extract resources contained in JAR to the workdir
  2024.                     if (antiJARLocking && !(path.endsWith(".class"))) {
  2025.                         byte[] buf = new byte[1024];
  2026.                         File resourceFile = new File
  2027.                             (loaderDir, jarEntry.getName());
  2028.                         if (!resourceFile.exists()) {
  2029.                             Enumeration entries = jarFiles[i].entries();
  2030.                             while (entries.hasMoreElements()) {
  2031.                                 JarEntry jarEntry2 =
  2032.                                     (JarEntry) entries.nextElement();
  2033.                                 if (!(jarEntry2.isDirectory())
  2034.                                     && (!jarEntry2.getName().endsWith
  2035.                                         (".class"))) {
  2036.                                     resourceFile = new File
  2037.                                         (loaderDir, jarEntry2.getName());
  2038.                                     resourceFile.getParentFile().mkdirs();
  2039.                                     FileOutputStream os = null;
  2040.                                     InputStream is = null;
  2041.                                     try {
  2042.                                         is = jarFiles[i].getInputStream
  2043.                                             (jarEntry2);
  2044.                                         os = new FileOutputStream
  2045.                                             (resourceFile);
  2046.                                         while (true) {
  2047.                                             int n = is.read(buf);
  2048.                                             if (n <= 0) {
  2049.                                                 break;
  2050.                                             }
  2051.                                             os.write(buf, 0, n);
  2052.                                         }
  2053.                                     } catch (IOException e) {
  2054.                                         // Ignore
  2055.                                     } finally {
  2056.                                         try {
  2057.                                             if (is != null) {
  2058.                                                 is.close();
  2059.                                             }
  2060.                                         } catch (IOException e) {
  2061.                                         }
  2062.                                         try {
  2063.                                             if (os != null) {
  2064.                                                 os.close();
  2065.                                             }
  2066.                                         } catch (IOException e) {
  2067.                                         }
  2068.                                     }
  2069.                                 }
  2070.                             }
  2071.                         }
  2072.                     }
  2073.  
  2074.                 }
  2075.  
  2076.             }
  2077.  
  2078.             if (entry == null) {
  2079.                 synchronized (notFoundResources) {
  2080.                     notFoundResources.put(name, name);
  2081.                 }
  2082.                 return null;
  2083.             }
  2084.  
  2085.             if (binaryStream != null) {
  2086.  
  2087.                 byte[] binaryContent = new byte[contentLength];
  2088.  
  2089.                 int pos = 0;
  2090.                 try {
  2091.  
  2092.                     while (true) {
  2093.                         int n = binaryStream.read(binaryContent, pos,
  2094.                                                   binaryContent.length - pos);
  2095.                         if (n <= 0)
  2096.                             break;
  2097.                         pos += n;
  2098.                     }
  2099.                     binaryStream.close();
  2100.                 } catch (IOException e) {
  2101.                     e.printStackTrace();
  2102.                     return null;
  2103.                 } catch (Exception e) {
  2104.                     e.printStackTrace();
  2105.                     return null;
  2106.                 }
  2107.  
  2108.                 if (fileNeedConvert) {
  2109.                     String str = new String(binaryContent,0,pos);
  2110.                     try {
  2111.                         binaryContent = str.getBytes("UTF-8");
  2112.                     } catch (Exception e) {
  2113.                         return null;
  2114.                     }
  2115.                 }
  2116.                 entry.binaryContent = binaryContent;
  2117.  
  2118.                 // The certificates are only available after the JarEntry
  2119.                 // associated input stream has been fully read
  2120.                 if (jarEntry != null) {
  2121.                     entry.certificates = jarEntry.getCertificates();
  2122.                 }
  2123.  
  2124.             }
  2125.  
  2126.         }
  2127.  
  2128.         // Add the entry in the local resource repository
  2129.         synchronized (resourceEntries) {
  2130.             // Ensures that all the threads which may be in a race to load
  2131.             // a particular class all end up with the same ResourceEntry
  2132.             // instance
  2133.             ResourceEntry entry2 = (ResourceEntry) resourceEntries.get(name);
  2134.             if (entry2 == null) {
  2135.                 resourceEntries.put(name, entry);
  2136.             } else {
  2137.                 entry = entry2;
  2138.             }
  2139.         }
  2140.  
  2141.         return entry;
  2142.  
  2143.     }
  2144.  
  2145.  
  2146.     /**
  2147.      * Returns true if the specified package name is sealed according to the
  2148.      * given manifest.
  2149.      */
  2150.     protected boolean isPackageSealed(String name, Manifest man) {
  2151.  
  2152.         String path = name.replace('.', '/') + '/';
  2153.         Attributes attr = man.getAttributes(path);
  2154.         String sealed = null;
  2155.         if (attr != null) {
  2156.             sealed = attr.getValue(Name.SEALED);
  2157.         }
  2158.         if (sealed == null) {
  2159.             if ((attr = man.getMainAttributes()) != null) {
  2160.                 sealed = attr.getValue(Name.SEALED);
  2161.             }
  2162.         }
  2163.         return "true".equalsIgnoreCase(sealed);
  2164.  
  2165.     }
  2166.  
  2167.  
  2168.     /**
  2169.      * Finds the resource with the given name if it has previously been
  2170.      * loaded and cached by this class loader, and return an input stream
  2171.      * to the resource data.  If this resource has not been cached, return
  2172.      * <code>null</code>.
  2173.      *
  2174.      * @param name Name of the resource to return
  2175.      */
  2176.     protected InputStream findLoadedResource(String name) {
  2177.  
  2178.         ResourceEntry entry = (ResourceEntry) resourceEntries.get(name);
  2179.         if (entry != null) {
  2180.             if (entry.binaryContent != null)
  2181.                 return new ByteArrayInputStream(entry.binaryContent);
  2182.         }
  2183.         return (null);
  2184.  
  2185.     }
  2186.  
  2187.  
  2188.     /**
  2189.      * Finds the class with the given name if it has previously been
  2190.      * loaded and cached by this class loader, and return the Class object.
  2191.      * If this class has not been cached, return <code>null</code>.
  2192.      *
  2193.      * @param name Name of the resource to return
  2194.      */
  2195.     protected Class findLoadedClass0(String name) {
  2196.  
  2197.         ResourceEntry entry = (ResourceEntry) resourceEntries.get(name);
  2198.         if (entry != null) {
  2199.             return entry.loadedClass;
  2200.         }
  2201.         return (null);  // FIXME - findLoadedResource()
  2202.  
  2203.     }
  2204.  
  2205.  
  2206.     /**
  2207.      * Refresh the system policy file, to pick up eventual changes.
  2208.      */
  2209.     protected void refreshPolicy() {
  2210.  
  2211.         try {
  2212.             // The policy file may have been modified to adjust
  2213.             // permissions, so we're reloading it when loading or
  2214.             // reloading a Context
  2215.             Policy policy = Policy.getPolicy();
  2216.             policy.refresh();
  2217.         } catch (AccessControlException e) {
  2218.             // Some policy files may restrict this, even for the core,
  2219.             // so this exception is ignored
  2220.         }
  2221.  
  2222.     }
  2223.  
  2224.  
  2225.     /**
  2226.      * Filter classes.
  2227.      *
  2228.      * @param name class name
  2229.      * @return true if the class should be filtered
  2230.      */
  2231.     protected boolean filter(String name) {
  2232.  
  2233.         if (name == null)
  2234.             return false;
  2235.  
  2236.         // Looking up the package
  2237.        String packageName = null;
  2238.         int pos = name.lastIndexOf('.');
  2239.         if (pos != -1)
  2240.             packageName = name.substring(0, pos);
  2241.         else
  2242.             return false;
  2243.  
  2244.         for (int i = 0; i < packageTriggers.length; i++) {
  2245.             if (packageName.startsWith(packageTriggers[i]))
  2246.                 return true;
  2247.         }
  2248.  
  2249.         return false;
  2250.  
  2251.     }
  2252.  
  2253.  
  2254.     /**
  2255.      * Validate a classname. As per SRV.9.7.2, we must restict loading of
  2256.      * classes from J2SE (java.*) and classes of the servlet API
  2257.      * (javax.servlet.*). That should enhance robustness and prevent a number
  2258.      * of user error (where an older version of servlet.jar would be present
  2259.      * in /WEB-INF/lib).
  2260.      *
  2261.      * @param name class name
  2262.      * @return true if the name is valid
  2263.      */
  2264.     protected boolean validate(String name) {
  2265.  
  2266.         if (name == null)
  2267.             return false;
  2268.         if (name.startsWith("java."))
  2269.             return false;
  2270.  
  2271.         return true;
  2272.  
  2273.     }
  2274.  
  2275.  
  2276.     /**
  2277.      * Check the specified JAR file, and return <code>true</code> if it does
  2278.      * not contain any of the trigger classes.
  2279.      *
  2280.      * @param jarfile The JAR file to be checked
  2281.      *
  2282.      * @exception IOException if an input/output error occurs
  2283.      */
  2284.     protected boolean validateJarFile(File jarfile)
  2285.         throws IOException {
  2286.  
  2287.         if (triggers == null)
  2288.             return (true);
  2289.         JarFile jarFile = new JarFile(jarfile);
  2290.         for (int i = 0; i < triggers.length; i++) {
  2291.             Class clazz = null;
  2292.             try {
  2293.                 if (parent != null) {
  2294.                     clazz = parent.loadClass(triggers[i]);
  2295.                 } else {
  2296.                     clazz = Class.forName(triggers[i]);
  2297.                 }
  2298.             } catch (Throwable t) {
  2299.                 clazz = null;
  2300.             }
  2301.             if (clazz == null)
  2302.                 continue;
  2303.             String name = triggers[i].replace('.', '/') + ".class";
  2304.             if (log.isDebugEnabled())
  2305.                 log.debug(" Checking for " + name);
  2306.             JarEntry jarEntry = jarFile.getJarEntry(name);
  2307.             if (jarEntry != null) {
  2308.                 log.info("validateJarFile(" + jarfile +
  2309.                     ") - jar not loaded. See Servlet Spec 2.3, "
  2310.                     + "section 9.7.2. Offending class: " + name);
  2311.                 jarFile.close();
  2312.                 return (false);
  2313.             }
  2314.         }
  2315.         jarFile.close();
  2316.         return (true);
  2317.  
  2318.     }
  2319.  
  2320.  
  2321.     /**
  2322.      * Get URL.
  2323.      */
  2324.     protected URL getURL(File file, boolean encoded)
  2325.         throws MalformedURLException {
  2326.  
  2327.         File realFile = file;
  2328.         try {
  2329.             realFile = realFile.getCanonicalFile();
  2330.         } catch (IOException e) {
  2331.             // Ignore
  2332.         }
  2333.         if(encoded) {
  2334.             return getURI(realFile);
  2335.         } else {
  2336.             return realFile.toURL();
  2337.         }
  2338.  
  2339.     }
  2340.  
  2341.  
  2342.     /**
  2343.      * Get URL.
  2344.      */
  2345.     protected URL getURI(File file)
  2346.         throws MalformedURLException {
  2347.  
  2348.  
  2349.         File realFile = file;
  2350.         try {
  2351.             realFile = realFile.getCanonicalFile();
  2352.         } catch (IOException e) {
  2353.             // Ignore
  2354.         }
  2355.         return realFile.toURI().toURL();
  2356.  
  2357.     }
  2358.  
  2359.  
  2360.     /**
  2361.      * Delete the specified directory, including all of its contents and
  2362.      * subdirectories recursively.
  2363.      *
  2364.      * @param dir File object representing the directory to be deleted
  2365.      */
  2366.     protected static void deleteDir(File dir) {
  2367.  
  2368.         String files[] = dir.list();
  2369.         if (files == null) {
  2370.             files = new String[0];
  2371.         }
  2372.         for (int i = 0; i < files.length; i++) {
  2373.             File file = new File(dir, files[i]);
  2374.             if (file.isDirectory()) {
  2375.                 deleteDir(file);
  2376.             } else {
  2377.                 file.delete();
  2378.             }
  2379.         }
  2380.         dir.delete();
  2381.  
  2382.     }
  2383.  
  2384.  
  2385. }
  2386.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement