KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > ejb > codegen > Generator


1 /*
2  * The contents of this file are subject to the terms
3  * of the Common Development and Distribution License
4  * (the License). You may not use this file except in
5  * compliance with the License.
6  *
7  * You can obtain a copy of the license at
8  * https://glassfish.dev.java.net/public/CDDLv1.0.html or
9  * glassfish/bootstrap/legal/CDDLv1.0.txt.
10  * See the License for the specific language governing
11  * permissions and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL
14  * Header Notice in each file and include the License file
15  * at glassfish/bootstrap/legal/CDDLv1.0.txt.
16  * If applicable, add the following below the CDDL Header,
17  * with the fields enclosed by brackets [] replaced by
18  * you own identifying information:
19  * "Portions Copyrighted [year] [name of copyright owner]"
20  *
21  * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
22  */

23
24 package com.sun.ejb.codegen;
25
26 import java.lang.reflect.*;
27 import java.util.*;
28 import java.util.logging.*;
29 import com.sun.logging.*;
30
31 import java.io.IOException JavaDoc;
32
33 import sun.rmi.rmic.IndentingWriter;
34
35 import com.sun.enterprise.deployment.*;
36
37
38 /**
39  * The base class for all code generators.
40  */

41
42 public abstract class Generator {
43
44     private static Logger _logger=null;
45     static{
46        _logger=LogDomains.getLogger(LogDomains.DPL_LOGGER);
47     }
48
49     protected String JavaDoc ejbClassSymbol;
50
51     public abstract String JavaDoc getGeneratedClass();
52
53     public abstract void generate(java.io.OutputStream JavaDoc out)
54         throws GeneratorException, java.io.IOException JavaDoc;
55
56
57     /**
58      * Get the package name from the class name.
59      * @param the class name.
60      * @return the package name.
61      */

62     protected String JavaDoc getPackageName(String JavaDoc className) {
63         int dot = className.lastIndexOf('.');
64         if (dot == -1)
65             return null;
66         return className.substring(0, dot);
67     }
68
69     protected String JavaDoc getBaseName(String JavaDoc className) {
70         int dot = className.lastIndexOf('.');
71         if (dot == -1)
72             return className;
73         return className.substring(dot+1);
74     }
75
76     protected String JavaDoc printType(Class JavaDoc cls) {
77         if (cls.isArray()) {
78             return printType(cls.getComponentType()) + "[]";
79         } else {
80             return cls.getName();
81         }
82     }
83
84     protected Method[] removeDups(Method[] orig)
85     {
86         // Remove duplicates from method array.
87
// Duplicates will arise if a class/intf and super-class/intf
88
// define methods with the same signature. Potentially the
89
// throws clauses of the methods may be different (note Java
90
// requires that the superclass/intf method have a superset of the
91
// exceptions in the derived method).
92
Vector nodups = new Vector();
93         for ( int i=0; i<orig.length; i++ ) {
94             Method m1 = orig[i];
95             boolean dup = false;
96             for ( Enumeration e=nodups.elements(); e.hasMoreElements(); ) {
97                 Method m2 = (Method)e.nextElement();
98
99                 // m1 and m2 are duplicates if they have the same signature
100
// (name and same parameters).
101
if ( !m1.getName().equals(m2.getName()) )
102                     continue;
103
104                 Class JavaDoc[] m1parms = m1.getParameterTypes();
105                 Class JavaDoc[] m2parms = m2.getParameterTypes();
106                 if ( m1parms.length != m2parms.length )
107                     continue;
108
109                 boolean parmsDup = true;
110                 for ( int j=0; j<m2parms.length; j++ ) {
111                     if ( m1parms[j] != m2parms[j] ) {
112                         parmsDup = false;
113                         break;
114                     }
115                 }
116                 if ( parmsDup ) {
117                     dup = true;
118                     // Select which of the duplicate methods to generate
119
// code for: choose the one that is lower in the
120
// inheritance hierarchy: this ensures that the generated
121
// method will compile.
122
if ( m2.getDeclaringClass().isAssignableFrom(
123                                                     m1.getDeclaringClass()) ) {
124                         // m2 is a superclass/intf of m1, so replace m2 with m1
125
nodups.remove(m2);
126                         nodups.add(m1);
127                     }
128                     break;
129                 }
130             }
131
132             if ( !dup )
133                 nodups.add(m1);
134         }
135         return (Method[])nodups.toArray(new Method[nodups.size()]);
136     }
137
138     /**
139      * Return true if method is on a javax.ejb.EJBObject/EJBLocalObject/
140      * javax.ejb.EJBHome,javax.ejb.EJBLocalHome interface.
141      */

142     protected boolean isEJBIntfMethod(Class JavaDoc ejbIntfClz, Method methodToCheck) {
143         boolean isEJBIntfMethod = false;
144
145         Method[] ejbIntfMethods = ejbIntfClz.getMethods();
146         for(int i = 0; i < ejbIntfMethods.length; i++) {
147             Method next = ejbIntfMethods[i];
148             if(methodCompare(methodToCheck, next)) {
149                 isEJBIntfMethod = true;
150
151                 String JavaDoc ejbIntfClzName = ejbIntfClz.getName();
152                 Class JavaDoc methodToCheckClz = methodToCheck.getDeclaringClass();
153                 if( !methodToCheckClz.getName().equals(ejbIntfClzName) ) {
154                     String JavaDoc[] logParams = { next.toString(),
155                                            methodToCheck.toString() };
156                     _logger.log(Level.WARNING,
157                                 "ejb.illegal_ejb_interface_override",
158                                 logParams);
159                 }
160
161                 break;
162             }
163         }
164
165     return isEJBIntfMethod;
166     }
167
168
169     private boolean methodCompare(Method factoryMethod, Method homeMethod) {
170
171     if(! factoryMethod.getName().equals(homeMethod.getName())) {
172         return false;
173         }
174
175     Class JavaDoc[] factoryParamTypes = factoryMethod.getParameterTypes();
176     Class JavaDoc[] beanParamTypes = homeMethod.getParameterTypes();
177     if (factoryParamTypes.length != beanParamTypes.length) {
178         return false;
179         }
180     for(int i = 0; i < factoryParamTypes.length; i++) {
181         if (factoryParamTypes[i] != beanParamTypes[i]) {
182         return false;
183             }
184         }
185
186     // NOTE : Exceptions and return types are not part of equality check
187

188     return true;
189
190     }
191
192     protected String JavaDoc[] printStaticMethodInit(IndentingWriter p, Class JavaDoc genClass,
193                                          Method[] methods)
194         throws IOException JavaDoc
195     {
196     if ( methods==null || methods.length == 0 )
197         return new String JavaDoc[0];
198     String JavaDoc[] methodVars = new String JavaDoc[methods.length];
199         // static variables for each biz method's Method object
200
for(int i = 0; i < methods.length; i++) {
201         String JavaDoc methodVar = getUniqueMethodVar(methodVars,
202                     "__Method__" + methods[i].getName(), 0);
203         methodVars[i] = methodVar;
204             p.pln("private static java.lang.reflect.Method " + methodVar + ";");
205         }
206
207         // static block to initialize Method objects
208
p.plnI("static {");
209         p.plnI("try {");
210         p.pln("java.lang.Class[] cl;");
211         for(int i = 0; i < methods.length; i++) {
212             Class JavaDoc[] params = methods[i].getParameterTypes();
213             // code to create array of parameter types' Classes
214
p.pln("cl = new java.lang.Class[" + params.length + "];");
215             for(int j = 0; j < params.length; j++) {
216                 p.pln("cl[" + j + "] = " + printType(params[j]) + ".class;");
217             }
218             // Foo.class.getMethod(...)
219
p.pln(methodVars[i] + " = "
220                     + genClass.getName() + ".class.getMethod(\""
221                     + methods[i].getName() + "\", cl);");
222         }
223         p.pOln("} catch(NoSuchMethodException e) {}");
224         p.pOln("}");
225
226     return methodVars;
227     }
228
229
230     // get a unique variable name for a Method object
231
// handle overloading of method names by adding a unique number suffix
232
private String JavaDoc getUniqueMethodVar(String JavaDoc[] existingNames, String JavaDoc newName,
233                       int count)
234     {
235     // XXX clean this by using iteration instead of recursion
236
boolean exists=false;
237     String JavaDoc name = newName;
238     if ( count > 0 )
239         name = newName + count;
240     for ( int i=0; i<existingNames.length; i++ ) {
241         String JavaDoc existingName = existingNames[i];
242         if ( existingName != null && existingName.equals(name) ) {
243         exists = true;
244         break;
245         }
246     }
247     if ( exists ) {
248         count++;
249         // "foo1" exists, so try "foo2"
250
return getUniqueMethodVar(existingNames, newName, count);
251     }
252     return name;
253     }
254
255     protected String JavaDoc getUniqueClassName(DeploymentContext context, String JavaDoc origName,
256                                         String JavaDoc origSuffix,
257                     Vector existingClassNames)
258     {
259     String JavaDoc newClassName = null;
260     boolean foundUniqueName = false;
261     int count = 0;
262     while ( !foundUniqueName ) {
263         String JavaDoc suffix = origSuffix;
264         if ( count > 0 ) {
265         suffix = origSuffix + count;
266             }
267         newClassName = origName + suffix;
268         if ( !existingClassNames.contains(newClassName) ) {
269         foundUniqueName = true;
270                 existingClassNames.add(newClassName);
271             }
272         else {
273         count++;
274             }
275     }
276     return newClassName;
277     }
278
279
280     protected String JavaDoc getTxAttribute(EjbDescriptor dd, Method method)
281     {
282     // The TX_* strings returned MUST match the TX_* constants in
283
// com.sun.ejb.Container.
284
if ( dd instanceof EjbSessionDescriptor
285          && ((EjbSessionDescriptor)dd).getTransactionType().equals("Bean") )
286         return "TX_BEAN_MANAGED";
287
288         String JavaDoc txAttr = null;
289     MethodDescriptor mdesc = new MethodDescriptor(method, ejbClassSymbol);
290         ContainerTransaction ct = dd.getContainerTransactionFor(mdesc);
291         if ( ct != null ) {
292             String JavaDoc attr = ct.getTransactionAttribute();
293             if ( attr.equals(ContainerTransaction.NOT_SUPPORTED) )
294                 txAttr = "TX_NOT_SUPPORTED";
295             else if ( attr.equals(ContainerTransaction.SUPPORTS) )
296                 txAttr = "TX_SUPPORTS";
297             else if ( attr.equals(ContainerTransaction.REQUIRED) )
298                 txAttr = "TX_REQUIRED";
299             else if ( attr.equals(ContainerTransaction.REQUIRES_NEW) )
300                 txAttr = "TX_REQUIRES_NEW";
301             else if ( attr.equals(ContainerTransaction.MANDATORY) )
302                 txAttr = "TX_MANDATORY";
303             else if ( attr.equals(ContainerTransaction.NEVER) )
304                 txAttr = "TX_NEVER";
305         }
306
307         if ( txAttr == null ) {
308             throw new RuntimeException JavaDoc("Transaction Attribute not found for method "+method);
309         }
310     return txAttr;
311     }
312
313     protected String JavaDoc getSecurityAttribute(EjbDescriptor dd, Method m)
314     {
315     // The SEC_* strings returned MUST match the SEC_* constants in
316
// com.sun.ejb.Container.
317

318     MethodDescriptor thisMethodDesc = new MethodDescriptor(m, ejbClassSymbol);
319
320     Set unchecked = dd.getUncheckedMethodDescriptors();
321     if ( unchecked != null ) {
322         Iterator i = unchecked.iterator();
323         while ( i.hasNext() ) {
324         MethodDescriptor md = (MethodDescriptor)i.next();
325         if ( thisMethodDesc.equals(md) )
326             return "SEC_UNCHECKED";
327         }
328     }
329
330     Set excluded = dd.getExcludedMethodDescriptors();
331     if ( excluded != null ) {
332         Iterator i = excluded.iterator();
333         while ( i.hasNext() ) {
334         MethodDescriptor md = (MethodDescriptor)i.next();
335         if ( thisMethodDesc.equals(md) )
336             return "SEC_EXCLUDED";
337         }
338     }
339
340     return "SEC_CHECKED";
341     }
342
343 }
344
Popular Tags