KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > aop > instrument > TransformerCommon


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.aop.instrument;
23
24 import java.io.File JavaDoc;
25 import java.io.FileOutputStream JavaDoc;
26 import java.lang.ref.WeakReference JavaDoc;
27 import java.net.URI JavaDoc;
28 import java.net.URL JavaDoc;
29 import java.net.URLClassLoader JavaDoc;
30 import java.security.AccessController JavaDoc;
31 import java.security.PrivilegedActionException JavaDoc;
32 import java.security.PrivilegedExceptionAction JavaDoc;
33
34 import org.jboss.aop.AspectManager;
35 import org.jboss.aop.classpool.AOPClassPool;
36 import org.jboss.aop.standalone.Compiler;
37
38 import javassist.CannotCompileException;
39 import javassist.ClassPool;
40 import javassist.CtClass;
41 import javassist.CtField;
42 import javassist.NotFoundException;
43
44 /**
45  * A few handy methods and common things used by the other Transformers
46  * @author <a HREF="mailto:kabirkhan@bigfoot.com">Kabir Khan</a>
47  * @version $Revision: 56777 $
48  *
49  */

50 public class TransformerCommon {
51
52    final static URL JavaDoc[] NO_URLS = new URL JavaDoc[0];
53    final static CtClass[] EMPTY_CTCLASS_ARRAY = new CtClass[0];
54    final static String JavaDoc WEAK_REFERENCE = WeakReference JavaDoc.class.getName();
55
56    public static boolean isCompileTime()
57    {
58       return Compiler.loader != null;
59    }
60
61    public static void compileOrLoadClass(CtClass classForPackage, CtClass newClass)
62    {
63       compileOrLoadClass(classForPackage, newClass, isCompileTime());
64    }
65
66    /** Compiles the class to file or adds it to the class pool
67     *
68     * @param classForPackage The class to be used to determine the directory to place the class in
69     * @param invocation The class to be comiled/added to class pool
70     * @throws Exception
71     */

72    public static void compileOrLoadClass(CtClass classForPackage, CtClass newClass, boolean compile)
73    {
74       try
75       {
76          registerGeneratedClass(newClass);
77          // If compile time
78
if (compile)
79          {
80             File JavaDoc file;
81             URLClassLoader JavaDoc loader = Compiler.loader;
82             if (loader == null)
83             {
84                loader = new URLClassLoader JavaDoc(NO_URLS, Thread.currentThread().getContextClassLoader());
85             }
86             URL JavaDoc url = loader.getResource(
87                   classForPackage.getName().replace('.', '/') + ".class");
88             String JavaDoc path = url.toString();
89             path = path.substring(0, path.lastIndexOf('/') + 1);
90             path = path + newClass.getSimpleName() + ".class";
91             URI JavaDoc newUrl = new URI JavaDoc(path);
92             file = new File JavaDoc(newUrl);
93             FileOutputStream JavaDoc fp = new FileOutputStream JavaDoc(file);
94             fp.write(newClass.toBytecode());
95             fp.close();
96          }
97          else
98          {
99             // if load time
100
if (System.getSecurityManager() == null)
101             {
102                ToClassAction.NON_PRIVILEGED.toClass(newClass, null);
103             }
104             else
105             {
106                ToClassAction.PRIVILEGED.toClass(newClass, null);
107             }
108          }
109
110          if (AspectManager.debugClasses)
111          {
112             newClass.debugWriteFile();
113          }
114       }
115       catch (Exception JavaDoc e)
116       {
117          throw new RuntimeException JavaDoc(e);
118       }
119    }
120
121    public static Class JavaDoc toClass(CtClass newClass) throws CannotCompileException
122    {
123       registerGeneratedClass(newClass);
124
125       if (System.getSecurityManager() == null)
126       {
127          return ToClassAction.NON_PRIVILEGED.toClass(newClass, null);
128       }
129       else
130       {
131          return ToClassAction.PRIVILEGED.toClass(newClass, null);
132       }
133    }
134
135    public static Class JavaDoc toClass(CtClass newClass, ClassLoader JavaDoc loader) throws CannotCompileException
136    {
137       registerGeneratedClass(newClass);
138
139       if (System.getSecurityManager() == null)
140       {
141          return ToClassAction.NON_PRIVILEGED.toClass(newClass, loader);
142       }
143       else
144       {
145          return ToClassAction.PRIVILEGED.toClass(newClass, loader);
146       }
147    }
148
149    protected static void addInfoField(Instrumentor instrumentor, String JavaDoc infoClassName, String JavaDoc infoName,
150          int modifiers, CtClass addTo, boolean weak, CtField.Initializer init) throws NotFoundException, CannotCompileException
151    {
152       if (weak)
153       {
154          addWeakReferenceInfoField(instrumentor, infoClassName, infoName, modifiers, addTo, init);
155       }
156       else
157       {
158          addStrongReferenceInfoField(instrumentor, infoClassName, infoName, modifiers, addTo, init);
159       }
160    }
161
162    private static void registerGeneratedClass(CtClass newClass)
163    {
164       //TODO Maybe we should force a ScopedClassPool created by JBoss Retro to be an AOP classpool once AOP kicks in?
165
ClassPool pool = newClass.getClassPool();
166       if (pool instanceof AOPClassPool)
167       {
168          ((AOPClassPool)pool).registerGeneratedClass(newClass.getName());
169       }
170    }
171
172    private static void addWeakReferenceInfoField(Instrumentor instrumentor, String JavaDoc infoClassName, String JavaDoc infoName,
173          int modifiers, CtClass addTo, CtField.Initializer init) throws NotFoundException, CannotCompileException
174    {
175       CtClass type = instrumentor.forName(WEAK_REFERENCE);
176       CtField field = new CtField(type, infoName, addTo);
177       field.setModifiers(modifiers);
178       addTo.addField(field, init);
179    }
180
181    private static void addStrongReferenceInfoField(Instrumentor instrumentor, String JavaDoc infoClassName, String JavaDoc infoName,
182          int modifiers, CtClass addTo, CtField.Initializer init) throws NotFoundException, CannotCompileException
183    {
184       CtClass type = instrumentor.forName(infoClassName);
185       CtField field = new CtField(type, infoName, addTo);
186       field.setModifiers(modifiers);
187       addTo.addField(field, init);
188    }
189
190    protected static String JavaDoc infoFromWeakReference(String JavaDoc infoClassName, String JavaDoc localName, String JavaDoc infoName)
191    {
192          return infoClassName + " " + localName + " = (" + infoClassName + ")" + infoName + ".get();";
193    }
194
195    /**
196     * Utility method to make a new class in a pool. It makes sure that the class is registered with the pool, so others can find it.
197     */

198    public static CtClass makeNestedClass(CtClass outer, String JavaDoc name, boolean isStatic, int modifiers, CtClass superClass) throws CannotCompileException
199    {
200       CtClass inner = makeNestedClass(outer, name, true);
201       inner.setModifiers(modifiers);
202       inner.setSuperclass(superClass);
203       return inner;
204    }
205
206    /**
207     * Utility method to make a new class in a pool. It makes sure that the class is registered with the pool, so others can find it.
208     */

209    public static CtClass makeNestedClass(CtClass outer, String JavaDoc name, boolean isStatic) throws CannotCompileException
210    {
211       registerGeneratedClass(outer.getClassPool(), outer.getName() + "$" + name);
212       CtClass inner = outer.makeNestedClass(name, true);
213       return inner;
214    }
215
216    /**
217     * Utility method to make a new class in a pool. It makes sure that the class is registered with the pool, so others can find it.
218     */

219    public static CtClass makeClass(ClassPool pool, String JavaDoc name)
220    {
221       registerGeneratedClass(pool, name);
222       return pool.makeClass(name);
223    }
224
225    /**
226     * Utility method to make a new class in a pool. It makes sure that the class is registered with the pool, so others can find it.
227     */

228    public static CtClass makeClass(ClassPool pool, String JavaDoc name, CtClass superClass)
229    {
230       registerGeneratedClass(pool, name);
231       return pool.makeClass(name, superClass);
232    }
233
234    private static void registerGeneratedClass(ClassPool pool, String JavaDoc name)
235    {
236       try
237       {
238          ((AOPClassPool)pool).registerGeneratedClass(name);
239       }
240       catch(ClassCastException JavaDoc e)
241       {
242
243       }
244    }
245
246    private interface ToClassAction
247    {
248       Class JavaDoc toClass(CtClass clazz, ClassLoader JavaDoc loader) throws CannotCompileException;
249
250       ToClassAction PRIVILEGED = new ToClassAction()
251       {
252          public Class JavaDoc toClass(final CtClass clazz, final ClassLoader JavaDoc loader) throws CannotCompileException
253          {
254             try
255             {
256                return (Class JavaDoc)AccessController.doPrivileged(new PrivilegedExceptionAction JavaDoc()
257                {
258                   public Object JavaDoc run() throws Exception JavaDoc
259                   {
260                      if (AspectManager.debugClasses)
261                      {
262                         clazz.debugWriteFile();
263                      }
264                      if (loader != null)
265                      {
266                         return clazz.toClass(loader, null);
267                      }
268                      return clazz.toClass();
269                   }
270                });
271             }
272             catch (PrivilegedActionException JavaDoc e)
273             {
274                Exception JavaDoc actual = e.getException();
275                if (actual instanceof CannotCompileException)
276                {
277                   throw (CannotCompileException)actual;
278                }
279                throw new RuntimeException JavaDoc(actual);
280             }
281          }
282       };
283
284       ToClassAction NON_PRIVILEGED = new ToClassAction()
285       {
286          public Class JavaDoc toClass(CtClass clazz, ClassLoader JavaDoc loader) throws CannotCompileException
287          {
288             if (AspectManager.debugClasses)
289             {
290                clazz.debugWriteFile();
291             }
292             if (loader != null)
293             {
294                return clazz.toClass(loader, null);
295             }
296             return clazz.toClass();
297          }
298       };
299    }
300 }
301
Popular Tags