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 java.lang.reflect.Modifier;
017 import java.util.ArrayList;
018 import java.util.Iterator;
019 import java.util.List;
020
021 import javassist.CtClass;
022 import javassist.CtMethod;
023
024 import org.apache.hivemind.ApplicationRuntimeException;
025 import org.apache.hivemind.service.InterfaceFab;
026 import org.apache.hivemind.service.MethodSignature;
027
028 /**
029 * @author Howard M. Lewis Ship
030 */
031 public class InterfaceFabImpl extends AbstractFab implements InterfaceFab
032 {
033 private List _methods = new ArrayList();
034
035 public InterfaceFabImpl(CtClassSource source, CtClass ctClass)
036 {
037 super(source, ctClass);
038 }
039
040 public String toString()
041 {
042 StringBuffer buffer = new StringBuffer("InterfaceFabImpl[\npublic interface ");
043
044 CtClass ctClass = getCtClass();
045
046 buffer.append(ctClass.getName());
047
048 try
049 {
050 CtClass[] interfaces = ctClass.getInterfaces();
051
052 for (int i = 0; i < interfaces.length; i++)
053 {
054 buffer.append(i == 0 ? " extends " : ", ");
055 buffer.append(interfaces[i].getName());
056 }
057
058 }
059 catch (Exception ex)
060 {
061 buffer.append("<Exception: " + ex + ">");
062 }
063
064 Iterator i = _methods.iterator();
065
066 while (i.hasNext())
067 {
068 MethodSignature sig = (MethodSignature) i.next();
069
070 buffer.append("\n\npublic ");
071 buffer.append(sig);
072 buffer.append(";");
073 }
074
075 buffer.append("\n]");
076
077 return buffer.toString();
078 }
079
080 public void addMethod(MethodSignature ms)
081 {
082 CtClass ctReturnType = convertClass(ms.getReturnType());
083 CtClass[] ctParameters = convertClasses(ms.getParameterTypes());
084 CtClass[] ctExceptions = convertClasses(ms.getExceptionTypes());
085
086 CtMethod method = new CtMethod(ctReturnType, ms.getName(), ctParameters, getCtClass());
087
088 try
089 {
090 method.setModifiers(Modifier.PUBLIC | Modifier.ABSTRACT);
091 method.setExceptionTypes(ctExceptions);
092
093 getCtClass().addMethod(method);
094 }
095 catch (Exception ex)
096 {
097 throw new ApplicationRuntimeException(EnhanceMessages.unableToAddMethod(
098 ms,
099 getCtClass(),
100 ex), ex);
101 }
102
103 _methods.add(ms);
104 }
105
106 public Class createInterface()
107 {
108 return createClass();
109 }
110
111 }