public String getValueFrom(Annotation annotation) { return (String) (attributeName == null ? AnnotationUtils.getValue(annotation) : AnnotationUtils.getValue(annotation, attributeName)); }
/** * Returns whether the given {@code propertyPathModel} requires the creation of a join. This is * the case if we find a non-optional association. * * @param propertyPathModel must not be {@literal null}. * @return */ private static boolean requiresJoin(Bindable<?> propertyPathModel) { if (!(propertyPathModel instanceof Attribute)) { return false; } Attribute<?, ?> attribute = (Attribute<?, ?>) propertyPathModel; if (!ASSOCIATION_TYPES.containsKey(attribute.getPersistentAttributeType())) { return false; } Class<? extends Annotation> associationAnnotation = ASSOCIATION_TYPES.get(attribute.getPersistentAttributeType()); if (associationAnnotation == null) { return false; } Member member = attribute.getJavaMember(); if (!(member instanceof AnnotatedElement)) { return true; } Annotation annotation = AnnotationUtils.getAnnotation((AnnotatedElement) member, associationAnnotation); return annotation == null ? true : (Boolean) AnnotationUtils.getValue(annotation, "optional"); }
private boolean isHypermediaDisabled(MethodParameter returnType) { return AnnotationUtils.findAnnotation(returnType.getMethod(), HypermediaDisabled.class) != null || AnnotationUtils.findAnnotation( returnType.getMethod().getDeclaringClass(), HypermediaDisabled.class) != null; }
public int compareTo(ClassAnnotationsLoader o) { Order order1 = AnnotationUtils.findAnnotation(getClass(), Order.class); Order order2 = AnnotationUtils.findAnnotation(o.getClass(), Order.class); int order1Value = order1 != null ? order1.value() : Ordered.LOWEST_PRECEDENCE; int order2Value = order2 != null ? order2.value() : Ordered.LOWEST_PRECEDENCE; return order1Value - order2Value; }
public String getValueFrom(AnnotatedElement annotatedElement) { Annotation annotation = annotatedElement.getAnnotation(annotationType); return (String) (attributeName == null ? AnnotationUtils.getValue(annotation) : AnnotationUtils.getValue(annotation, attributeName)); }
/** * Finds the property name that is used as the unique id. * * @param Method uniqueIdMethod * @return String the property name that is used as the unique id. */ public static String findUniqueIdName(Method uniqueIdMethod) { Annotation annot = AnnotationUtils.findAnnotation(uniqueIdMethod, UniqueId.class); if (annot != null) { Map<String, Object> annotAttribs = AnnotationUtils.getAnnotationAttributes(annot); String uniqueIdName = String.valueOf(annotAttribs.get("name")); return uniqueIdName; } return UniqueId.UNIQUE_NAME; }
private <T extends Annotation> Collection<T> getAnnotations( DbUnitTestContext testContext, Class<T> annotationType) { List<T> annotations = new ArrayList<T>(); addAnnotationToList( annotations, AnnotationUtils.findAnnotation(testContext.getTestClass(), annotationType)); addAnnotationToList( annotations, AnnotationUtils.findAnnotation(testContext.getTestMethod(), annotationType)); return annotations; }
/* (non-Javadoc) * @see org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#getCustomTypeCondition(java.lang.Class) */ @Override protected RequestCondition<?> getCustomTypeCondition(Class<?> handlerType) { BPCAPIVersion apiVersion = AnnotationUtils.findAnnotation(handlerType, BPCAPIVersion.class); if (apiVersion != null) return new BPCAPIVersionCondition(apiVersion); BPCMethod bpcMethod = AnnotationUtils.findAnnotation(handlerType, BPCMethod.class); if (bpcMethod != null) return new BPCMethodCondition(bpcMethod); return null; }
@Override protected HandlerMethod lookupHandlerMethod(String lookupPath, HttpServletRequest request) throws Exception { ReqInfoImpl req = new ReqInfoImpl(request, lookupPath); LogInfoImpl.getLogInfo(request, null).setReqInfo(req); HandlerMethod hm = super.lookupHandlerMethod(lookupPath, request); if (hm == null) return null; Class<?> clz = null; if (!classMap.containsKey(hm)) { clz = hm.getBeanType(); Winlet winlet = AnnotationUtils.findAnnotation(clz, Winlet.class); if (winlet == null) clz = null; classMap.put(hm, clz); } else clz = classMap.get(hm); if (clz != null) { // This is a Winlet if (req.getActionId() == null) { // 没有指定Action Window annotation = AnnotationUtils.findAnnotation(hm.getMethod(), Window.class); if (annotation == null) // 不是@Window方法 return hm; WinletDef def = WinletDef.getDef(clz); Object winlet = WinletManager.getWinlet(Context.get(), def); req.setWinlet(def, winlet); return new HandlerMethod(winlet, def.getWindow(annotation.value()).getMethod()); } else { int idx = req.getActionId().indexOf("."); if (idx > 0) { String winlet = req.getActionId().substring(0, idx); String action = req.getActionId().substring(idx + 1); WinletDef def = WinletDef.getDef(WinletClassLoader.getWinletClassByPath(winlet)); Object w = WinletManager.getWinlet(Context.get(), def); req.setWinlet(def, w); return new HandlerMethod(w, def.getAction(action).getMethod()); } else { WinletDef def = WinletDef.getDef(clz); Object w = WinletManager.getWinlet(Context.get(), def); req.setWinlet(def, w); ActionDef action = def.getAction(req.getActionId()); return new HandlerMethod(w, action.getMethod()); } } } return hm; }
protected List<DbUnitDataset> collectDatasetAnnotations(final Method testMethod) { final List<DbUnitDataset> datasetsAnnotations = new ArrayList<DbUnitDataset>(); final DbUnitDataset methodDataset = AnnotationUtils.findAnnotation(testMethod, DbUnitDataset.class); if (methodDataset != null) { datasetsAnnotations.add(methodDataset); } final DbUnitDataset classDataset = AnnotationUtils.findAnnotation(testMethod.getDeclaringClass(), DbUnitDataset.class); if (classDataset != null) { datasetsAnnotations.add(classDataset); } return datasetsAnnotations; }
/** * Validate the model attribute if applicable. * * <p>The default implementation checks for {@code @javax.validation.Valid}. * * @param binder the DataBinder to be used * @param parameter the method parameter */ protected void validateIfApplicable(WebDataBinder binder, MethodParameter parameter) { Annotation[] annotations = parameter.getParameterAnnotations(); for (Annotation ann : annotations) { Validated validatedAnn = AnnotationUtils.getAnnotation(ann, Validated.class); if (validatedAnn != null || ann.annotationType().getSimpleName().startsWith("Valid")) { Object hints = (validatedAnn != null ? validatedAnn.value() : AnnotationUtils.getValue(ann)); Object[] validationHints = (hints instanceof Object[] ? (Object[]) hints : new Object[] {hints}); binder.validate(validationHints); break; } } }
/** * Inspects the annotated resource to understand its capabilities * * @param resource */ @SuppressWarnings("rawtypes") public static List<ResourceMetadata> inspect(Class resource) { EntityResource annot = AnnotationUtils.findAnnotation(resource, EntityResource.class); if (annot != null) { return inspectEntity(annot, resource); } RelationshipResource relAnnot = AnnotationUtils.findAnnotation(resource, RelationshipResource.class); if (relAnnot != null) { return inspectRelationship(relAnnot, resource); } throw new UnsupportedOperationException("Unable to inspect " + resource.getName()); }
public Map<String, Object> getAnnotationAttributes( String annotationType, boolean classValuesAsString) { Annotation[] anns = getIntrospectedClass().getAnnotations(); for (Annotation ann : anns) { if (ann.annotationType().getName().equals(annotationType)) { return AnnotationUtils.getAnnotationAttributes(ann, classValuesAsString); } for (Annotation metaAnn : ann.annotationType().getAnnotations()) { if (metaAnn.annotationType().getName().equals(annotationType)) { return AnnotationUtils.getAnnotationAttributes(metaAnn, classValuesAsString); } } } return null; }
/** * Returns whether the given repository interface is a candidate for bean definition creation in * the strict repository detection mode. The default implementation inspects the domain type * managed for a set of well-known annotations (see {@link #getIdentifyingAnnotations()}). If none * of them is found, the candidate is discarded. Implementations should make sure, the only return * {@literal true} if they're really sure the interface handed to the method is really a store * interface. * * @param repositoryInterface * @return * @since 1.9 */ protected boolean isStrictRepositoryCandidate(Class<?> repositoryInterface) { RepositoryMetadata metadata = AbstractRepositoryMetadata.getMetadata(repositoryInterface); Collection<Class<?>> types = getIdentifyingTypes(); for (Class<?> type : types) { if (type.isAssignableFrom(repositoryInterface)) { return true; } } Class<?> domainType = metadata.getDomainType(); Collection<Class<? extends Annotation>> annotations = getIdentifyingAnnotations(); if (annotations.isEmpty()) { return true; } for (Class<? extends Annotation> annotationType : annotations) { if (AnnotationUtils.findAnnotation(domainType, annotationType) != null) { return true; } } LOGGER.debug(MULTI_STORE_DROPPED, getModuleName(), repositoryInterface); return false; }
private void setHostFromAnnotation() { for (Class<?> aClass : getValidClasses(SwaggerDefinition.class)) { SwaggerDefinition swaggerDefinition = AnnotationUtils.findAnnotation(aClass, SwaggerDefinition.class); host = swaggerDefinition.host(); } }
private void setBasePathFromAnnotation() { for (Class<?> aClass : getValidClasses(SwaggerDefinition.class)) { SwaggerDefinition swaggerDefinition = AnnotationUtils.findAnnotation(aClass, SwaggerDefinition.class); basePath = swaggerDefinition.basePath(); } }
/** Extract the value attribute from the given annotation. */ protected Object extractValue(Annotation valueAnnotation) { Object value = AnnotationUtils.getValue(valueAnnotation); if (value == null) { throw new IllegalStateException("Value annotation must have a value attribute"); } return value; }
/** {@inheritDoc} */ public String getUserPassword(Long userId) { JdbcTemplate jdbcTemplate = new JdbcTemplate(SessionFactoryUtils.getDataSource(getSessionFactory())); Table table = AnnotationUtils.findAnnotation(SysUserEntity.class, Table.class); return jdbcTemplate.queryForObject( "select password from " + table.name() + " where id=?", String.class, userId); }
private AbstractEndpoint createEndpoint(MessageHandler handler, T annotation) { AbstractEndpoint endpoint = null; String inputChannelName = (String) AnnotationUtils.getValue(annotation, INPUT_CHANNEL_ATTRIBUTE); if (StringUtils.hasText(inputChannelName)) { MessageChannel inputChannel; try { inputChannel = this.channelResolver.resolveDestination(inputChannelName); } catch (DestinationResolutionException e) { inputChannel = new DirectChannel(); if (this.beanFactory instanceof ConfigurableListableBeanFactory) { ConfigurableListableBeanFactory listableBeanFactory = (ConfigurableListableBeanFactory) this.beanFactory; listableBeanFactory.registerSingleton(inputChannelName, inputChannel); inputChannel = (MessageChannel) listableBeanFactory.initializeBean(inputChannel, inputChannelName); } } Assert.notNull(inputChannel, "failed to resolve inputChannel '" + inputChannelName + "'"); Assert.isInstanceOf( SubscribableChannel.class, inputChannel, "The input channel for an Annotation-based endpoint must be a SubscribableChannel."); endpoint = new EventDrivenConsumer((SubscribableChannel) inputChannel, handler); } return endpoint; }
/** {@inheritDoc} */ public String getUserPassword(String username) { SimpleJdbcTemplate jdbcTemplate = new SimpleJdbcTemplate(SessionFactoryUtils.getDataSource(getSessionFactory())); Table table = AnnotationUtils.findAnnotation(User.class, Table.class); return jdbcTemplate.queryForObject( "select password from " + table.name() + " where username=?", String.class, username); }
@Override public Object postProcessAfterInitialization(final Object bean, final String beanName) throws BeansException { Class<?> targetClass = AopUtils.getTargetClass(bean); final RabbitListener classLevelListener = AnnotationUtils.findAnnotation(bean.getClass(), RabbitListener.class); final List<Method> multiMethods = new ArrayList<Method>(); ReflectionUtils.doWithMethods( targetClass, new ReflectionUtils.MethodCallback() { @Override public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { RabbitListener rabbitListener = AnnotationUtils.getAnnotation(method, RabbitListener.class); if (rabbitListener != null) { processAmqpListener(rabbitListener, method, bean, beanName); } if (classLevelListener != null) { RabbitHandler rabbitHandler = AnnotationUtils.getAnnotation(method, RabbitHandler.class); if (rabbitHandler != null) { multiMethods.add(method); } } } }); if (classLevelListener != null) { processMultiMethodListener(classLevelListener, multiMethods, bean, beanName); } return bean; }
/** * Initialize a new HandlerMethodResolver for the specified handler type. * * @param handlerType the handler class to introspect */ public void init(Class<?> handlerType) { Class<?>[] handlerTypes = Proxy.isProxyClass(handlerType) ? handlerType.getInterfaces() : new Class<?>[] {handlerType}; for (final Class<?> currentHandlerType : handlerTypes) { ReflectionUtils.doWithMethods( currentHandlerType, new ReflectionUtils.MethodCallback() { public void doWith(Method method) { Method specificMethod = ClassUtils.getMostSpecificMethod(method, currentHandlerType); if (isHandlerMethod(method)) { handlerMethods.add(specificMethod); } else if (method.isAnnotationPresent(InitBinder.class)) { initBinderMethods.add(specificMethod); } else if (method.isAnnotationPresent(ModelAttribute.class)) { modelAttributeMethods.add(specificMethod); } } }, ReflectionUtils.NON_BRIDGED_METHODS); } this.typeLevelMapping = AnnotationUtils.findAnnotation(handlerType, RequestMapping.class); SessionAttributes sessionAttributes = handlerType.getAnnotation(SessionAttributes.class); this.sessionAttributesFound = (sessionAttributes != null); if (this.sessionAttributesFound) { this.sessionAttributeNames.addAll(Arrays.asList(sessionAttributes.value())); this.sessionAttributeTypes.addAll(Arrays.asList(sessionAttributes.types())); } }
/** * Uses method and type-level @{@link RequestMapping} annotations to create the * RequestMappingInfo. * * @return the created RequestMappingInfo, or {@code null} if the method does not have a * {@code @RequestMapping} annotation. * @see #getCustomMethodCondition(Method) * @see #getCustomTypeCondition(Class) */ @Override protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) { RequestMappingInfo info = null; RequestMapping methodAnnotation = AnnotationUtils.findAnnotation(method, RequestMapping.class); if (methodAnnotation != null) { RequestCondition<?> methodCondition = getCustomMethodCondition(method); info = createRequestMappingInfo(methodAnnotation, methodCondition); RequestMapping typeAnnotation = AnnotationUtils.findAnnotation(handlerType, RequestMapping.class); if (typeAnnotation != null) { RequestCondition<?> typeCondition = getCustomTypeCondition(handlerType); info = createRequestMappingInfo(typeAnnotation, typeCondition).combine(info); } } return info; }
protected WebApplicationContext createRootApplicationContext(ServletContext servletContext) { SpringApplicationBuilder builder = new SpringApplicationBuilder(); builder.main(getClass()); ApplicationContext parent = getExistingRootWebApplicationContext(servletContext); if (parent != null) { this.logger.info("Root context already created (using as parent)."); servletContext.setAttribute( WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, null); builder.initializers(new ParentContextApplicationContextInitializer(parent)); } builder.initializers(new ServletContextApplicationContextInitializer(servletContext)); builder.contextClass(AnnotationConfigEmbeddedWebApplicationContext.class); builder = configure(builder); SpringApplication application = builder.build(); if (application.getSources().isEmpty() && AnnotationUtils.findAnnotation(getClass(), Configuration.class) != null) { application.getSources().add(getClass()); } Assert.state( application.getSources().size() > 0, "No SpringApplication sources have been defined. Either override the " + "configure method or add an @Configuration annotation"); // Ensure error pages are registered application.getSources().add(ErrorPageFilter.class); return run(application); }
public static <T extends Annotation> T getAnnotation( PropertyDescriptor pd, Class<T> annotationType) { Method readMethod = pd.getReadMethod(); Preconditions.checkNotNull(readMethod); T column = AnnotationUtils.findAnnotation(readMethod, annotationType); return column; }
/** * Inspects the relationship resource and returns meta data about it * * @param annot * @param resource */ private static List<ResourceMetadata> inspectRelationship( RelationshipResource annot, Class<?> resource) { Map<String, Object> annotAttribs = AnnotationUtils.getAnnotationAttributes(annot); String urlPath = String.valueOf(annotAttribs.get("name")); String entityPath = findEntityNameByAnnotationAttributes(annotAttribs); MetaHelper helper = new MetaHelper(resource); findOperation(RelationshipResourceAction.Create.class, HttpMethod.POST, helper); findOperation(RelationshipResourceAction.Read.class, HttpMethod.GET, helper); findOperation(RelationshipResourceAction.ReadById.class, HttpMethod.GET, helper); findOperation(RelationshipResourceAction.Update.class, HttpMethod.PUT, helper); findOperation(RelationshipResourceAction.Delete.class, HttpMethod.DELETE, helper); if (resource.isAnnotationPresent(WebApiDeleted.class)) { return Arrays.asList( new ResourceMetadata( ResourceDictionary.resourceKey(entityPath, urlPath), RESOURCE_TYPE.RELATIONSHIP, null, inspectApi(resource), ALL_RELATIONSHIP_RESOURCE_INTERFACES, entityPath)); } else { return Arrays.asList( new ResourceMetadata( ResourceDictionary.resourceKey(entityPath, urlPath), RESOURCE_TYPE.RELATIONSHIP, helper.operations, inspectApi(resource), helper.apiDeleted, entityPath)); } }
protected void initBinder( Object handler, String attrName, WebDataBinder binder, NativeWebRequest webRequest) throws Exception { if (this.bindingInitializer != null) { this.bindingInitializer.initBinder(binder, webRequest); } if (handler != null) { Set<Method> initBinderMethods = this.methodResolver.getInitBinderMethods(); if (!initBinderMethods.isEmpty()) { boolean debug = logger.isDebugEnabled(); for (Method initBinderMethod : initBinderMethods) { Method methodToInvoke = BridgeMethodResolver.findBridgedMethod(initBinderMethod); String[] targetNames = AnnotationUtils.findAnnotation(methodToInvoke, InitBinder.class).value(); if (targetNames.length == 0 || Arrays.asList(targetNames).contains(attrName)) { Object[] initBinderArgs = resolveInitBinderArguments(handler, methodToInvoke, binder, webRequest); if (debug) { logger.debug("Invoking init-binder method: " + methodToInvoke); } Object returnValue = doInvokeMethod(methodToInvoke, handler, initBinderArgs); if (returnValue != null) { throw new IllegalStateException( "InitBinder methods must not have a return value: " + methodToInvoke); } } } } } }
@Override protected Set<String> getExclusions( AnnotationMetadata metadata, AnnotationAttributes attributes) { Set<String> exclusions = new LinkedHashSet<String>(); Class<?> source = ClassUtils.resolveClassName(metadata.getClassName(), null); for (String annotationName : ANNOTATION_NAMES) { AnnotationAttributes merged = AnnotatedElementUtils.getMergedAnnotationAttributes(source, annotationName); Class<?>[] exclude = (merged == null ? null : merged.getClassArray("exclude")); if (exclude != null) { for (Class<?> excludeClass : exclude) { exclusions.add(excludeClass.getName()); } } } for (List<Annotation> annotations : getAnnotations(metadata).values()) { for (Annotation annotation : annotations) { String[] exclude = (String[]) AnnotationUtils.getAnnotationAttributes(annotation, true).get("exclude"); if (!ObjectUtils.isEmpty(exclude)) { exclusions.addAll(Arrays.asList(exclude)); } } } return exclusions; }
public AnnotationAttributes(Annotation annotation) { Assert.state( (annotation instanceof DatabaseSetup) || (annotation instanceof DatabaseTearDown), "Only DatabaseSetup and DatabaseTearDown annotations are supported"); Map<String, Object> attributes = AnnotationUtils.getAnnotationAttributes(annotation); this.type = (DatabaseOperation) attributes.get("type"); this.value = (String[]) attributes.get("value"); }
public final Object invokeHandlerMethod( Method handlerMethod, Object handler, NativeWebRequest webRequest, ExtendedModelMap implicitModel) throws Exception { Method handlerMethodToInvoke = BridgeMethodResolver.findBridgedMethod(handlerMethod); try { boolean debug = logger.isDebugEnabled(); for (String attrName : this.methodResolver.getActualSessionAttributeNames()) { Object attrValue = this.sessionAttributeStore.retrieveAttribute(webRequest, attrName); if (attrValue != null) { implicitModel.addAttribute(attrName, attrValue); } } for (Method attributeMethod : this.methodResolver.getModelAttributeMethods()) { Method attributeMethodToInvoke = BridgeMethodResolver.findBridgedMethod(attributeMethod); Object[] args = resolveHandlerArguments(attributeMethodToInvoke, handler, webRequest, implicitModel); if (debug) { logger.debug("Invoking model attribute method: " + attributeMethodToInvoke); } String attrName = AnnotationUtils.findAnnotation(attributeMethod, ModelAttribute.class).value(); if (!"".equals(attrName) && implicitModel.containsAttribute(attrName)) { continue; } ReflectionUtils.makeAccessible(attributeMethodToInvoke); Object attrValue = attributeMethodToInvoke.invoke(handler, args); if ("".equals(attrName)) { Class<?> resolvedType = GenericTypeResolver.resolveReturnType(attributeMethodToInvoke, handler.getClass()); attrName = Conventions.getVariableNameForReturnType( attributeMethodToInvoke, resolvedType, attrValue); } if (!implicitModel.containsAttribute(attrName)) { implicitModel.addAttribute(attrName, attrValue); } } Object[] args = resolveHandlerArguments(handlerMethodToInvoke, handler, webRequest, implicitModel); if (debug) { logger.debug("Invoking request handler method: " + handlerMethodToInvoke); } ReflectionUtils.makeAccessible(handlerMethodToInvoke); return handlerMethodToInvoke.invoke(handler, args); } catch (IllegalStateException ex) { // Internal assertion failed (e.g. invalid signature): // throw exception with full handler method context... throw new HandlerMethodInvocationException(handlerMethodToInvoke, ex); } catch (InvocationTargetException ex) { // User-defined @ModelAttribute/@InitBinder/@RequestMapping method threw an exception... ReflectionUtils.rethrowException(ex.getTargetException()); return null; } }