List of usage examples for java.lang.reflect Method getAnnotation
public <T extends Annotation> T getAnnotation(Class<T> annotationClass)
From source file:com.facebook.config.ConfigAccessor.java
public <T> T getBean(String key, Class<? extends ExtractableBeanBuilder<T>> beanBuilderClass) { try {/*from ww w .j a v a 2s .c o m*/ JSONObject jsonBean = get(key, null, new JSONObjectExtractor()); ConfigAccessor jsonBeanAccessor = new ConfigAccessor(jsonBean); Object beanBuilder = beanBuilderClass.newInstance(); for (Method m : beanBuilderClass.getMethods()) { if (m.getName().toLowerCase().startsWith("set")) { FieldExtractor extractor = m.getAnnotation(FieldExtractor.class); if (extractor != null) { if (!Extractor.class.isAssignableFrom(extractor.extractorClass())) { String message = String.format("extractor %s does not extend Extractor.class", extractor); LOG.error(message); throw new ConfigException(message); } // if the parameter isn't optional check, or if it's optional // and it is present; ie, if it's not optional and not there, let // get() throw a ConfigException if (!extractor.optional() || jsonBeanAccessor.hasKey(extractor.key())) { Object value = jsonBeanAccessor.get(extractor.key(), null, (Extractor) extractor.extractorClass().newInstance()); m.invoke(beanBuilder, value); } } else { LOG.warn("unable to find annotation for setter method " + m.getName()); } } } return ((ExtractableBeanBuilder<T>) beanBuilder).build(); } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { throw new ConfigException(e); } }
From source file:com.github.kongchen.swagger.docgen.mavenplugin.SpringMavenDocumentSource.java
@Override public void loadDocuments() throws GenerateException { Map<String, SpringResource> resourceMap = new HashMap<String, SpringResource>(); SwaggerConfig swaggerConfig = new SwaggerConfig(); swaggerConfig.setApiVersion(apiSource.getApiVersion()); swaggerConfig.setSwaggerVersion(SwaggerSpec.version()); List<ApiListingReference> apiListingReferences = new ArrayList<ApiListingReference>(); List<AuthorizationType> authorizationTypes = new ArrayList<AuthorizationType>(); //relate all methods to one base request mapping if multiple controllers exist for that mapping //get all methods from each controller & find their request mapping //create map - resource string (after first slash) as key, new SpringResource as value for (Class<?> c : apiSource.getValidClasses()) { RequestMapping requestMapping = (RequestMapping) c.getAnnotation(RequestMapping.class); String description = ""; if (c.isAnnotationPresent(Api.class)) { description = ((Api) c.getAnnotation(Api.class)).value(); }/*from ww w . jav a 2s . c o m*/ if (requestMapping != null && requestMapping.value().length != 0) { //This try/catch block is to stop a bamboo build from failing due to NoClassDefFoundError //This occurs when a class or method loaded by reflections contains a type that has no dependency try { resourceMap = analyzeController(c, resourceMap, description); List<Method> mList = new ArrayList<Method>(Arrays.asList(c.getMethods())); if (c.getSuperclass() != null) { mList.addAll(Arrays.asList(c.getSuperclass().getMethods())); } for (Method m : mList) { if (m.isAnnotationPresent(RequestMapping.class)) { RequestMapping methodReq = m.getAnnotation(RequestMapping.class); //isolate resource name - attempt first by the first part of the mapping if (methodReq != null && methodReq.value().length != 0) { for (int i = 0; i < methodReq.value().length; i++) { String resourceKey = ""; String resourceName = Utils.parseResourceName(methodReq.value()[i]); if (!(resourceName.equals(""))) { String version = Utils.parseVersion(requestMapping.value()[0]); //get version - first try by class mapping, then method if (version.equals("")) { //class mapping failed - use method version = Utils.parseVersion(methodReq.value()[i]); } resourceKey = Utils.createResourceKey(resourceName, version); if ((!(resourceMap.containsKey(resourceKey)))) { resourceMap.put(resourceKey, new SpringResource(c, resourceName, resourceKey, description)); } resourceMap.get(resourceKey).addMethod(m); } } } } } } catch (NoClassDefFoundError e) { LOG.error(e.getMessage()); LOG.info(c.getName()); //exception occurs when a method type or annotation is not recognized by the plugin } catch (ClassNotFoundException e) { LOG.error(e.getMessage()); LOG.info(c.getName()); } } } for (String str : resourceMap.keySet()) { ApiListing doc = null; SpringResource resource = resourceMap.get(str); try { doc = getDocFromSpringResource(resource, swaggerConfig); setBasePath(doc.basePath()); } catch (Exception e) { LOG.error("DOC NOT GENERATED FOR: " + resource.getResourceName()); e.printStackTrace(); } if (doc == null) continue; ApiListingReference apiListingReference = new ApiListingReference(doc.resourcePath(), doc.description(), doc.position()); apiListingReferences.add(apiListingReference); acceptDocument(doc); } // sort apiListingRefernce by position Collections.sort(apiListingReferences, new Comparator<ApiListingReference>() { @Override public int compare(ApiListingReference o1, ApiListingReference o2) { if (o1 == null && o2 == null) return 0; if (o1 == null && o2 != null) return -1; if (o1 != null && o2 == null) return 1; return o1.position() - o2.position(); } }); serviceDocument = new ResourceListing(swaggerConfig.apiVersion(), swaggerConfig.swaggerVersion(), scala.collection.immutable.List .fromIterator(JavaConversions.asScalaIterator(apiListingReferences.iterator())), scala.collection.immutable.List.fromIterator( JavaConversions.asScalaIterator(authorizationTypes.iterator())), swaggerConfig.info()); }
From source file:com.haulmont.cuba.core.config.AppPropertiesLocator.java
protected TypeStringify getTypeStringify(Method method) { try {//ww w . j a v a 2 s . c om Stringify stringifyAnn = method.getAnnotation(Stringify.class); if (stringifyAnn != null) { if ("".equals(stringifyAnn.method())) { return stringifyAnn.stringify().newInstance(); } else { String methodName = stringifyAnn.method(); return new MethodTypeStringify(method.getReturnType().getMethod(methodName)); } } Factory factoryAnn = method.getAnnotation(Factory.class); if (factoryAnn != null) { TypeStringify typeStringify = getTypeStringifyForFactory(factoryAnn.factory()); if (typeStringify != null) return typeStringify; } if (Date.class.isAssignableFrom(method.getReturnType())) { return new DateStringify(); } if (Entity.class.isAssignableFrom(method.getReturnType())) { return new EntityStringify(); } if (EnumClass.class.isAssignableFrom(method.getReturnType())) { EnumStore mode = method.getAnnotation(EnumStore.class); if (mode != null && EnumStoreMode.ID == mode.value()) { @SuppressWarnings("unchecked") Class<EnumClass> enumeration = (Class<EnumClass>) method.getReturnType(); TypeStringify idStringify = TypeStringify.getInferred(ConfigUtil.getEnumIdType(enumeration)); return new EnumClassStringify(idStringify); } } return TypeStringify.getInferred(method.getReturnType()); } catch (Exception e) { log.warn("Error getting TypeStringify: " + e); return new PrimitiveTypeStringify(); } }
From source file:de.escalon.hypermedia.hydra.serialize.JacksonHydraSerializer.java
private Map<String, Object> getTerms(Object bean, Class<?> mixInClass) throws IntrospectionException, IllegalAccessException, NoSuchFieldException { // define terms from package or type in context final Class<?> beanClass = bean.getClass(); Map<String, Object> termsMap = getAnnotatedTerms(beanClass.getPackage(), beanClass.getPackage().getName()); Map<String, Object> classTermsMap = getAnnotatedTerms(beanClass, beanClass.getName()); Map<String, Object> mixinTermsMap = getAnnotatedTerms(mixInClass, beanClass.getName()); // class terms override package terms termsMap.putAll(classTermsMap);/* ww w . j a va 2 s .c o m*/ // mixin terms override class terms termsMap.putAll(mixinTermsMap); final Field[] fields = beanClass.getDeclaredFields(); for (Field field : fields) { final Expose fieldExpose = field.getAnnotation(Expose.class); if (Enum.class.isAssignableFrom(field.getType())) { Map<String, String> map = new LinkedHashMap<String, String>(); termsMap.put(field.getName(), map); if (fieldExpose != null) { map.put(AT_ID, fieldExpose.value()); } map.put(AT_TYPE, AT_VOCAB); final Enum value = (Enum) field.get(bean); final Expose enumValueExpose = getAnnotation(value.getClass().getField(value.name()), Expose.class); // TODO redefine actual enum value to exposed on enum value definition if (enumValueExpose != null) { termsMap.put(value.toString(), enumValueExpose.value()); } else { // might use upperToCamelCase if nothing is exposed final String camelCaseEnumValue = WordUtils .capitalizeFully(value.toString(), new char[] { '_' }).replaceAll("_", ""); termsMap.put(value.toString(), camelCaseEnumValue); } } else { if (fieldExpose != null) { termsMap.put(field.getName(), fieldExpose.value()); } } } // TODO do this recursively for nested beans and collect as long as // nested beans have same vocab // expose getters in context final BeanInfo beanInfo = Introspector.getBeanInfo(beanClass); final PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { final Method method = propertyDescriptor.getReadMethod(); final Expose expose = method.getAnnotation(Expose.class); if (expose != null) { termsMap.put(propertyDescriptor.getName(), expose.value()); } } return termsMap; }
From source file:org.geoserver.wps.jts.SpringBeanProcessFactory.java
@Override protected Method method(String className) { Class c = classMap.get(className); Method lastExecute = null;/* w w w. ja va2 s. c o m*/ if (c != null) { for (Method m : c.getMethods()) { if (m.getName().equals("execute")) { if (lastExecute != null) { lastExecute = m; } // if annotated return immediately, otherwise keep it aside if (m.getAnnotation(DescribeResult.class) != null || m.getAnnotation(DescribeResults.class) != null) { return m; } } } } return lastExecute; }
From source file:com.googlecode.jdbcproc.daofactory.impl.block.service.ResultSetConverterBlockServiceImpl.java
/** * Gets table prefix from @JoinColumn.name() * @param method getter method with OneToOne annotation and possibly JoinColumn * @return @JoinColumn.name() + "_" or empty string ("") *///from www . j a v a 2 s . com private String getTablePrefixFromJoinColumnAnnotation(Method method) { String name = ""; if (method.isAnnotationPresent(JoinColumn.class)) { JoinColumn joinColumn = method.getAnnotation(JoinColumn.class); if (StringUtils.hasText(joinColumn.table())) { name = joinColumn.table() + "_"; } } return name; }
From source file:org.flite.cach3.aop.L2UpdateMultiCacheAdvice.java
private void doUpdate(final JoinPoint jp, final Object retVal) throws Throwable { if (isCacheDisabled()) { LOG.debug("Caching is disabled."); return;/*from w w w.j a va2 s .com*/ } final Method methodToCache = getMethodToCache(jp); List<L2UpdateMultiCache> lAnnotations; // if (methodToCache.getAnnotation(L2UpdateMultiCache.class) != null) { lAnnotations = Arrays.asList(methodToCache.getAnnotation(L2UpdateMultiCache.class)); // } else { // lAnnotations = Arrays.asList(); // lAnnotations = Arrays.asList(methodToCache.getAnnotation(L2UpdateMultiCaches.class).value()); // } for (int i = 0; i < lAnnotations.size(); i++) { try { // This is injected caching. If anything goes wrong in the caching, LOG the crap outta it, // but do not let it surface up past the AOP injection itself. final AnnotationInfo info = getAnnotationInfo(lAnnotations.get(i), methodToCache.getName()); final List<Object> dataList = (List<Object>) UpdateMultiCacheAdvice.getIndexObject( info.getAsInteger(AType.DATA_INDEX), retVal, jp.getArgs(), methodToCache.toString()); final List<Object> keyObjects = UpdateMultiCacheAdvice .getKeyObjects(info.getAsInteger(AType.KEY_INDEX), retVal, jp, methodToCache); final List<String> baseKeys = UpdateMultiCacheAdvice.getBaseKeys(keyObjects, info.getAsString(AType.KEY_TEMPLATE, null), retVal, jp.getArgs(), factory, methodStore); final List<String> cacheKeys = new ArrayList<String>(baseKeys.size()); for (final String base : baseKeys) { cacheKeys.add(buildCacheKey(base, info.getAsString(AType.NAMESPACE, null), info.getAsString(AType.KEY_PREFIX, null))); } updateCache(cacheKeys, dataList, methodToCache, info.<Duration>getAsType(AType.WINDOW, null), getCache()); } catch (Exception ex) { if (LOG.isDebugEnabled()) { LOG.warn("Caching on " + jp.toShortString() + " aborted due to an error.", ex); } else { LOG.warn("Caching on " + jp.toShortString() + " aborted due to an error: " + ex.getMessage()); } } } }
From source file:com.consol.citrus.admin.service.TestCaseServiceImpl.java
/** * Finds all Citrus annotated test methods in test class. Do only return methods when more than one test method * is found. Otherwise use class itself as test representation. * @param testClass/*from w w w . j a v a2s .c om*/ * @return */ private List<String> getTestMethods(Class<?> testClass) { List<String> methodNames = new ArrayList<String>(); for (Method method : ReflectionUtils.getAllDeclaredMethods(testClass)) { if (method.getAnnotation(CitrusTest.class) != null) { CitrusTest citrusAnnotation = method.getAnnotation(CitrusTest.class); if (StringUtils.hasText(citrusAnnotation.name())) { methodNames.add(citrusAnnotation.name()); } else { // use default method name as test methodNames.add(method.getName()); } } } return methodNames; }
From source file:net.sourceforge.vulcan.spring.SpringBeanXmlEncoder.java
void encodeBean(Element root, String beanName, Object bean) { final BeanWrapper bw = new BeanWrapperImpl(bean); final PropertyDescriptor[] pds = bw.getPropertyDescriptors(); final Element beanNode = new Element("bean"); root.addContent(beanNode);/* w w w . ja v a 2 s. c o m*/ if (beanName != null) { beanNode.setAttribute("name", beanName); } if (factoryExpert.needsFactory(bean)) { encodeBeanByFactory(beanNode, bean); } else { beanNode.setAttribute("class", bean.getClass().getName()); } for (PropertyDescriptor pd : pds) { if (pd.getWriteMethod() == null) continue; final Method readMethod = pd.getReadMethod(); if (readMethod == null) continue; if (readMethod.getAnnotation(Transient.class) != null) { continue; } final String name = pd.getName(); final Object value = bw.getPropertyValue(name); if (value == null) continue; final Element propertyNode = new Element("property"); propertyNode.setAttribute("name", name); beanNode.addContent(propertyNode); encodeObject(propertyNode, value); } }
From source file:cn.webwheel.ActionSetter.java
public List<SetterInfo> parseSetters(Class cls) { List<SetterInfo> list = new ArrayList<SetterInfo>(); Field[] fields = cls.getFields(); for (int i = fields.length - 1; i >= 0; i--) { Field field = fields[i];//from w ww .ja v a 2 s.c om if (Modifier.isFinal(field.getModifiers())) continue; if (Modifier.isStatic(field.getModifiers())) continue; WebParam param = field.getAnnotation(WebParam.class); String name = field.getName(); if (field.getType().isArray()) name += "[]"; if (param != null && !param.value().isEmpty()) name = param.value(); SetterInfo si = getSetterInfo(field, name); if (si == null) { if (param != null) { logger.severe("wrong WebParam used at " + field); } continue; } list.add(si); } Method[] methods = cls.getMethods(); for (int i = methods.length - 1; i >= 0; i--) { Method method = methods[i]; WebParam param = method.getAnnotation(WebParam.class); String name = isSetter(method); if (name == null) { continue; } if (method.getParameterTypes()[0].isArray()) { name += "[]"; } if (param != null && !param.value().isEmpty()) { name = param.value(); } SetterInfo si = getSetterInfo(method, name); if (si == null) { if (param != null) { logger.severe("wrong WebParam used at " + method); } continue; } list.add(si); } return list; }