KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > oracle > toplink > essentials > internal > ejb > cmp3 > metadata > MetadataHelper


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
5  * in compliance with the License.
6  *
7  * You can obtain a copy of the license at
8  * glassfish/bootstrap/legal/CDDLv1.0.txt or
9  * https://glassfish.dev.java.net/public/CDDLv1.0.html.
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 in each file and include the License file at
15  * glassfish/bootstrap/legal/CDDLv1.0.txt. If applicable,
16  * add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your
18  * own identifying information: Portions Copyright [yyyy]
19  * [name of copyright owner]
20  */

21 package oracle.toplink.essentials.internal.ejb.cmp3.metadata;
22
23 import java.lang.annotation.Annotation JavaDoc;
24
25 import java.lang.reflect.AnnotatedElement JavaDoc;
26 import java.lang.reflect.Field JavaDoc;
27 import java.lang.reflect.Method JavaDoc;
28 import java.lang.reflect.ParameterizedType JavaDoc;
29 import java.lang.reflect.Type JavaDoc;
30
31 import java.security.AccessController JavaDoc;
32 import java.security.PrivilegedActionException JavaDoc;
33
34 import java.util.ArrayList JavaDoc;
35 import java.util.Collection JavaDoc;
36 import java.util.HashMap JavaDoc;
37 import java.util.HashSet JavaDoc;
38 import java.util.Hashtable JavaDoc;
39 import java.util.List JavaDoc;
40 import java.util.Map JavaDoc;
41 import java.util.Set JavaDoc;
42 import java.util.Vector JavaDoc;
43
44 import javax.persistence.Embeddable;
45 import javax.persistence.Embedded;
46 import javax.persistence.EmbeddedId;
47 import javax.persistence.ManyToMany;
48 import javax.persistence.ManyToOne;
49 import javax.persistence.OneToMany;
50 import javax.persistence.OneToOne;
51
52 import oracle.toplink.essentials.descriptors.ClassDescriptor;
53
54 import oracle.toplink.essentials.exceptions.ValidationException;
55
56 import oracle.toplink.essentials.internal.ejb.cmp3.metadata.accessors.MetadataAccessor;
57 import oracle.toplink.essentials.internal.ejb.cmp3.metadata.accessors.objects.MetadataAccessibleObject;
58 import oracle.toplink.essentials.internal.ejb.cmp3.metadata.listeners.MetadataEntityListener;
59
60 import oracle.toplink.essentials.internal.helper.Helper;
61
62 import oracle.toplink.essentials.internal.security.PrivilegedAccessHelper;
63 import oracle.toplink.essentials.internal.security.PrivilegedClassForName;
64 import oracle.toplink.essentials.internal.security.PrivilegedGetDeclaredFields;
65 import oracle.toplink.essentials.internal.security.PrivilegedGetDeclaredMethods;
66 import oracle.toplink.essentials.internal.security.PrivilegedGetField;
67 import oracle.toplink.essentials.internal.security.PrivilegedGetMethod;
68 import oracle.toplink.essentials.internal.security.PrivilegedGetMethods;
69
70 import oracle.toplink.essentials.sessions.Project;
71
72 /**
73  * Common helper methods for the metadata processing.
74  *
75  * @author Guy Pelletier
76  * @since TopLink EJB 3.0 Reference Implementation
77  */

78 public class MetadataHelper {
79     public static final String JavaDoc IS_PROPERTY_METHOD_PREFIX = "is";
80     public static final String JavaDoc GET_PROPERTY_METHOD_PREFIX = "get";
81     public static final String JavaDoc SET_PROPERTY_METHOD_PREFIX = "set";
82     public static final String JavaDoc SET_IS_PROPERTY_METHOD_PREFIX = "setIs";
83     private static final int POSITION_AFTER_IS_PREFIX = IS_PROPERTY_METHOD_PREFIX.length();
84     private static final int POSITION_AFTER_GET_PREFIX = GET_PROPERTY_METHOD_PREFIX.length();
85     
86     public static final String JavaDoc PERSISTENCE_PACKAGE_PREFIX = "javax.persistence";
87
88     /**
89      * INTERNAL:
90      * Search the given sessions list of ordered descriptors for a descriptor
91      * for the class named the same as the given class.
92      *
93      * We do not use the session based getDescriptor() methods because they
94      * require the project be initialized with classes. We are avoiding using
95      * a project with loaded classes so the project can be constructed prior to
96      * any class weaving.
97      */

98     public static ClassDescriptor findDescriptor(Project project, Class JavaDoc cls) {
99         for (ClassDescriptor descriptor : (Vector JavaDoc<ClassDescriptor>) project.getOrderedDescriptors()) {
100             if (descriptor.getJavaClassName().equals(cls.getName())){
101                 return descriptor;
102             }
103         }
104         
105         return null;
106     }
107     
108     /**
109      * INTERNAL:
110      * Method to read an annotation. I think there is a bug in the JDK when
111      * reading annotations from classes. It returns the wrong type. Anyhow,
112      * this method fixes that.
113      */

114     public static <T extends Annotation JavaDoc> T getAnnotation(Class JavaDoc annotation, AnnotatedElement JavaDoc annotatedElement) {
115         return (T) annotatedElement.getAnnotation(annotation);
116     }
117     
118     /**
119      * INTERNAL:
120      * Wrapper to the getAnnotation() call to check if we should ignore
121      * annotations.
122      */

123     public static <T extends Annotation JavaDoc> T getAnnotation(Class JavaDoc annotation, AnnotatedElement JavaDoc annotatedElement, MetadataDescriptor descriptor) {
124         // WIP - we should log a message to the fact of which annotations
125
// we are ignoring.
126
if (descriptor.ignoreAnnotations()) {
127             return null;
128         } else {
129             return (T) getAnnotation(annotation, annotatedElement);
130         }
131     }
132     
133     /**
134      * INTERNAL:
135      * Wrapper to the getAnnotation() call using an Accessor.
136      */

137     public static <T extends Annotation JavaDoc> T getAnnotation(Class JavaDoc annotation, MetadataAccessor accessor) {
138         return (T) getAnnotation(annotation, accessor.getAnnotatedElement(), accessor.getDescriptor());
139     }
140     
141     /**
142      * INTERNAL:
143      * Wrapper to the getAnnotation() call using an MetadataDescriptor.
144      */

145     public static <T extends Annotation JavaDoc> T getAnnotation(Class JavaDoc annotation, MetadataDescriptor descriptor) {
146         return (T) getAnnotation(annotation, descriptor.getJavaClass(), descriptor);
147     }
148     
149     /**
150      * INTERNAL:
151      * Method to convert a getXyz or isXyz method name to an xyz attribute name.
152      * NOTE: The method name passed it may not actually be a method name, so
153      * by default return the name passed in.
154      */

155     public static String JavaDoc getAttributeNameFromMethodName(String JavaDoc methodName) {
156         String JavaDoc leadingChar = "";
157         String JavaDoc restOfName = methodName;
158         
159         if (methodName.startsWith(GET_PROPERTY_METHOD_PREFIX)) {
160             leadingChar = methodName.substring(POSITION_AFTER_GET_PREFIX, POSITION_AFTER_GET_PREFIX + 1);
161             restOfName = methodName.substring(POSITION_AFTER_GET_PREFIX + 1);
162         } else if (methodName.startsWith(IS_PROPERTY_METHOD_PREFIX)){
163             leadingChar = methodName.substring(POSITION_AFTER_IS_PREFIX, POSITION_AFTER_IS_PREFIX + 1);
164             restOfName = methodName.substring(POSITION_AFTER_IS_PREFIX + 1);
165         }
166         
167         return leadingChar.toLowerCase().concat(restOfName);
168     }
169     
170     /**
171      * INTERNAL:
172      * Returns the same candidate methods as an entity listener would.
173      */

174     public static Method JavaDoc[] getCandidateCallbackMethodsForDefaultListener(MetadataEntityListener listener) {
175         return getCandidateCallbackMethodsForEntityListener(listener);
176     }
177     
178     /**
179      * INTERNAL:
180      * Return only the actual methods declared on this entity class.
181      */

182     public static Method JavaDoc[] getCandidateCallbackMethodsForEntityClass(Class JavaDoc entityClass) {
183         return getDeclaredMethods(entityClass);
184     }
185     
186     /**
187      * INTERNAL:
188      * Returns a list of methods from the given class, which can have private,
189      * protected, package and public access, AND will also return public
190      * methods from superclasses.
191      */

192     public static Method JavaDoc[] getCandidateCallbackMethodsForEntityListener(MetadataEntityListener listener) {
193         HashSet JavaDoc candidateMethods = new HashSet JavaDoc();
194         Class JavaDoc listenerClass = listener.getListenerClass();
195         
196         // Add all the declared methods ...
197
Method JavaDoc[] declaredMethods = getDeclaredMethods(listenerClass);
198         for (int i = 0; i < declaredMethods.length; i++) {
199             candidateMethods.add(declaredMethods[i]);
200         }
201         
202         // Now add any public methods from superclasses ...
203
Method JavaDoc[] methods = getMethods(listenerClass);
204         for (int i = 0; i < methods.length; i++) {
205             if (candidateMethods.contains(methods[i])) {
206                 continue;
207             }
208             
209             candidateMethods.add(methods[i]);
210         }
211         
212         return (Method JavaDoc[]) candidateMethods.toArray(new Method JavaDoc[candidateMethods.size()]);
213     }
214     
215     /**
216      * INTERNAL:
217      * Return potential lifecyle callback event methods for a mapped superclass.
218      * We must 'convert' the method to the entity class context before adding it
219      * to the listener.
220      */

221     public static Method JavaDoc[] getCandidateCallbackMethodsForMappedSuperclass(Class JavaDoc mappedSuperclass, Class JavaDoc entityClass) {
222         ArrayList JavaDoc candidateMethods = new ArrayList JavaDoc();
223         Method JavaDoc[] allMethods = getMethods(entityClass);
224         Method JavaDoc[] declaredMethods = getDeclaredMethods(mappedSuperclass);
225         
226         for (int i = 0; i < declaredMethods.length; i++) {
227             Method JavaDoc method = getMethodForName(allMethods, declaredMethods[i].getName());
228             
229             if (method != null) {
230                 candidateMethods.add(method);
231             }
232         }
233         
234         return (Method JavaDoc[]) candidateMethods.toArray(new Method JavaDoc[candidateMethods.size()]);
235     }
236     
237     /**
238      * INTERNAL:
239      * Load a class from a given class name.
240      */

241     public static Class JavaDoc getClassForName(String JavaDoc classname, ClassLoader JavaDoc classLoader) {
242         try {
243             if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()){
244                 try {
245                     return(Class JavaDoc)AccessController.doPrivileged(new PrivilegedClassForName(classname, true, classLoader));
246                 } catch (PrivilegedActionException JavaDoc exception) {
247                     throw ValidationException.unableToLoadClass(classname, exception.getException()); }
248             } else {
249                 return oracle.toplink.essentials.internal.security.PrivilegedAccessHelper.getClassForName(classname, true, classLoader);
250             }
251         } catch (ClassNotFoundException JavaDoc exception) {
252             throw ValidationException.unableToLoadClass(classname, exception);
253         }
254     }
255     
256     /**
257      * INTERNAL:
258      */

259     public static int getDeclaredAnnotationsCount(AnnotatedElement JavaDoc annotatedElement, MetadataDescriptor descriptor) {
260         if (descriptor.ignoreAnnotations()) {
261             return 0;
262         } else {
263             // Look for javax.persistence annotations only.
264
int count = 0;
265             
266             for (Annotation JavaDoc annotation : annotatedElement.getDeclaredAnnotations()) {
267                 if (annotation.annotationType().getName().startsWith(PERSISTENCE_PACKAGE_PREFIX)) {
268                     count++;
269                 }
270             }
271             
272             return count;
273         }
274     }
275     
276     /**
277      * INTERNAL:
278      * Get the declared methods from a class using the doPriveleged security
279      * access. This call returns all methods (private, protected, package and
280      * public) on the give class ONLY. It does not traverse the superclasses.
281      */

282     public static Method JavaDoc[] getDeclaredMethods(Class JavaDoc cls) {
283         if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()){
284             try {
285                 return(Method JavaDoc[])AccessController.doPrivileged(new PrivilegedGetDeclaredMethods(cls));
286             } catch (PrivilegedActionException JavaDoc exception) {
287                 // we will not get here, there are no checked exceptions in this call
288
return null;
289             }
290         } else {
291             return oracle.toplink.essentials.internal.security.PrivilegedAccessHelper.getDeclaredMethods(cls);
292         }
293     }
294     
295     /**
296      * INTERNAL:
297      * Return the discriminator type class for the given discriminator type.
298      */

299     public static Class JavaDoc getDiscriminatorType(String JavaDoc discriminatorType) {
300         if (discriminatorType.equals(MetadataConstants.CHAR)) {
301             return Character JavaDoc.class;
302         } else if (discriminatorType.equals(MetadataConstants.STRING)) {
303             return String JavaDoc.class;
304         } else if (discriminatorType.equals(MetadataConstants.INTEGER)) {
305             return Integer JavaDoc.class;
306         } else {
307             // Should never hit because of validation.
308
return null;
309         }
310     }
311     
312     /**
313      * INTERNAL:
314      * Return the field classification for the given temporal type.
315      */

316     public static Class JavaDoc getFieldClassification(String JavaDoc temporalType) {
317         if (temporalType.equals(MetadataConstants.DATE)) {
318             return java.sql.Date JavaDoc.class;
319         } else if (temporalType.equals(MetadataConstants.TIME)) {
320             return java.sql.Time JavaDoc.class;
321         } else if (temporalType.equals(MetadataConstants.TIMESTAMP)) {
322             return java.sql.Timestamp JavaDoc.class;
323         } else {
324             // Should never hit because of validation.
325
return null;
326         }
327     }
328     
329     /**
330      * INTERNAL:
331      * Helper method that will return a given field based on the provided attribute name.
332      */

333     public static Field JavaDoc getFieldForName(String JavaDoc fieldName, Class JavaDoc javaClass) {
334         Field JavaDoc field = null;
335         
336         try {
337             if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()){
338                 try {
339                     field = (Field JavaDoc)AccessController.doPrivileged(new PrivilegedGetField(javaClass, fieldName, false));
340                 } catch (PrivilegedActionException JavaDoc exception) {
341                     return null;
342                 }
343             } else {
344                 field = PrivilegedAccessHelper.getField(javaClass, fieldName, false);
345             }
346         } catch (NoSuchFieldException JavaDoc nsfex) {
347             return null;
348         }
349         
350         return field;
351     }
352
353     /**
354      * INTERNAL:
355      * Get the declared fields from a class using the doPriveleged security
356      * access.
357      */

358     public static Field JavaDoc[] getFields(Class JavaDoc cls) {
359         if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()){
360             try {
361                 return (Field JavaDoc[])AccessController.doPrivileged(new PrivilegedGetDeclaredFields(cls));
362             } catch (PrivilegedActionException JavaDoc exception) {
363                 // no checked exceptions are thrown, so we should not get here
364
return null;
365             }
366         } else {
367             return PrivilegedAccessHelper.getDeclaredFields(cls);
368         }
369     }
370     
371     /**
372      * INTERNAL:
373      * Returns a fully qualified table name based on the values passed in.
374      * eg. schema.catalog.name
375      */

376     public static String JavaDoc getFullyQualifiedTableName(String JavaDoc tableName, String JavaDoc catalog, String JavaDoc schema) {
377         // catalog, attach it if specified
378
if (! catalog.equals("")) {
379             tableName = catalog + "." + tableName;
380         }
381         
382         // schema, attach it if specified
383
if (! schema.equals("")) {
384             tableName = schema + "." + tableName;
385         }
386     
387         return tableName;
388     }
389     
390     /**
391      * INTERNAL:
392      * Returns a fully qualified table name based on the values passed in.
393      * eg. schema.catalog.name
394      */

395     public static String JavaDoc getFullyQualifiedTableName(String JavaDoc name, String JavaDoc defaultName, String JavaDoc catalog, String JavaDoc schema) {
396         // check if a name was specified otherwise use the default
397
String JavaDoc tableName = name;
398         if (tableName.equals("")) {
399             tableName = defaultName;
400         }
401     
402         return getFullyQualifiedTableName(tableName, catalog, schema);
403     }
404     
405     /**
406      * INTERNAL:
407      * Method to return a generic method return type.
408      */

409     public static Type JavaDoc getGenericReturnType(Method JavaDoc method) {
410         // WIP - should use PrivilegedAccessController
411
return method.getGenericReturnType();
412     }
413     
414     /**
415      * INTERNAL:
416      * Method to return a generic field type.
417      */

418     public static Type JavaDoc getGenericType(Field JavaDoc field) {
419         // WIP - should use PrivilegedAccessController
420
return field.getGenericType();
421     }
422     
423     /**
424      * INTERNAL:
425      * If the methodName passed in is a declared method on cls, then return
426      * the methodName. Otherwise return null to indicate it does not exist.
427      */

428     protected static Method JavaDoc getMethod(String JavaDoc methodName, Class JavaDoc cls, Class JavaDoc[] params) {
429         try {
430             if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()){
431                 try {
432                     return (Method JavaDoc)AccessController.doPrivileged(new PrivilegedGetMethod(cls, methodName, params, true));
433                 } catch (PrivilegedActionException JavaDoc exception) {
434                     return null;
435                 }
436             } else {
437                 return PrivilegedAccessHelper.getMethod(cls, methodName, params, true);
438             }
439         } catch (NoSuchMethodException JavaDoc e1) {
440             return null;
441         }
442     }
443     
444     /**
445      * INTERNAL:
446      * Find the method in the list where method.getName() == methodName.
447      */

448     public static Method JavaDoc getMethodForName(Method JavaDoc[] methods, String JavaDoc methodName) {
449         for (int i = 0; i < methods.length; i++) {
450             Method JavaDoc method = methods[i];
451         
452             if (method.getName().equals(methodName)) {
453                 return method;
454             }
455         }
456         
457         return null;
458     }
459     
460     /**
461      * INTERNAL:
462      * Method to convert an xyz property name into a getXyz or isXyz method.
463      */

464     public static Method JavaDoc getMethodForPropertyName(String JavaDoc propertyName, Class JavaDoc cls) {
465         Method JavaDoc method;
466         
467         String JavaDoc leadingChar = String.valueOf(propertyName.charAt(0)).toUpperCase();
468         String JavaDoc restOfName = propertyName.substring(1);
469         
470         // Look for a getPropertyName() method
471
method = getMethod(GET_PROPERTY_METHOD_PREFIX.concat(leadingChar).concat(restOfName), cls, new Class JavaDoc[]{});
472         
473         if (method == null) {
474             // Look for an isPropertyName() method
475
method = getMethod(IS_PROPERTY_METHOD_PREFIX.concat(leadingChar).concat(restOfName), cls, new Class JavaDoc[]{});
476         }
477         
478         return method;
479     }
480     
481     /**
482      * INTERNAL:
483      * Get the methods from a class using the doPriveleged security access.
484      * This call returns only public methods from the given class and its
485      * superclasses.
486      */

487     public static Method JavaDoc[] getMethods(Class JavaDoc cls) {
488         if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()){
489             try {
490                 return (Method JavaDoc[])AccessController.doPrivileged(new PrivilegedGetMethods(cls));
491             } catch (PrivilegedActionException JavaDoc exception) {
492                 return null;
493             }
494         } else {
495             return PrivilegedAccessHelper.getMethods(cls);
496         }
497     }
498     
499     /**
500      * INTERNAL:
501      * Return the raw class of the generic type.
502      */

503     public static Class JavaDoc getRawClassFromGeneric(Type JavaDoc type) {
504         return (Class JavaDoc)(((ParameterizedType JavaDoc) type).getRawType());
505     }
506     
507     /**
508      * INTERNAL:
509      * Method to return the correct reference class for either a method or a
510      * field. If targetEntity is not specified return the default.
511      */

512     public static Class JavaDoc getReferenceClass(Class JavaDoc defaultReferenceClass, Class JavaDoc targetEntity) {
513         if (targetEntity == void.class) {
514             return defaultReferenceClass;
515         }
516         
517         return targetEntity;
518     }
519     
520     /**
521      * INTERNAL:
522      * Helper method to return the type class of a ParameterizedType. This will
523      * handle the case for a generic collection. It now supports multiple types,
524      * e.g. Hastable<<String>, <Employee>>
525      */

526     public static Class JavaDoc getReturnTypeFromGeneric(Type JavaDoc type) {
527         ParameterizedType JavaDoc pType = (ParameterizedType JavaDoc) type;
528         
529         if (java.util.Map JavaDoc.class.isAssignableFrom((Class JavaDoc) pType.getRawType())) {
530             return (Class JavaDoc) pType.getActualTypeArguments()[1];
531         }
532         
533         return (Class JavaDoc) pType.getActualTypeArguments()[0];
534     }
535     
536     /**
537      * INTERNAL:
538      * Method to convert a getMethod into a setMethod. This method could return
539      * null if the corresponding set method is not found.
540      */

541     public static Method JavaDoc getSetMethod(Method JavaDoc method, Class JavaDoc cls) {
542         String JavaDoc getMethodName = method.getName();
543         Class JavaDoc[] params = new Class JavaDoc[] { method.getReturnType() };
544             
545         if (getMethodName.startsWith(GET_PROPERTY_METHOD_PREFIX)) {
546             // Replace 'get' with 'set'.
547
return getMethod(SET_PROPERTY_METHOD_PREFIX + getMethodName.substring(3), cls, params);
548         }
549         
550         // methodName.startsWith(IS_PROPERTY_METHOD_PREFIX)
551
// Check for a setXyz method first, if it exists use it.
552
Method JavaDoc setMethod = getMethod(SET_PROPERTY_METHOD_PREFIX + getMethodName.substring(2), cls, params);
553         
554         if (setMethod == null) {
555             // setXyz method was not found try setIsXyz
556
return getMethod(SET_IS_PROPERTY_METHOD_PREFIX + getMethodName.substring(2), cls, params);
557         }
558         
559         return setMethod;
560     }
561
562     /**
563      * INTERNAL:
564      */

565     public static boolean havePersistenceAnnotationsDefined(AnnotatedElement JavaDoc[] annotatedElements) {
566         for (AnnotatedElement JavaDoc annotatedElement : annotatedElements) {
567             for (Annotation JavaDoc annotation : annotatedElement.getDeclaredAnnotations()) {
568                 if (annotation.annotationType().getName().startsWith(PERSISTENCE_PACKAGE_PREFIX)) {
569                     return true;
570                 }
571             }
572         }
573         
574         return false;
575     }
576  
577     /**
578      * INTERNAL:
579      * Indicates whether the specified annotation is actually not present on
580      * the specified class. Used for defaulting. Need this check since the
581      * isAnnotationPresent calls can return a false when true because of the
582      * meta-data complete feature.
583      */

584     public static boolean isAnnotationNotPresent(Class JavaDoc annotation, AnnotatedElement JavaDoc annotatedElement) {
585         return ! annotatedElement.isAnnotationPresent(annotation);
586     }
587     
588     /**
589      * INTERNAL:
590      * Indicates whether the specified annotation is present on the specified
591      * class.
592      */

593     public static boolean isAnnotationPresent(Class JavaDoc annotation, AnnotatedElement JavaDoc annotatedElement) {
594         return annotatedElement.isAnnotationPresent(annotation);
595     }
596     
597     /**
598      * INTERNAL:
599      * Indicates whether the specified annotation is present on the specified
600      * class.
601      */

602     public static boolean isAnnotationPresent(Class JavaDoc annotation, AnnotatedElement JavaDoc annotatedElement, MetadataDescriptor descriptor) {
603         // WIP - we should log a message to the fact of which annotations
604
// we are ignoring.
605
if (descriptor.ignoreAnnotations()) {
606             return false;
607         } else {
608             return isAnnotationPresent(annotation, annotatedElement);
609         }
610     }
611     
612     /**
613      * INTERNAL:
614      * Indicates whether the specified annotation is present on java class
615      * for the given descriptor metadata.
616      */

617     public static boolean isAnnotationPresent(Class JavaDoc annotation, MetadataDescriptor descriptor) {
618         return isAnnotationPresent(annotation, descriptor.getJavaClass(), descriptor);
619     }
620     
621     /**
622      * INTERNAL:
623      * Return true if this accessor represents an aggregate mapping. True is
624      * returned id and @Embedded is found or if an @Embeddable is found on the
625      * reference class.
626      */

627     public static boolean isEmbedded(MetadataAccessibleObject accessibleObject, MetadataDescriptor descriptor) {
628         AnnotatedElement JavaDoc annotatedElement = accessibleObject.getAnnotatedElement();
629         
630         if (isAnnotationNotPresent(Embedded.class, annotatedElement) && isAnnotationNotPresent(EmbeddedId.class, annotatedElement)) {
631             return (isAnnotationPresent(Embeddable.class, accessibleObject.getReferenceClass()));
632         } else {
633             // Still need to make the call since we may need to ignore it
634
// because of meta-data complete.
635
return isAnnotationPresent(Embedded.class, annotatedElement, descriptor);
636         }
637     }
638     
639     /**
640      * INTERNAL:
641      * Return true if this accessor represents an aggregate mapping. True is
642      * returned id and @Embedded is found or if an @Embeddable is found on the
643      * reference class.
644      */

645     public static boolean isEmbeddedId(MetadataAccessibleObject accessibleObject, MetadataDescriptor descriptor) {
646         return isAnnotationPresent(EmbeddedId.class, accessibleObject.getAnnotatedElement(), descriptor);
647     }
648     
649     /**
650      * INTERNAL:
651      * Method to return whether a collection type is a generic.
652      */

653     public static boolean isGenericCollectionType(Type JavaDoc type) {
654         return (type instanceof ParameterizedType JavaDoc);
655     }
656
657     /**
658      * INTERNAL:
659      * Return true if this field accessor represents a m-m relationship.
660      */

661     public static boolean isManyToMany(MetadataAccessibleObject accessibleObject, MetadataDescriptor descriptor) {
662         Class JavaDoc rawClass = accessibleObject.getRawClass();
663         AnnotatedElement JavaDoc annotatedElement = accessibleObject.getAnnotatedElement();
664         
665         if (isAnnotationPresent(ManyToMany.class, annotatedElement, descriptor)) {
666             if (MetadataHelper.isSupportedCollectionClass(rawClass)) {
667                 return true;
668             } else {
669                 throw ValidationException.invalidCollectionTypeForRelationship(rawClass, annotatedElement);
670             }
671         }
672         
673         return false;
674     }
675     
676     /**
677      * INTERNAL:
678      * Return true if this accessor represents a m-1 relationship.
679      */

680     public static boolean isManyToOne(MetadataAccessibleObject annotatedAccessor, MetadataDescriptor descriptor) {
681         return isAnnotationPresent(ManyToOne.class, annotatedAccessor.getAnnotatedElement(), descriptor);
682     }
683     
684     /**
685      * INTERNAL: WIP send in the processor
686      * Return true if this accessor represents a 1-m relationship.
687      */

688     public static boolean isOneToMany(MetadataAccessibleObject annotatedAccessor, MetadataLogger logger, MetadataDescriptor descriptor) {
689         Class JavaDoc rawClass = annotatedAccessor.getRawClass();
690         AnnotatedElement JavaDoc annotatedElement = annotatedAccessor.getAnnotatedElement();
691         
692         if (isAnnotationNotPresent(OneToMany.class, annotatedElement)) {
693             if (MetadataHelper.isGenericCollectionType(annotatedAccessor.getRelationType()) && MetadataHelper.isSupportedCollectionClass(rawClass)) {
694                 logger.logConfigMessage(MetadataLogger.ONE_TO_MANY_MAPPING, annotatedElement);
695                 return true;
696             }
697         } else {
698             // Still need to make the call since we may need to ignore it
699
// because of meta-data complete.
700
if (isAnnotationPresent(OneToMany.class, annotatedElement, descriptor)) {
701                 if (MetadataHelper.isSupportedCollectionClass(rawClass)) {
702                     return true;
703                 } else {
704                     throw ValidationException.invalidCollectionTypeForRelationship(rawClass, annotatedElement);
705                 }
706             }
707         }
708         
709         return false;
710     }
711     
712     /**
713      * INTERNAL:
714      * Return true if this accessor represents a 1-1 relationship.
715      */

716     public static boolean isOneToOne(MetadataAccessibleObject accessibleObject, MetadataProject project, MetadataLogger logger, MetadataDescriptor descriptor) {
717         Class JavaDoc referenceClass = accessibleObject.getReferenceClass();
718         AnnotatedElement JavaDoc annotatedElement = accessibleObject.getAnnotatedElement();
719         
720         if (isAnnotationNotPresent(OneToOne.class, annotatedElement)) {
721             if (project.containsDescriptor(referenceClass) && ! isEmbedded(accessibleObject, descriptor)) {
722                 logger.logConfigMessage(MetadataLogger.ONE_TO_ONE_MAPPING, annotatedElement);
723                 return true;
724             } else {
725                 return false;
726             }
727         } else {
728             // Still need to make the call since we may need to ignore it
729
// because of meta-data complete.
730
return isAnnotationPresent(OneToOne.class, annotatedElement, descriptor);
731         }
732     }
733     
734     /**
735      * INTERNAL:
736      * Returns true is the given class is primitive wrapper type.
737      */

738      public static boolean isPrimitiveWrapperClass(Class JavaDoc cls) {
739         return cls.equals(Long JavaDoc.class) ||
740                cls.equals(Short JavaDoc.class) ||
741                cls.equals(Float JavaDoc.class) ||
742                cls.equals(Byte JavaDoc.class) ||
743                cls.equals(Double JavaDoc.class) ||
744                cls.equals(Number JavaDoc.class) ||
745                cls.equals(Boolean JavaDoc.class) ||
746                cls.equals(Integer JavaDoc.class) ||
747                cls.equals(Character JavaDoc.class) ||
748                cls.equals(java.math.BigInteger JavaDoc.class) ||
749                cls.equals(java.math.BigDecimal JavaDoc.class);
750      }
751      
752     /**
753      * INTERNAL:
754      * Method to return whether a class is a supported Collection. EJB 3.0 spec
755      * currently only supports Collection and Set.
756      */

757     public static boolean isSupportedCollectionClass(Class JavaDoc cls) {
758         return cls == Collection JavaDoc.class ||
759                cls == Set JavaDoc.class ||
760                cls == List JavaDoc.class ||
761                cls == Map JavaDoc.class;
762     }
763     
764     /**
765      * INTERNAL:
766      * Search the class for an attribute with a name matching 'attributeName'
767      */

768     public static boolean isValidAttributeName(String JavaDoc attributeName, Class JavaDoc javaClass) {
769         Field JavaDoc attributes[] = getFields(javaClass);
770         
771         for (int i = 0; i < attributes.length; i++) {
772             if (attributes[i].getName().equals(attributeName)) {
773                 return true;
774             }
775         }
776
777         return false;
778     }
779     
780     /**
781      * INTERNAL:
782      * Returns true if the given class is a valid blob type.
783      */

784     public static boolean isValidBlobType(Class JavaDoc cls) {
785         return cls.equals(byte[].class) ||
786                cls.equals(Byte JavaDoc[].class) ||
787                cls.equals(java.sql.Blob JavaDoc.class) ||
788                Helper.classImplementsInterface(cls, java.io.Serializable JavaDoc.class);
789     }
790     
791     /**
792      * INTERNAL:
793      * Returns true if the given class is a valid clob type.
794      */

795     public static boolean isValidClobType(Class JavaDoc cls) {
796         return cls.equals(char[].class) ||
797                cls.equals(String JavaDoc.class) ||
798                cls.equals(Character JavaDoc[].class) ||
799                cls.equals(java.sql.Clob JavaDoc.class);
800     }
801     
802     /**
803      * INTERNAL:
804      * Return true if the given class is a valid enum type.
805      */

806     public static boolean isValidEnumeratedType(Class JavaDoc cls) {
807         return cls.isEnum();
808     }
809     
810     /**
811      * INTERNAL:
812      * Returns true if the given class is a valid lob type.
813      */

814     public static boolean isValidLobType(Class JavaDoc cls) {
815         return isValidClobType(cls) || isValidBlobType(cls);
816     }
817     
818     /**
819      * INTERNAL:
820      */

821     public static boolean isValidPersistenceMethodName(String JavaDoc methodName) {
822         return methodName.startsWith(GET_PROPERTY_METHOD_PREFIX) || methodName.startsWith(IS_PROPERTY_METHOD_PREFIX);
823     }
824     
825     /**
826      * INTERNAL:
827      * Returns true if the given class is valid for SerializedObjectMapping.
828      */

829     public static boolean isValidSerializedType(Class JavaDoc cls) {
830         if (cls.isPrimitive()) {
831             return false;
832         }
833         
834         if (isPrimitiveWrapperClass(cls)) {
835             return false;
836         }
837         
838         if (isValidLobType(cls)) {
839             return false;
840         }
841         
842         if (isValidTemporalType(cls)) {
843             return false;
844         }
845      
846         return true;
847     }
848      
849     /**
850      * INTERNAL:
851      * Returns true if the given class is a valid temporal type and must be
852      * marked temporal.
853      */

854     public static boolean isValidTemporalType(Class JavaDoc cls) {
855         return (cls.equals(java.util.Date JavaDoc.class) ||
856                 cls.equals(java.util.Calendar JavaDoc.class) ||
857                 cls.equals(java.util.GregorianCalendar JavaDoc.class));
858      }
859      
860     /**
861      * INTERNAL:
862      * Returns true if the given class is a valid timestamp locking type.
863      */

864     public static boolean isValidTimstampVersionLockingType(Class JavaDoc cls) {
865         return (cls.equals(java.sql.Timestamp JavaDoc.class));
866     }
867      
868     /**
869      * INTERNAL:
870      * Returns true if the given class is a valid version locking type.
871      */

872     public static boolean isValidVersionLockingType(Class JavaDoc cls) {
873         return (cls.equals(int.class) ||
874                 cls.equals(Integer JavaDoc.class) ||
875                 cls.equals(short.class) ||
876                 cls.equals(Short JavaDoc.class) ||
877                 cls.equals(long.class) ||
878                 cls.equals(Long JavaDoc.class));
879     }
880     
881     /**
882      * INTERNAL:
883      * Indicates whether the class should ignore annotations. Note that such
884      * classes should already have their descriptors with PKs added to
885      * session's project.
886      */

887     public static boolean shouldIgnoreAnnotations(Class JavaDoc cls, HashMap JavaDoc<Class JavaDoc, MetadataDescriptor> metadataDescriptors) {
888         MetadataDescriptor descriptor = metadataDescriptors.get(cls);
889         
890         if (descriptor != null) {
891             return descriptor.ignoreAnnotations();
892         } else {
893             return false;
894         }
895     }
896 }
897
Popular Tags