/** * Goes through the class hierarchy and find the authorization annotations attached to a certain * method. * * @param clazz class to be scanned * @param authorizationActionMap the map to be populated */ private void findAuthorizationActions( Class<?> clazz, Map<String, String> authorizationActionMap) { if (clazz == null || clazz == Object.class) { return; } String classAuthorizationActionsAllowed = getAuthorizationActions(clazz.getAnnotations(), AUTHORIZATION_ANNOTATION_CLASS_NAME); for (Method m : clazz.getMethods()) { if (SKIP_METHODS.contains(m.getName())) { continue; } String methodAuthorizationActionsAllowed = getAuthorizationActions(m.getAnnotations(), AUTHORIZATION_ANNOTATION_CLASS_NAME); String authorizationActions = methodAuthorizationActionsAllowed != null ? methodAuthorizationActionsAllowed : classAuthorizationActionsAllowed; if (authorizationActions != null) { authorizationActionMap.put(m.getName(), authorizationActions); } } if (!authorizationActionMap.isEmpty()) { return; } findAuthorizationActions(clazz.getSuperclass(), authorizationActionMap); if (!authorizationActionMap.isEmpty()) { return; } for (Class<?> interfaceCls : clazz.getInterfaces()) { findAuthorizationActions(interfaceCls, authorizationActionMap); } }
private void assertAnnotations(Class<?> type) { assertThat( describe(type).getDeclaredAnnotations(), hasItems( new AnnotationList.ForLoadedAnnotation(type.getDeclaredAnnotations()) .toArray(new AnnotationDescription[type.getDeclaredAnnotations().length]))); assertThat( describe(type).getDeclaredAnnotations().size(), is(type.getDeclaredAnnotations().length)); assertThat( describe(type).getInheritedAnnotations(), hasItems( new AnnotationList.ForLoadedAnnotation(type.getAnnotations()) .toArray(new AnnotationDescription[type.getAnnotations().length]))); assertThat(describe(type).getInheritedAnnotations().size(), is(type.getAnnotations().length)); }
/** * Checks for {@link InstanceResolverAnnotation} and creates an instance resolver from it if any. * Otherwise null. */ public static <T> InstanceResolver<T> createFromInstanceResolverAnnotation( @NotNull Class<T> clazz) { for (Annotation a : clazz.getAnnotations()) { InstanceResolverAnnotation ira = a.annotationType().getAnnotation(InstanceResolverAnnotation.class); if (ira == null) continue; Class<? extends InstanceResolver> ir = ira.value(); try { return ir.getConstructor(Class.class).newInstance(clazz); } catch (InstantiationException e) { throw new WebServiceException( ServerMessages.FAILED_TO_INSTANTIATE_INSTANCE_RESOLVER( ir.getName(), a.annotationType(), clazz.getName())); } catch (IllegalAccessException e) { throw new WebServiceException( ServerMessages.FAILED_TO_INSTANTIATE_INSTANCE_RESOLVER( ir.getName(), a.annotationType(), clazz.getName())); } catch (InvocationTargetException e) { throw new WebServiceException( ServerMessages.FAILED_TO_INSTANTIATE_INSTANCE_RESOLVER( ir.getName(), a.annotationType(), clazz.getName())); } catch (NoSuchMethodException e) { throw new WebServiceException( ServerMessages.FAILED_TO_INSTANTIATE_INSTANCE_RESOLVER( ir.getName(), a.annotationType(), clazz.getName())); } } return null; }
private void introspectInjectClass( AnnotatedType<X> type, ArrayList<ConfigProgram> injectProgramList) { InjectManager cdiManager = getBeanManager(); for (Annotation ann : type.getAnnotations()) { Class<? extends Annotation> annType = ann.annotationType(); InjectionPointHandler handler = cdiManager.getInjectionPointHandler(annType); if (handler != null) { injectProgramList.add(new ClassHandlerProgram(ann, handler)); } } // ioc/123i for (Class<?> parentClass = type.getJavaClass().getSuperclass(); parentClass != null; parentClass = parentClass.getSuperclass()) { for (Annotation ann : parentClass.getAnnotations()) { Class<? extends Annotation> annType = ann.annotationType(); InjectionPointHandler handler = cdiManager.getInjectionPointHandler(annType); if (handler != null) { injectProgramList.add(new ClassHandlerProgram(ann, handler)); } } } }
private final void validateTwoAnnotations(final PackageInfoModifier.Modification mod) throws Exception { assertNotNull(mod); final byte[] newClass = mod.toByteArray(); assertNotNull(newClass); assertTrue(newClass.length > 0); final Class<?> c = new ClassDefiner().define(mod.getPackageName(), newClass); assertNotNull(c); final Annotation[] annotations = c.getAnnotations(); assertNotNull(annotations); assertTrue(annotations.length == 2); Annotation a = annotations[0]; assertNotNull(a); if (a instanceof Deprecated) { a = annotations[1]; assertNotNull(a); } assertTrue(a instanceof XmlJavaTypeAdapters); final XmlJavaTypeAdapters adaptersAnnotation = (XmlJavaTypeAdapters) a; final XmlJavaTypeAdapter[] adapters = adaptersAnnotation.value(); assertNotNull(adapters); assertEquals(1, adapters.length); final XmlJavaTypeAdapter adapter = adapters[0]; assertNotNull(adapter); assertEquals(Person.class, adapter.type()); assertEquals(AnyTypeAdapter.class, adapter.value()); }
/** * Finds all constraint annotations defined for the given class and returns them in a list of * constraint descriptors. * * @param beanClass The class to check for constraints annotations. * @return A list of constraint descriptors for all constraint specified on the given class. */ private List<ConstraintDescriptorImpl<?>> findClassLevelConstraints(Class<?> beanClass) { List<ConstraintDescriptorImpl<?>> metaData = new ArrayList<ConstraintDescriptorImpl<?>>(); for (Annotation annotation : beanClass.getAnnotations()) { metaData.addAll(findConstraintAnnotations(beanClass, annotation, ElementType.TYPE)); } return metaData; }
/** * @param uri The uri to identify the component with. * @param type The type to create the metadata for * @param factory A reflection library to provide class construction and field get/set * functionality * @param copyStrategies A copy strategy library * @throws NoSuchMethodException If the component has no default constructor */ public ComponentMetadata( SimpleUri uri, Class<T> type, ReflectFactory factory, CopyStrategyLibrary copyStrategies) throws NoSuchMethodException { super(uri, type, factory, copyStrategies, Predicates.<Field>alwaysTrue()); replicated = type.getAnnotation(Replicate.class) != null; blockLifecycleEventsRequired = type.getAnnotation(RequiresBlockLifecycleEvents.class) != null; ForceBlockActive forceBlockActiveAnnotation = type.getAnnotation(ForceBlockActive.class); if (forceBlockActiveAnnotation != null) { forceBlockActive = true; retainUnalteredOnBlockChange = forceBlockActiveAnnotation.retainUnalteredOnBlockChange(); } for (ComponentFieldMetadata<T, ?> field : getFields()) { if (field.isReplicated()) { replicated = true; if (field.getReplicationInfo().value().isReplicateFromOwner()) { replicatedFromOwner = true; } } if (field.isOwnedReference()) { referenceOwner = true; } } annotations = Lists.newArrayList(type.getAnnotations()); }
private void inspect() { managerModCount = manager.getModCount(); // first global, then type level, then method level // but later one can override pre (for same annotation) List<Annotation> typeLevel = new ArrayList<Annotation>(); Class<?> serviceType = serviceClass; while (serviceType != null) { for (Annotation ann : serviceType.getAnnotations()) { if (ann.annotationType().isAnnotationPresent(AcServiceIntercepted.class)) { putOrAppendAnnotation(typeLevel, ann); } } Class<?> theType = serviceType; serviceType = null; for (Class<?> superInf : theType.getInterfaces()) { if (AcService.class.isAssignableFrom(superInf)) { serviceType = superInf; break; } } } for (Method method : serviceClass.getMethods()) { List<Annotation> annList = new ArrayList<Annotation>(typeLevel); for (Annotation ann : method.getAnnotations()) { if (ann.annotationType().isAnnotationPresent(AcServiceIntercepted.class)) { putOrAppendAnnotation(annList, ann); } } methodAnnotationList.put(method, annList); setupRuntimeInterceptorList(method); } }
protected EndpointConfig add(Annotation[] annotations, boolean forWriting) { // Same as [issue-10] with JSON provider; must check for null: if (annotations != null) { for (Annotation annotation : annotations) { Class<?> type = annotation.annotationType(); if (type == JsonView.class) { // Can only use one view; but if multiple defined, use first (no exception) Class<?>[] views = ((JsonView) annotation).value(); _activeView = (views.length > 0) ? views[0] : null; } else if (type == JsonRootName.class) { _rootName = ((JsonRootName) annotation).value(); } else if (type == JacksonFeatures.class) { JacksonFeatures feats = (JacksonFeatures) annotation; if (forWriting) { _serEnable = nullIfEmpty(feats.serializationEnable()); _serDisable = nullIfEmpty(feats.serializationDisable()); } else { _deserEnable = nullIfEmpty(feats.deserializationEnable()); _deserDisable = nullIfEmpty(feats.deserializationDisable()); } } else if (type == JacksonAnnotationsInside.class) { // skip; processed below (in parent), so encountering here is of no use } else { // For all unrecognized types, check meta-annotation(s) to see if they are bundles JacksonAnnotationsInside inside = type.getAnnotation(JacksonAnnotationsInside.class); if (inside != null) { add(type.getAnnotations(), forWriting); } } } } return this; }
@Override public List<Module> get() { List<Module> modules = new ArrayList<>(); ClassPath classpath; for (String pkg : packages) { try { classpath = ClassPath.from(Thread.currentThread().getContextClassLoader()); for (ClassPath.ClassInfo classInfo : classpath.getTopLevelClassesRecursive(pkg)) { try { // Include Modules that have at least on Conditional Class<?> cls = Class.forName(classInfo.getName(), false, ClassLoader.getSystemClassLoader()); if (!cls.isInterface() && !Modifier.isAbstract(cls.getModifiers()) && Module.class.isAssignableFrom(cls)) { for (Annotation annot : cls.getAnnotations()) { if (null != annot.annotationType().getAnnotation(Conditional.class)) { modules.add((Module) cls.newInstance()); break; } } } } catch (Exception e) { throw new RuntimeException("Failed to instantiate module '" + pkg + "'", e); } } } catch (Exception e) { throw new RuntimeException("Failed to scan root package '" + pkg + "'", e); } } return modules; }
public void registerServlets(String packageName, ServletContextHandler context) { // 遍历指定包下的所有类文件 Set<Class<?>> classes = ClassUtils.getClasses(packageName); Iterator<Class<?>> iter = classes.iterator(); while (iter.hasNext()) { Class<?> cls = iter.next(); Annotation[] anns = cls.getAnnotations(); for (Annotation ann : anns) { if (ann instanceof WebServlet) { try { ServletHolder servlet = new ServletHolder((HttpServlet) cls.newInstance()); WebServlet path = (WebServlet) ann; context.addServlet(servlet, path.value()[0]); this.holders.add(servlet); if (logger.isDebugEnabled()) { logger.info("register servlet: " + cls.getName() + " succeeded"); } } catch (InstantiationException ie) { logger.error("registerServlets", ie); } catch (IllegalAccessException iae) { logger.error("registerServlets", iae); } catch (Exception e) { logger.error("registerServlets", e); } break; } } } }
/** Returns true if the given class has a scope annotation. */ private static boolean hasScope(Class<? extends Interceptor> interceptorClass) { for (Annotation annotation : interceptorClass.getAnnotations()) { if (Annotations.isScopeAnnotation(annotation.annotationType())) { return true; } } return false; }
private static boolean isIgnoreAnnotationPresent(Class<?> candidate) { for (Annotation annotation : candidate.getAnnotations()) { if (annotation.toString().contains("Ignore")) { return true; } } return false; }
/** * Create new factory instance for given type and bean manager. * * @param rawType type of the components to provide. * @param locator actual HK2 service locator instance. * @param beanManager current bean manager to get references from. * @param cdiManaged set to {@code true} if the component should be managed by CDI. */ public CdiBeanHk2Factory( final Class<T> rawType, final ServiceLocator locator, final BeanManager beanManager, final boolean cdiManaged) { this.clazz = rawType; this.qualifiers = CdiUtil.getQualifiers(clazz.getAnnotations()); this.referenceProvider = cdiManaged ? new InstanceManager<T>() { final Iterator<Bean<?>> beans = beanManager.getBeans(clazz, qualifiers).iterator(); final Bean bean = beans.hasNext() ? beans.next() : null; final CreationalContext creationalContext = bean != null ? beanManager.createCreationalContext(bean) : null; @Override public T getInstance(final Class<T> clazz) { return (bean != null) ? (T) beanManager.getReference(bean, clazz, creationalContext) : null; } @Override public void preDestroy(final T instance) { // do nothing } } : new InstanceManager<T>() { final AnnotatedType<T> annotatedType = beanManager.createAnnotatedType(clazz); final InjectionTargetFactory<T> injectionTargetFactory = beanManager.getInjectionTargetFactory(annotatedType); final InjectionTarget<T> injectionTarget = injectionTargetFactory.createInjectionTarget(null); final CreationalContext<T> creationalContext = beanManager.createCreationalContext(null); @Override public T getInstance(final Class<T> clazz) { final T instance = injectionTarget.produce(creationalContext); injectionTarget.inject(instance, creationalContext); if (locator != null) { locator.inject(instance, CdiComponentProvider.CDI_CLASS_ANALYZER); } injectionTarget.postConstruct(instance); return instance; } @Override public void preDestroy(final T instance) { injectionTarget.preDestroy(instance); } }; }
/** Factory method to obtain a {@link SourceClass} from a {@link Class}. */ public SourceClass asSourceClass(Class<?> classType) throws IOException { try { // Sanity test that we can read annotations, if not fall back to ASM classType.getAnnotations(); return new SourceClass(classType); } catch (Throwable ex) { // Enforce ASM via class name resolution return asSourceClass(classType.getName()); } }
private static boolean isTest(Class c) { for( Annotation a : c.getAnnotations() ) if( a instanceof Ignore ) return false; for( Method m : c.getMethods() ) for( Annotation a : m.getAnnotations() ) if( a instanceof Test ) return true; return false; }
/** * Returns whether or not to require that the user have all of the privileges in order to be * "authorized" for this class * * @param target the class to act on * @return boolean true/false whether to "and" privileges together * @see org.openmrs.annotation.Authorized#requireAll() */ public boolean getRequireAll(Class target) { for (Annotation annotation : target.getAnnotations()) { // check for Secured annotations if (annotation instanceof Authorized) { Authorized attr = (Authorized) annotation; return attr.requireAll(); } } return false; }
public static Class<? extends Annotation> getScopeAnnotation(Class<?> clazz) { Annotation[] anns = clazz.getAnnotations(); for (Annotation a : anns) { Class<? extends Annotation> annClass = a.annotationType(); if (ApplicationScoped.class == annClass || Dependent.class == annClass || ContextScoped.class == annClass) return annClass; } return ContextScoped.class; }
public ScriptManifest getAnnotation(Class<?> sClass) { Annotation[] annotations = sClass.getAnnotations(); for (Annotation annotation : annotations) { if (annotation instanceof ScriptManifest) { return (ScriptManifest) annotation; } } return null; }
/** * Gets all the annotation info for a particular class and puts it in our annotation info cache. * * @param c * @return */ public AnnotationInfo putAnnotationInfo(Class c) { { Entity entity = (Entity) c.getAnnotation(Entity.class); if (entity == null) { throw new PersistenceException("Class not marked as an @Entity: " + c.getName()); } } AnnotationInfo ai = new AnnotationInfo(); ai.setClassAnnotations(c.getAnnotations()); ai.setMainClass(c); Class superClass = c; Class rootClass = null; while ((superClass = superClass.getSuperclass()) != null) { MappedSuperclass mappedSuperclass = (MappedSuperclass) superClass.getAnnotation(MappedSuperclass.class); Entity entity = (Entity) superClass.getAnnotation(Entity.class); Inheritance inheritance = (Inheritance) superClass.getAnnotation(Inheritance.class); if (mappedSuperclass != null || entity != null) { putProperties(ai, superClass); putMethods(ai, superClass); if (entity != null) { rootClass = superClass; } putEntityListeners(ai, superClass); } } if (rootClass != null) { ai.setRootClass(rootClass); DiscriminatorValue dv = (DiscriminatorValue) c.getAnnotation(DiscriminatorValue.class); String discriminatorValue; if (dv != null) { discriminatorValue = dv.value(); if (discriminatorValue == null) { throw new PersistenceException( "You must specify a value= for @DiscriminatorValue on " + c.getName()); } } else { discriminatorValue = c.getSimpleName(); } ai.setDiscriminatorValue(discriminatorValue); discriminatorMap.put(discriminatorValue, ai); } else { ai.setRootClass(c); } putTableDeclaration(ai, c); putProperties(ai, c); putMethods(ai, c); if (ai.getIdMethod() == null) { throw new PersistenceException("No ID method specified for: " + c.getName()); } putEntityListeners(ai, c); getAnnotationMap().put(c.getName(), ai); return ai; }
protected static List<Class<? extends Annotation>> getNameBound(Class<?> declaring) { List<Class<? extends Annotation>> nameBound = new ArrayList<Class<? extends Annotation>>(); for (Annotation annotation : declaring.getAnnotations()) { if (annotation.annotationType().isAnnotationPresent(NameBinding.class)) { if (nameBound == null) { nameBound.add(annotation.annotationType()); } } } return nameBound; }
private boolean hasFileDependencyAnnotation(Class<?> clazz) { // return clazz.isAnnotationPresent(FileDependency.class);// because of some reason, does not // work. (different classloader?) Annotation[] annotations = clazz.getAnnotations(); if (annotations == null || annotations.length == 0) return false; for (Annotation annotation : annotations) if (annotation.annotationType().getName().equals(FileDependency.class.getName())) return true; return false; }
public static void PrintAnnotationsOnClass(Class<?> cls) { System.out.println("Annotation for class: " + cls.getName()); Annotation[] annotations = cls.getAnnotations(); if (annotations.length == 0) { System.out.println(" None"); } else { for (Annotation a : annotations) { System.out.println(" annotation: " + a.getClass().getName()); } } }
@SuppressWarnings("rawtypes") public static Set<Annotation> getAnnotations(Class cls) { Set<Annotation> ret = new HashSet<Annotation>(); ret.addAll(Arrays.asList(cls.getAnnotations())); if (cls.getSuperclass() != null) { ret.addAll(getAnnotations(cls.getSuperclass())); } for (Class intrface : cls.getInterfaces()) { ret.addAll(getAnnotations(intrface)); } return ret; }
/** * Accessor for the MetaData for the specified class, read from annotations. The annotations can * be of any supported type. * * @param cls The class * @param pmd PackageMetaData to use as a parent * @param clr ClassLoader resolver * @return The ClassMetaData */ public AbstractClassMetaData getMetaDataForClass( Class cls, PackageMetaData pmd, ClassLoaderResolver clr) { if (cls == null) { return null; } Annotation[] annotations = cls.getAnnotations(); if (annotations == null || annotations.length == 0) { return null; } // Find an annotation reader for this classes annotations (if we have one) String readerClassName = null; for (int i = 0; i < annotations.length; i++) { String reader = annotationReaderLookup.get(annotations[i].annotationType().getName()); if (reader != null) { readerClassName = reader; break; } } if (readerClassName == null) { NucleusLogger.METADATA.debug(Localiser.msg("044202", cls.getName())); return null; } AnnotationReader reader = annotationReaders.get(readerClassName); if (reader == null) { // Try to create this AnnotationReader try { Class[] ctrArgs = new Class[] {ClassConstants.METADATA_MANAGER}; Object[] ctrParams = new Object[] {metadataMgr}; PluginManager pluginMgr = metadataMgr.getNucleusContext().getPluginManager(); reader = (AnnotationReader) pluginMgr.createExecutableExtension( "org.datanucleus.annotations", "reader", readerClassName, "reader", ctrArgs, ctrParams); annotationReaders.put( readerClassName, reader); // Save the annotation reader in case we have more of this type } catch (Exception e) { NucleusLogger.METADATA.warn( Localiser.msg("MetaData.AnnotationReaderNotFound", readerClassName)); return null; } } return reader.getMetaDataForClass(cls, pmd, clr); }
public <T> NetHandler(Class<T> clazz) { Annotation[] ass = clazz.getAnnotations(); if (ass != null) { for (Annotation annotation : ass) { if (annotation.annotationType() == FormUrlEncoded.class) { defaultRequestType = MethodInfo.RequestType.FORM_URL_ENCODED; } else if (annotation.annotationType() == Multipart.class) { defaultRequestType = MethodInfo.RequestType.MULTIPART; } } } }
public void testMethodPatternUsingMethodAnnotations() throws Exception { Class<?> foo = Foo.class.getClass(); ParameterInfo info = new ParameterInfo(1, foo.getClass(), foo.getAnnotations(), null); assertNotNull(info); assertNotNull(info.toString()); assertEquals(1, info.getIndex()); assertEquals(foo, info.getType()); assertNull(info.getExpression()); assertNotNull(info.getAnnotations()); }
private void addBind(Name moduleName, Class<?> buttonEvent, RegisterBindButton info) { List<Input> defaultInputs = Lists.newArrayList(); for (Annotation annotation : buttonEvent.getAnnotations()) { if (annotation instanceof DefaultBinding) { DefaultBinding defaultBinding = (DefaultBinding) annotation; Input input = defaultBinding.type().getInput(defaultBinding.id()); if (!data.values().contains(input)) { defaultInputs.add(input); } } } SimpleUri bindUri = new SimpleUri(moduleName, info.id()); setBinds(bindUri, defaultInputs.toArray(new Input[defaultInputs.size()])); }
/** * Get the <code>Secured</code> attributes for a given target class. * * @param target The target method * @return Collection of <code>SecurityConfig</code> * @see Attributes#getAttributes */ public Collection getAttributes(Class target) { Set<String> attributes = new HashSet<String>(); for (Annotation annotation : target.getAnnotations()) { // check for Secured annotations if (annotation instanceof Authorized) { Authorized attr = (Authorized) annotation; for (String privilege : attr.value()) { attributes.add(privilege); } break; } } return attributes; }
@SuppressWarnings("unchecked") private static void annotatedWith(Set<Class<?>> contracts, Class annotation, Class<?> clazz) { if (!Proxy.isProxyClass(clazz)) { Annotation[] annArr = clazz.getAnnotations(); for (Annotation ann : annArr) { Class<?> x = ann.annotationType(); Object t = x.getAnnotation(annotation); if (null != t) { contracts.add(clazz); return; } } } }