KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > mx > loading > ClassPreloadService


1 /*
2 * JBoss, Home of Professional Open Source
3 * Copyright 2005, JBoss Inc., and individual contributors as indicated
4 * by the @authors tag. See the copyright.txt in the distribution for a
5 * full listing of individual contributors.
6 *
7 * This is free software; you can redistribute it and/or modify it
8 * under the terms of the GNU Lesser General Public License as
9 * published by the Free Software Foundation; either version 2.1 of
10 * the License, or (at your option) any later version.
11 *
12 * This software is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this software; if not, write to the Free
19 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
20 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
21 */

22 package org.jboss.mx.loading;
23
24 import java.net.URL JavaDoc;
25 import java.io.InputStream JavaDoc;
26 import java.io.IOException JavaDoc;
27 import java.util.zip.ZipInputStream JavaDoc;
28 import java.util.zip.ZipEntry JavaDoc;
29 import java.util.regex.Pattern JavaDoc;
30 import java.util.regex.Matcher JavaDoc;
31 import java.util.ArrayList JavaDoc;
32 import java.util.Arrays JavaDoc;
33
34 import org.jboss.logging.Logger;
35
36 /**
37  A simple service that can be used preload all classes in the classpath
38  of the thread context class loader seen in the start method as the thread
39  context class loader. A simple xmbean fragment for deploying the service
40  is:
41
42     <mbean code="org.jboss.mx.loading.ClassPreloadService"
43       name="jboss.mx:service=ClassPreloadService"
44       xmbean-dd="">
45       <xmbean>
46           <attribute access="read-write"
47              getMethod="getIncludePatterns" setMethod="setIncludePatterns">
48              <description>The patterns for classpath includes</description>
49              <name>IncludePatterns</name>
50              <type>[Ljava.lang.String;</type>
51           </attribute>
52           <attribute access="read-write"
53              getMethod="getExcludePatterns" setMethod="setExcludePatterns">
54              <description>The patterns for classpath excludes</description>
55              <name>ExcludePatterns</name>
56              <type>[Ljava.lang.String;</type>
57           </attribute>
58           <attribute access="read-write"
59              getMethod="isSimpleMatch" setMethod="setSimpleMatch">
60              <description>A flag indicate if String.endsWith matching of includes/excludes should be used</description>
61              <name>SimpleMatch</name>
62              <type>[Ljava.lang.String;</type>
63           </attribute>
64          <operation>
65             <name>start</name>
66          </operation>
67          <attribute>
68       </xmbean>
69        <attribute name="ExcludePatterns">jbossmq.jar</attribute>
70        <attribute name="IncludePatterns"></attribute>
71        <attribute name="SimpleMatch">true</attribute>
72    </mbean>
73
74  @author Scott.Stark@jboss.org
75  @version $Revision: 38456 $
76  */

77 public class ClassPreloadService
78 {
79    static Logger log = Logger.getLogger(ClassPreloadService.class);
80    /** The RE expressions for classpath elements to include */
81    private String JavaDoc[] includePattern = {};
82    /** The RE expressions for classpath elements to exclude */
83    private String JavaDoc[] excludePattern = {};
84    /** A flag indicate if String.endsWith matching of includes/excludes should be used */
85    private boolean simpleMatch;
86    boolean trace;
87
88    public String JavaDoc[] getIncludePatterns()
89    {
90       return includePattern;
91    }
92    public void setIncludePatterns(String JavaDoc[] includePattern)
93    {
94       this.includePattern = includePattern;
95    }
96
97    public String JavaDoc[] getExcludePatterns()
98    {
99       return excludePattern;
100    }
101    public void setExcludePatterns(String JavaDoc[] excludePattern)
102    {
103       this.excludePattern = excludePattern;
104    }
105
106    public boolean isSimpleMatch()
107    {
108       return simpleMatch;
109    }
110    public void setSimpleMatch(boolean simpleMatch)
111    {
112       this.simpleMatch = simpleMatch;
113    }
114
115    public URL JavaDoc[] getRawClassPath()
116    {
117       ClassLoader JavaDoc loader = Thread.currentThread().getContextClassLoader();
118       URL JavaDoc[] fullCP = ClassLoaderUtils.getClassLoaderURLs(loader);
119       return fullCP;
120    }
121
122    /**
123     Load all classes seen the TCL classpath. This entails a scan of every
124     archive in the TCL classpath URLs for .class entries.
125     */

126    public void start()
127    {
128       trace = log.isTraceEnabled();
129       log.debug("Starting, includes="+ Arrays.asList(includePattern)
130          +", excludes="+excludePattern);
131       // Compile the include/exclude patterns
132
Pattern JavaDoc[] includes = compileIncludes();
133       Pattern JavaDoc[] excludes = compileExcludes();
134
135       ClassLoader JavaDoc loader = Thread.currentThread().getContextClassLoader();
136       URL JavaDoc[] rawCP = ClassLoaderUtils.getClassLoaderURLs(loader);
137       URL JavaDoc[] cp = filterCP(rawCP, includes, excludes);
138
139       int loadedClasses = 0;
140       int loadErrors = 0;
141       for(int n = 0; n < cp.length; n ++)
142       {
143          URL JavaDoc u = cp[n];
144          try
145          {
146             InputStream JavaDoc is = u.openStream();
147             ZipInputStream JavaDoc zis = new ZipInputStream JavaDoc(is);
148             ZipEntry JavaDoc ze = zis.getNextEntry();
149             while (ze != null)
150             {
151                String JavaDoc name = ze.getName();
152                if (name.endsWith(".class"))
153                {
154                   int length = name.length();
155                   String JavaDoc cname = name.replace('/', '.').substring(0, length - 6);
156                   try
157                   {
158                      Class JavaDoc c = loader.loadClass(cname);
159                      loadedClasses ++;
160                      if (trace)
161                         log.trace("loaded class: " + cname);
162                   }
163                   catch (Throwable JavaDoc e)
164                   {
165                      loadErrors ++;
166                      if( trace )
167                         log.trace("Failed to load class, "+e.getMessage());
168                   }
169                }
170                ze = zis.getNextEntry();
171             }
172             zis.close();
173          }
174          catch (IOException JavaDoc ignore)
175          {
176             // Not a jar
177
}
178       }
179       log.info("Loaded "+loadedClasses+" classes, "+loadErrors+" CNFEs");
180    }
181
182    public Pattern JavaDoc[] compileIncludes()
183    {
184       ArrayList JavaDoc tmp = new ArrayList JavaDoc();
185       int count = this.includePattern != null ? includePattern.length : 0;
186       for(int n = 0; n < count; n ++)
187       {
188          String JavaDoc p = includePattern[n];
189          Pattern JavaDoc pat = Pattern.compile(p);
190          tmp.add(pat);
191       }
192       Pattern JavaDoc[] includes = new Pattern JavaDoc[tmp.size()];
193       tmp.toArray(includes);
194       return includes;
195    }
196    public Pattern JavaDoc[] compileExcludes()
197    {
198       ArrayList JavaDoc tmp = new ArrayList JavaDoc();
199       int count = this.excludePattern != null ? excludePattern.length : 0;
200       for(int n = 0; n < count; n ++)
201       {
202          String JavaDoc p = excludePattern[n];
203          Pattern JavaDoc pat = Pattern.compile(p);
204          tmp.add(pat);
205       }
206       Pattern JavaDoc[] includes = new Pattern JavaDoc[tmp.size()];
207       tmp.toArray(includes);
208       return includes;
209    }
210
211    public URL JavaDoc[] filterCP(URL JavaDoc[] rawCP, Pattern JavaDoc[] includes, Pattern JavaDoc[] excludes)
212    {
213       if( trace )
214          log.trace("filterCP, rawCP="+Arrays.asList(rawCP));
215       ArrayList JavaDoc tmp = new ArrayList JavaDoc();
216       int count = rawCP != null ? rawCP.length : 0;
217       for(int m = 0; m < count; m ++)
218       {
219          URL JavaDoc pathURL = rawCP[m];
220          String JavaDoc path = pathURL.toString();
221          boolean excluded = false;
222
223          // Excludes take priority over includes
224
for(int n = 0; n < excludes.length; n ++)
225          {
226             Pattern JavaDoc p = excludes[n];
227             Matcher JavaDoc matcher = p.matcher(path);
228             if( simpleMatch && path.endsWith(p.pattern()) )
229             {
230                excluded = true;
231                break;
232             }
233             else if( matcher.matches() )
234             {
235                excluded = true;
236                break;
237             }
238          }
239          if( excluded )
240          {
241             log.debug("Excluded: "+pathURL);
242             continue;
243          }
244
245          // If there are no explicit includes, accept the non-excluded paths
246
boolean included = includes.length == 0;
247          for(int n = 0; n < includes.length; n ++)
248          {
249             Pattern JavaDoc p = includes[n];
250             Matcher JavaDoc matcher = p.matcher(path);
251             if( simpleMatch && path.endsWith(p.pattern()) )
252                tmp.add(pathURL);
253             else if( matcher.matches() )
254                tmp.add(pathURL);
255          }
256          if( included )
257          {
258             log.debug("Included: "+pathURL);
259             tmp.add(pathURL);
260          }
261       }
262       URL JavaDoc[] cp = new URL JavaDoc[tmp.size()];
263       tmp.toArray(cp);
264       return cp;
265    }
266 }
267
Popular Tags