001 // Copyright 2004, 2005 The Apache Software Foundation 002 // 003 // Licensed under the Apache License, Version 2.0 (the "License"); 004 // you may not use this file except in compliance with the License. 005 // You may obtain a copy of the License at 006 // 007 // http://www.apache.org/licenses/LICENSE-2.0 008 // 009 // Unless required by applicable law or agreed to in writing, software 010 // distributed under the License is distributed on an "AS IS" BASIS, 011 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 012 // See the License for the specific language governing permissions and 013 // limitations under the License. 014 package org.apache.tapestry.enhance; 015 016 import javassist.CtClass; 017 import javassist.NotFoundException; 018 import org.apache.hivemind.ApplicationRuntimeException; 019 import org.apache.hivemind.service.ClassFabUtils; 020 021 /** 022 * Wrapper around Javassist's {@link javassist.ClassPool} and our own 023 * {@link org.apache.hivemind.service.impl.ClassFactoryClassLoader} that manages the creation of new 024 * instance of {@link javassist.CtClass} and converts finished CtClass's into instantiable Classes. 025 * 026 * @author Howard Lewis Ship 027 */ 028 public class CtClassSource 029 { 030 private HiveMindClassPool _pool; 031 032 public CtClassSource(HiveMindClassPool pool) 033 { 034 _pool = pool; 035 } 036 037 public CtClass getCtClass(Class searchClass) 038 { 039 ClassLoader loader = searchClass.getClassLoader(); 040 041 // Add the class loader for the searchClass to the class pool and 042 // delegating class loader if needed. 043 044 _pool.appendClassLoader(loader); 045 046 String name = ClassFabUtils.getJavaClassName(searchClass); 047 048 try 049 { 050 return _pool.get(name); 051 } 052 catch (NotFoundException ex) 053 { 054 throw new ApplicationRuntimeException(EnhanceMessages.unableToLookupClass(name, ex), ex); 055 } 056 } 057 058 public CtClass newClass(String name, Class superClass) 059 { 060 CtClass ctSuperClass = getCtClass(superClass); 061 062 return _pool.makeClass(name, ctSuperClass); 063 } 064 065 /** 066 * Creates a new, empty interace, with the given name. 067 * 068 * @since 1.1 069 */ 070 071 public CtClass newInterface(String name) 072 { 073 return _pool.makeInterface(name); 074 } 075 076 public Class createClass(CtClass ctClass) 077 { 078 return createClass(ctClass, false); 079 } 080 081 public Class createClass(CtClass ctClass, boolean detach) 082 { 083 try 084 { 085 return _pool.toClass(ctClass, detach); 086 } 087 catch (Throwable ex) 088 { 089 throw new ApplicationRuntimeException(EnhanceMessages.unableToWriteClass(ctClass, ex), ex); 090 } 091 } 092 093 public void setPool(HiveMindClassPool pool) 094 { 095 _pool = pool; 096 } 097 }