List of usage examples for java.lang Class isAnnotationPresent
@Override public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass)
From source file:org.springframework.test.context.TestContext.java
/** * Construct a new test context for the supplied {@linkplain Class test class} * and {@linkplain ContextCache context cache} and parse the corresponding * {@link ContextConfiguration @ContextConfiguration} or * {@link ContextHierarchy @ContextHierarchy} annotation, if present. * <p>If the supplied class name for the default {@code ContextLoader} * is {@code null} or <em>empty</em> and no concrete {@code ContextLoader} * class is explicitly supplied via {@code @ContextConfiguration}, a * {@link org.springframework.test.context.support.DelegatingSmartContextLoader * DelegatingSmartContextLoader} or// w w w .j ava 2s . co m * {@link org.springframework.test.context.web.WebDelegatingSmartContextLoader * WebDelegatingSmartContextLoader} will be used instead. * @param testClass the test class for which the test context should be * constructed (must not be {@code null}) * @param contextCache the context cache from which the constructed test * context should retrieve application contexts (must not be * {@code null}) * @param defaultContextLoaderClassName the name of the default * {@code ContextLoader} class to use (may be {@code null}) */ TestContext(Class<?> testClass, ContextCache contextCache, String defaultContextLoaderClassName) { Assert.notNull(testClass, "Test class must not be null"); Assert.notNull(contextCache, "ContextCache must not be null"); this.testClass = testClass; this.contextCache = contextCache; this.cacheAwareContextLoaderDelegate = new CacheAwareContextLoaderDelegate(contextCache); MergedContextConfiguration mergedContextConfiguration; if (testClass.isAnnotationPresent(ContextConfiguration.class) || testClass.isAnnotationPresent(ContextHierarchy.class)) { mergedContextConfiguration = ContextLoaderUtils.buildMergedContextConfiguration(testClass, defaultContextLoaderClassName, cacheAwareContextLoaderDelegate); } else { if (logger.isInfoEnabled()) { logger.info(String.format( "Neither @ContextConfiguration nor @ContextHierarchy found for test class [%s]", testClass.getName())); } mergedContextConfiguration = new MergedContextConfiguration(testClass, null, null, null, null); } this.mergedContextConfiguration = mergedContextConfiguration; }
From source file:org.apache.struts2.convention.DefaultClassFinder.java
public List<Class> findAnnotatedClasses(Class<? extends Annotation> annotation) { classesNotLoaded.clear();//from w ww.j a v a 2s .c om List<Class> classes = new ArrayList<>(); List<Info> infos = getAnnotationInfos(annotation.getName()); for (Info info : infos) { if (info instanceof ClassInfo) { ClassInfo classInfo = (ClassInfo) info; try { Class clazz = classInfo.get(); // double check via proper reflection if (clazz.isAnnotationPresent(annotation)) { classes.add(clazz); } } catch (Throwable e) { LOG.error("Error loading class [{}]", classInfo.getName(), e); classesNotLoaded.add(classInfo.getName()); } } } return classes; }
From source file:net.paoding.rose.web.impl.module.ModulesBuilderImpl.java
private boolean checkController(final XmlWebApplicationContext context, String beanName, ModuleImpl module) throws IllegalAccessException { AbstractBeanDefinition beanDefinition = (AbstractBeanDefinition) context.getBeanFactory() .getBeanDefinition(beanName); String beanClassName = beanDefinition.getBeanClassName(); String controllerSuffix = null; for (String suffix : RoseConstants.CONTROLLER_SUFFIXES) { if (beanClassName.length() > suffix.length() && beanClassName.endsWith(suffix)) { if (suffix.length() == 1 && Character .isUpperCase(beanClassName.charAt(beanClassName.length() - suffix.length() - 1))) { continue; }//ww w . j a v a 2 s. c o m controllerSuffix = suffix; break; } } if (controllerSuffix == null) { if (beanDefinition.hasBeanClass()) { Class<?> beanClass = beanDefinition.getBeanClass(); if (beanClass.isAnnotationPresent(Path.class)) { throw new IllegalArgumentException( "@" + Path.class.getSimpleName() + " is only allowed in Resource/Controller, " + "is it a Resource/Controller? wrong spelling? : " + beanClassName); } } // ?l?r?uer?or??? if (beanClassName.endsWith("Controler") || beanClassName.endsWith("Controllor") || beanClassName.endsWith("Resouce") || beanClassName.endsWith("Resorce")) { // ?throw??? logger.error("", new IllegalArgumentException( "invalid class name end wrong spelling? : " + beanClassName)); } return false; } String[] controllerPaths = null; if (!beanDefinition.hasBeanClass()) { try { beanDefinition.resolveBeanClass(Thread.currentThread().getContextClassLoader()); } catch (ClassNotFoundException e) { throw new CannotLoadBeanClassException("", beanName, beanDefinition.getBeanClassName(), e); } } final Class<?> clazz = beanDefinition.getBeanClass(); final String controllerName = StringUtils.removeEnd(ClassUtils.getShortNameAsProperty(clazz), controllerSuffix); Path reqMappingAnnotation = clazz.getAnnotation(Path.class); if (reqMappingAnnotation != null) { controllerPaths = reqMappingAnnotation.value(); } if (controllerPaths != null) { // controllerPaths.length==0path?controller for (int i = 0; i < controllerPaths.length; i++) { if ("#".equals(controllerPaths[i])) { controllerPaths[i] = "/" + controllerName; } else if (controllerPaths[i].equals("/")) { controllerPaths[i] = ""; } else if (controllerPaths[i].length() > 0 && controllerPaths[i].charAt(0) != '/') { controllerPaths[i] = "/" + controllerPaths[i]; } if (controllerPaths[i].length() > 1 && controllerPaths[i].endsWith("/")) { if (controllerPaths[i].endsWith("//")) { throw new IllegalArgumentException("invalid path '" + controllerPaths[i] + "' for controller " + beanClassName + ": don't end with more than one '/'"); } controllerPaths[i] = controllerPaths[i].substring(0, controllerPaths[i].length() - 1); } } } else { // TODO: ?0.91.0?201007?? if (controllerName.equals("index") || controllerName.equals("home") || controllerName.equals("welcome")) { // ??IndexController/HomeController/WelcomeController@Path("") throw new IllegalArgumentException("please add @Path(\"\") to " + clazz.getName()); } else { controllerPaths = new String[] { "/" + controllerName }; } } // Controller??Context?? // Context??? Object controller = context.getBean(beanName); module.addController(// controllerPaths, clazz, controllerName, controller); if (Proxy.isProxyClass(controller.getClass())) { if (logger.isDebugEnabled()) { logger.debug("module '" + module.getMappingPath() + "': add controller " + Arrays.toString(controllerPaths) + "= proxy of " + clazz.getName()); } } else { if (logger.isDebugEnabled()) { logger.debug("module '" + module.getMappingPath() // + "': add controller " + Arrays.toString(controllerPaths) + "= " + controller.getClass().getName()); } } return true; }
From source file:com.laxser.blitz.web.impl.module.ModulesBuilderImpl.java
private boolean checkController(final XmlWebApplicationContext context, String beanName, ModuleImpl module) throws IllegalAccessException { AbstractBeanDefinition beanDefinition = (AbstractBeanDefinition) context.getBeanFactory() .getBeanDefinition(beanName); String beanClassName = beanDefinition.getBeanClassName(); String controllerSuffix = null; for (String suffix : BlitzConstants.CONTROLLER_SUFFIXES) { if (beanClassName.length() > suffix.length() && beanClassName.endsWith(suffix)) { if (suffix.length() == 1 && Character .isUpperCase(beanClassName.charAt(beanClassName.length() - suffix.length() - 1))) { continue; }/*from ww w. j a v a 2 s. c o m*/ controllerSuffix = suffix; break; } } if (controllerSuffix == null) { if (beanDefinition.hasBeanClass()) { Class<?> beanClass = beanDefinition.getBeanClass(); if (beanClass.isAnnotationPresent(Path.class)) { throw new IllegalArgumentException( "@" + Path.class.getSimpleName() + " is only allowed in Resource/Controller, " + "is it a Resource/Controller? wrong spelling? : " + beanClassName); } } // ?l?r?uer?or??? if (beanClassName.endsWith("Controler") || beanClassName.endsWith("Controllor") || beanClassName.endsWith("Resouce") || beanClassName.endsWith("Resorce")) { // ?throw??? logger.error("", new IllegalArgumentException( "invalid class name end wrong spelling? : " + beanClassName)); } return false; } String[] controllerPaths = null; if (!beanDefinition.hasBeanClass()) { try { beanDefinition.resolveBeanClass(Thread.currentThread().getContextClassLoader()); } catch (ClassNotFoundException e) { throw new CannotLoadBeanClassException("", beanName, beanDefinition.getBeanClassName(), e); } } final Class<?> clazz = beanDefinition.getBeanClass(); final String controllerName = StringUtils.removeEnd(ClassUtils.getShortNameAsProperty(clazz), controllerSuffix); Path reqMappingAnnotation = clazz.getAnnotation(Path.class); if (reqMappingAnnotation != null) { controllerPaths = reqMappingAnnotation.value(); } if (controllerPaths != null) { // controllerPaths.length==0path?controller for (int i = 0; i < controllerPaths.length; i++) { if ("#".equals(controllerPaths[i])) { controllerPaths[i] = "/" + controllerName; } else if (controllerPaths[i].equals("/")) { controllerPaths[i] = ""; } else if (controllerPaths[i].length() > 0 && controllerPaths[i].charAt(0) != '/') { controllerPaths[i] = "/" + controllerPaths[i]; } if (controllerPaths[i].length() > 1 && controllerPaths[i].endsWith("/")) { if (controllerPaths[i].endsWith("//")) { throw new IllegalArgumentException("invalid path '" + controllerPaths[i] + "' for controller " + beanClassName + ": don't end with more than one '/'"); } controllerPaths[i] = controllerPaths[i].substring(0, controllerPaths[i].length() - 1); } } } else { // TODO: ?0.91.0?201007?? if (controllerName.equals("index") || controllerName.equals("home") || controllerName.equals("welcome")) { // ??IndexController/HomeController/WelcomeController@Path("") throw new IllegalArgumentException("please add @Path(\"\") to " + clazz.getName()); } else { controllerPaths = new String[] { "/" + controllerName }; } } // Controller??Context?? // Context??? Object controller = context.getBean(beanName); module.addController(// controllerPaths, clazz, controllerName, controller); if (Proxy.isProxyClass(controller.getClass())) { if (logger.isDebugEnabled()) { logger.debug("module '" + module.getMappingPath() + "': add controller " + Arrays.toString(controllerPaths) + "= proxy of " + clazz.getName()); } } else { if (logger.isDebugEnabled()) { logger.debug("module '" + module.getMappingPath() // + "': add controller " + Arrays.toString(controllerPaths) + "= " + controller.getClass().getName()); } } return true; }
From source file:com.vmware.photon.controller.swagger.resources.SwaggerJsonListing.java
/** * This outputs the json that contains a list of all resources that are documented, * and the paths for getting their documentation. * * @return SwaggerResourceListings The API representation for the master list of documented resources. */// w w w. ja va 2 s .com @GET public SwaggerResourceListings getSwaggerResourceListings() { synchronized (resourceListingsLock) { if (resourceListings != null) { return resourceListings; } } SwaggerResourceListings listings = new SwaggerResourceListings(); listings.setBasePath(""); listings.setApiVersion(this.apiVersion); listings.setSwaggerVersion(this.swaggerVersion); List<SwaggerResourceListingPath> apis = new ArrayList<>(); Set<String> apiValues = new HashSet<>(); for (Class<?> resource : resources) { if (resource.isAnnotationPresent(Api.class)) { SwaggerResourceListingPath swaggerResourcePath = new SwaggerResourceListingPath(); Api api = resource.getAnnotation(Api.class); if (!apiValues.contains(api.value())) { swaggerResourcePath .setPath(UriBuilder.fromPath(SWAGGER_PATH).path(api.value()).build().toString()); apis.add(swaggerResourcePath); apiValues.add(api.value()); } } } listings.setApis(apis); synchronized (resourceListingsLock) { resourceListings = listings; } return listings; }
From source file:cz.jirutka.validator.collection.CommonEachValidator.java
public void initialize(Annotation eachAnnotation) { Class<? extends Annotation> eachAType = eachAnnotation.annotationType(); LOG.trace("Initializing CommonEachValidator for {}", eachAType); if (factory == null) { LOG.debug("No ValidatorFactory injected, building default one"); factory = Validation.buildDefaultValidatorFactory(); }/*from w w w. j a v a2s .co m*/ validatorInstances = new ConcurrentHashMap<>(2); if (eachAType.isAnnotationPresent(EachConstraint.class)) { Class constraintClass = eachAType.getAnnotation(EachConstraint.class).validateAs(); Annotation constraint = createConstraintAndCopyAttributes(constraintClass, eachAnnotation); ConstraintDescriptor descriptor = createConstraintDescriptor(constraint); descriptors = unmodifiableList(asList(descriptor)); // legacy } else if (isWrapperAnnotation(eachAType)) { Annotation[] constraints = unwrapConstraints(eachAnnotation); Validate.notEmpty(constraints, "%s annotation does not contain any constraint", eachAType); List<ConstraintDescriptor> list = new ArrayList<>(constraints.length); for (Annotation constraint : constraints) { list.add(createConstraintDescriptor(constraint)); } descriptors = unmodifiableList(list); this.earlyInterpolate = true; } else { throw new IllegalArgumentException(String.format( "%s is not annotated with @EachConstraint and doesn't declare 'value' of type Annotation[] either.", eachAType.getName())); } // constraints are always of the same type, so just pick first ConstraintDescriptor descriptor = descriptors.get(0); validators = categorizeValidatorsByType(descriptor.getConstraintValidatorClasses()); Validate.notEmpty(validators, "No validator found for constraint: %s", descriptor.getAnnotation().annotationType()); }
From source file:org.b3log.latke.servlet.handler.AdviceHandler.java
/** * get AfterRequestProcessAdvice from annotation. * * @param invokeHolder the real invoked method * @param processorClass the class of the invoked methond * @return the list of AfterRequestProcessAdvice *//*from w w w . j av a2 s.co m*/ private List<Class<? extends AfterRequestProcessAdvice>> getAfterList(final Method invokeHolder, final Class<?> processorClass) { // after invoke(first method before advice and then class before advice). final List<Class<? extends AfterRequestProcessAdvice>> afterAdviceClassList = new ArrayList<Class<? extends AfterRequestProcessAdvice>>(); if (invokeHolder.isAnnotationPresent(After.class)) { final Class<? extends AfterRequestProcessAdvice>[] ac = invokeHolder.getAnnotation(After.class) .adviceClass(); afterAdviceClassList.addAll(Arrays.asList(ac)); } if (processorClass.isAnnotationPresent(After.class)) { final Class<? extends AfterRequestProcessAdvice>[] ac = processorClass.getAnnotation(After.class) .adviceClass(); afterAdviceClassList.addAll(Arrays.asList(ac)); } return afterAdviceClassList; }
From source file:org.apache.metron.common.stellar.StellarTest.java
@Test public void ensureDocumentation() { ClassLoader classLoader = getClass().getClassLoader(); int numFound = 0; for (Class<?> clazz : new ClasspathFunctionResolver().resolvables()) { if (clazz.isAnnotationPresent(Stellar.class)) { numFound++;//from w ww . j a v a 2s. c o m Stellar annotation = clazz.getAnnotation(Stellar.class); Assert.assertFalse("Must specify a name for " + clazz.getName(), StringUtils.isEmpty(annotation.name())); Assert.assertFalse("Must specify a description annotation for " + clazz.getName(), StringUtils.isEmpty(annotation.description())); Assert.assertTrue("Must specify a non-empty params for " + clazz.getName(), annotation.params().length > 0); Assert.assertTrue("Must specify a non-empty params for " + clazz.getName(), StringUtils.isNoneEmpty(annotation.params())); Assert.assertFalse("Must specify a returns annotation for " + clazz.getName(), StringUtils.isEmpty(annotation.returns())); } } Assert.assertTrue(numFound > 0); }
From source file:de.xaniox.heavyspleef.core.flag.FlagManager.java
public void disableFlag(Class<? extends AbstractFlag<?>> clazz) { AbstractFlag<?> flag = getFlag(clazz); Validate.notNull(flag, "Flag is not registered or already disabled"); String path = flags.inverse().remove(flag); if (clazz.isAnnotationPresent(BukkitListener.class)) { HandlerList.unregisterAll(flag); }/*from w w w. j a v a2 s . c o m*/ Iterator<GamePropertyBundle> iterator = propertyBundles.iterator(); while (iterator.hasNext()) { GamePropertyBundle bundle = iterator.next(); if (bundle.getRelatingFlag() == null || bundle.getRelatingFlag() != flag) { continue; } iterator.remove(); } disabledFlags.add(path); }
From source file:net.firejack.platform.core.utils.Factory.java
private <T> T convertFrom0(Class<?> clazz, Object dto) { if (dto == null) return null; Object bean = null;/*from w ww . ja va 2 s . c o m*/ try { bean = clazz.newInstance(); List<FieldInfo> infos = fields.get(dto.getClass()); if (infos == null) { infos = getAllField(dto.getClass(), dto.getClass(), new ArrayList<FieldInfo>()); fields.put(dto.getClass(), infos); } for (FieldInfo info : infos) { if (info.readonly()) { continue; } String name = info.name(); Object entity = bean; clazz = entity.getClass(); String[] lookup = name.split("\\."); if (lookup.length > 1) { if (isNullValue(dto, info.getField().getName())) continue; for (int i = 0; i < lookup.length - 1; i++) { Object instance = get(entity, lookup[i], null); if (instance == null) { FieldInfo fieldInfo = getField(clazz, lookup[i]); Class<?> type = fieldInfo.getType(); if (!type.isInterface() && !Modifier.isAbstract(type.getModifiers())) { instance = type.newInstance(); set(entity, lookup[i], instance); entity = instance; clazz = type; } } else { entity = instance; clazz = instance.getClass(); } } name = lookup[lookup.length - 1]; } FieldInfo distField = getField(clazz, name); if (distField != null) { Class<?> type = distField.getType(); Object value = get(dto, info.getField().getName(), type); if (value != null) { if (value instanceof AbstractDTO) { if (contains(value)) { Object convert = get(value); set(entity, name, convert); } else { add(value, null); Object convert = convertFrom0(type, value); add(value, convert); set(entity, name, convert); } } else if (value instanceof Collection) { Collection result = (Collection) value; Class<?> arrayType = distField.getGenericType(); if (AbstractModel.class.isAssignableFrom(arrayType) || arrayType.isAnnotationPresent(XmlAccessorType.class)) { try { result = (Collection) value.getClass().newInstance(); } catch (InstantiationException e) { result = new ArrayList(); } for (Object o : (Collection) value) { Object convert = convertFrom0(arrayType, o); result.add(convert); } } set(entity, name, result); } else { set(entity, name, value); } } } } } catch (Exception e) { logger.warn(e.getMessage()); } return (T) bean; }