KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > derbyBuild > ClassSizeCrawler


1 /*
2
3    Derby - Class org.apache.derby.iapi.services.cache.ClassSizeCrawler
4
5    Licensed to the Apache Software Foundation (ASF) under one or more
6    contributor license agreements. See the NOTICE file distributed with
7    this work for additional information regarding copyright ownership.
8    The ASF licenses this file to You under the Apache License, Version 2.0
9    (the "License"); you may not use this file except in compliance with
10    the License. You may obtain a copy of the License at
11
12       http://www.apache.org/licenses/LICENSE-2.0
13
14    Unless required by applicable law or agreed to in writing, software
15    distributed under the License is distributed on an "AS IS" BASIS,
16    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17    See the License for the specific language governing permissions and
18    limitations under the License.
19
20  */

21
22 package org.apache.derbyBuild;
23
24 import org.apache.derby.iapi.services.cache.ClassSize;
25
26 import java.io.File JavaDoc;
27 import java.io.FileWriter JavaDoc;
28 import java.io.PrintWriter JavaDoc;
29 import java.io.IOException JavaDoc;
30 import java.io.FileOutputStream JavaDoc;
31 import java.io.ObjectOutput JavaDoc;
32 import java.io.ObjectOutputStream JavaDoc;
33 import java.lang.SecurityException JavaDoc;
34 import java.lang.ClassNotFoundException JavaDoc;
35 import java.util.Hashtable JavaDoc;
36 import java.util.Enumeration JavaDoc;
37 import java.util.Calendar JavaDoc;
38 import java.util.Date JavaDoc;
39
40 /**
41  * This class implements a program that catalogs the size estimate coefficients of various classes.
42  * @see ClassSize#getSizeCoefficients.
43  *<p>
44  * The program is invoked as:
45  *<p>
46  * java -DWS=<i>work-space</i> [-DclassDir=<i>class-dir</i>] [-Dout=<i>out-file</i> [-Dprefix[.<i>x</i>=<i>package-prefix</i>]] [-Dverbose=true] org.apache.derby.iapi.services.cache.ClassSizeCrawler <i>class-or-interface</i> ...<br>
47  *<p>
48  * This program gets the size coefficients for each class in the <i>class-or-interface</i> list,
49  * and for each class that implements an interface in the list. If there is an interface in the list
50  * this program crawls through the classes hierarcy, starting at points specified by the prefix
51  * properties, looking for classes that implement the interfaces.
52  *<p>
53  * If the <i>class-or-interface</i> list is empty then this program searches for implementations
54  * of org.apache.derby.iapi.types.DataValueDescriptor, and at least one prefix property
55  * must be specified
56  *<p>
57  * The catalog is written as a java source file
58  * into <i>out-file</i>, by default
59  * <i>work-space</i>/java/org.apache.derby.iapi.services.cache.ClassSizeCatalog.java.
60  *<p>
61  * <i>work-space</i> is the directory containing the java and classes directories. $WS in the
62  * standard development environment. This property is required.
63  *<p>
64  * <i>class-dir</i> is the directory containing the compiled classes. By default it is <i>work-space</i>/classes.
65  *<p>
66  * <i>package-prefix</i> is the first part of a package name. e.g. "com.ibm.db2j.impl". At least
67  * one prefix property must be specified if there is an interface in the list.
68  *<p>
69  * For example:<br>
70  * <pre>
71  * <code>
72  * java -DWS=$WS \
73  * -Dprefix.1=org.apache.derby.iapi.types \
74  * org.apache.derby.iapi.services.cache.ClassSizeCrawler \
75  * org.apache.derby.iapi.types.DataValueDescriptor \
76  * java.math.BigDecimal \
77  * org.apache.derby.impl.services.cache.Generic.CachedItem
78  *</code>
79  *</pre>
80  */

81 public class ClassSizeCrawler
82 {
83     public static void main( String JavaDoc[] arg)
84     {
85         String JavaDoc[] classAndInterfaceList = {"org.apache.derby.iapi.types.DataValueDescriptor"};
86         if(arg.length > 0)
87             classAndInterfaceList = arg;
88         Class JavaDoc[] interfaceList = new Class JavaDoc[classAndInterfaceList.length];
89         int interfaceCount = 0;
90         Class JavaDoc[] classList = new Class JavaDoc[classAndInterfaceList.length];
91         int classCount = 0;
92
93         Class JavaDoc classSizeClass = ClassSize.class; // Make sure that the garbage collector does not unload it
94
ClassSize.setDummyCatalog();
95         /* Most of the classes we will catalog invoke ClassSize.estimateBaseFromCatalog in
96          * their static initializer. This dummy the catalog out so that this will not generate
97          * errors. We will not actually use the classes, just examine their fields.
98          */

99
100         for( int i = 0; i < classAndInterfaceList.length; i++)
101         {
102             Class JavaDoc cls = null;
103             try
104             {
105                 cls = Class.forName( classAndInterfaceList[i]);
106             }
107             catch( ClassNotFoundException JavaDoc cnfe)
108             {
109                 System.err.println( "*** Could not find class " + classAndInterfaceList[i]);
110                 System.exit(1);
111             }
112             if( cls.isInterface())
113                 interfaceList[ interfaceCount++] = cls;
114             else
115                 classList[ classCount++] = cls;
116         }
117
118         String JavaDoc WS = System.getProperty( "WS");
119         if( WS == null)
120         {
121             System.err.println( "*** WS is not set.");
122             System.exit(1);
123         }
124
125         StringBuffer JavaDoc baseDir = new StringBuffer JavaDoc( System.getProperty( "classDir", ""));
126         if( baseDir.length() == 0)
127         {
128             baseDir.append( WS);
129             baseDir.append( '/');
130             baseDir.append( "classes");
131         }
132         int baseDirLength = baseDir.length();
133
134         StringBuffer JavaDoc packagePrefix = new StringBuffer JavaDoc( );
135
136         Hashtable JavaDoc classSizes = new Hashtable JavaDoc();
137
138         ClassSizeCrawler crawler = new ClassSizeCrawler(interfaceList, interfaceCount, classSizes);
139
140         if( interfaceCount > 0)
141         {
142             boolean gotPrefix = false;
143             // Crawl through the class hierarchies for classes implementing the interfaces
144
for( Enumeration JavaDoc e = System.getProperties().propertyNames();
145                  e.hasMoreElements();)
146             {
147                 String JavaDoc propertyName = (String JavaDoc) e.nextElement();
148                 if( propertyName.equals( "prefix") || propertyName.startsWith( "prefix."))
149                 {
150                     gotPrefix = true;
151                     packagePrefix.setLength( 0);
152                     packagePrefix.append( System.getProperty( propertyName));
153                     baseDir.setLength( baseDirLength);
154                     if( packagePrefix.length() > 0)
155                     {
156                         baseDir.append( '/');
157                         for( int offset = 0; offset < packagePrefix.length(); offset++)
158                         {
159                             char c = packagePrefix.charAt( offset);
160                             if( c == '.')
161                                 baseDir.append( '/');
162                             else
163                                 baseDir.append( c);
164                         }
165                     }
166                     crawler.crawl( new File JavaDoc( baseDir.toString()), packagePrefix);
167                 }
168             }
169             if( ! gotPrefix)
170             {
171                 System.err.println( "*** Could not search the class hierarchy because no starting");
172                 System.err.println( " prefixes where specified.");
173                 System.exit(1);
174             }
175         }
176         for( int i = 0; i < classCount; i++)
177             crawler.addClass( classList[i]);
178
179         baseDir.setLength( baseDirLength);
180         String JavaDoc outputFileName =
181           System.getProperty( "out", WS + "/java/org.apache.derby.iapi.services.cache.ClassSizeCatalog.java");
182         try
183         {
184             Calendar JavaDoc cal = Calendar.getInstance();
185             cal.setTime( new Date JavaDoc());
186             int year = cal.get( Calendar.YEAR);
187             PrintWriter JavaDoc out = new PrintWriter JavaDoc( new FileWriter JavaDoc( outputFileName));
188             out.print( "/*\n\n" +
189
190                        " Licensed to the Apache Software Foundation (ASF) under one or more\n" +
191                        " contributor license agreements. See the NOTICE file distributed with\n" +
192                        " this work for additional information regarding copyright ownership.\n" +
193                        " The ASF licenses this file to You under the Apache License, Version 2.0\n" +
194                        " (the \"License\"); you may not use this file except in compliance with\n" +
195                        " the License. You may obtain a copy of the License at\n" +
196                        "\n" +
197                        " http://www.apache.org/licenses/LICENSE-2.0\n" +
198                        "\n" +
199                        " Unless required by applicable law or agreed to in writing, software\n" +
200                        " distributed under the License is distributed on an \"AS IS\" BASIS,\n" +
201                        " WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" +
202                        " See the License for the specific language governing permissions and\n" +
203                        " limitations under the License.\n" +
204                        " */\n");
205             out.print( "package org.apache.derby.iapi.services.cache;\n" +
206                        "import java.util.Hashtable;\n" +
207                        "class ClassSizeCatalog extends java.util.Hashtable\n" +
208                        "{\n" +
209                        " ClassSizeCatalog()\n" +
210                        " {\n");
211             for( Enumeration JavaDoc e = classSizes.keys();
212                  e.hasMoreElements();)
213             {
214                 String JavaDoc className = (String JavaDoc) e.nextElement();
215                 int[] coeff = (int[]) classSizes.get( className);
216                 out.print( " put( \"" + className + "\", new int[]{" + coeff[0] + "," + coeff[1] + "});\n");
217             }
218             out.print(" }\n" +
219                       "}\n");
220             out.flush();
221             out.close();
222         }
223         catch( IOException JavaDoc ioe)
224         {
225             System.err.println( "*** Cannot write to " + outputFileName);
226             System.err.println( " " + ioe.getMessage());
227             System.exit(1);
228         }
229     } // end of main
230

231     private Class JavaDoc[] interfaceList; // Search for classes that implement these interfaces
232
private int interfaceCount;
233     private Hashtable JavaDoc classSizes;
234     private boolean verbose = false;
235
236     private ClassSizeCrawler( Class JavaDoc[] interfaceList,
237                               int interfaceCount,
238                               Hashtable JavaDoc classSizes)
239     {
240         this.interfaceList = interfaceList;
241         this.classSizes = classSizes;
242         this.interfaceCount = interfaceCount;
243         verbose = new Boolean JavaDoc( System.getProperty( "verbose", "false")).booleanValue();
244     }
245
246     private void crawl( File JavaDoc curDir, StringBuffer JavaDoc className)
247     {
248         if( verbose)
249             System.out.println( "Searching directory " + curDir.getPath());
250
251         try
252         {
253             if( ! curDir.isDirectory())
254             {
255                 System.err.println( "*** " + curDir.getPath() + " is not a directory.");
256                 System.exit(1);
257             }
258         }
259         catch( SecurityException JavaDoc se)
260         {
261             System.err.println( "Cannot access " + curDir.getPath());
262             System.exit(1);
263         }
264         String JavaDoc[] filenames = curDir.list( );
265         if( className.length() != 0)
266             className.append( ".");
267
268         int classNameLength = className.length();
269         for( int fileIdx = 0; fileIdx < filenames.length; fileIdx++)
270         {
271             if( filenames[fileIdx].endsWith( ".class"))
272             {
273                 // Strip off the ".class" suffix
274
String JavaDoc s = filenames[fileIdx].substring( 0, filenames[fileIdx].length() - 6);
275                 className.append( s);
276                 Class JavaDoc targetClass = null;
277                 String JavaDoc targetClassName = className.toString();
278                 try
279                 {
280                     targetClass = Class.forName( targetClassName);
281                     if( !targetClass.isInterface())
282                     {
283                         for( int interfaceIdx = 0; interfaceIdx < interfaceCount; interfaceIdx++)
284                         {
285                             if( interfaceList[interfaceIdx].isAssignableFrom( targetClass))
286                                 addClass( targetClass);
287                         }
288                     }
289                 }
290                 catch( ClassNotFoundException JavaDoc cnfe)
291                 {
292                     System.err.println( "Could not find class " + targetClassName);
293                     System.exit(1);
294                 }
295                 catch( Throwable JavaDoc t){}
296                 className.setLength( classNameLength);
297             }
298             else
299             {
300                 File JavaDoc nextDir = new File JavaDoc( curDir, filenames[fileIdx]);
301                 if( nextDir.isDirectory())
302                 {
303                     className.append( filenames[fileIdx]);
304                     crawl( nextDir, className);
305                     className.setLength( classNameLength);
306                 }
307             }
308         }
309     } // end of crawl
310

311     private void addClass( Class JavaDoc targetClass)
312     {
313         int[] coefficients = ClassSize.getSizeCoefficients( targetClass);
314         if( verbose)
315             System.out.println( targetClass.getName() + " " + coefficients[0] + ", " + coefficients[1]);
316         classSizes.put( targetClass.getName(), coefficients);
317     } // end of addClass
318
} // end of ClassSizeCrawler
319
Popular Tags