List of usage examples for java.lang Class isAnnotationPresent
@Override public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass)
From source file:org.broadinstitute.gatk.utils.help.GATKDoclet.java
/** * Returns the instantiated DocumentedGATKFeatureObject that describes the GATKDoc * structure we will apply to Doc./* w w w. j a v a 2 s . co m*/ * * @param doc * @return null if this proves inappropriate or doc shouldn't be documented */ private DocumentedGATKFeatureObject getFeatureForClassDoc(ClassDoc doc) { Class<? extends Object> docClass = getClassForClassDoc(doc); if (docClass == null) return null; // not annotated so it shouldn't be documented if (docClass.isAnnotationPresent(DocumentedGATKFeature.class)) { DocumentedGATKFeature f = docClass.getAnnotation(DocumentedGATKFeature.class); return new DocumentedGATKFeatureObject(docClass, f.enable(), f.groupName(), f.summary(), f.extraDocs()); } else { for (DocumentedGATKFeatureObject staticDocs : STATIC_DOCS) { if (staticDocs.getClassToDoc().isAssignableFrom(docClass)) { return new DocumentedGATKFeatureObject(docClass, staticDocs.enable(), staticDocs.groupName(), staticDocs.summary(), staticDocs.extraDocs()); } } return null; } }
From source file:org.openspaces.remoting.SpaceRemotingServiceExporter.java
private boolean shouldAutowire(Object service) { if (service instanceof AutowireArgumentsMarker) { return true; }//from w w w .ja v a 2 s. co m if (service.getClass().isAnnotationPresent(AutowireArguments.class)) { return true; } for (Class clazz : service.getClass().getInterfaces()) { if (clazz.isAnnotationPresent(AutowireArguments.class)) { return true; } } return false; }
From source file:com.zero_x_baadf00d.partialize.Partialize.java
/** * Build a JSON object from data taken from the scanner and * the given class type and instance.// w ww. j a v a2s . co m * * @param depth The current depth * @param fields The field names to requests * @param clazz The class of the object to render * @param instance The instance of the object to render * @param partialObject The partial JSON document * @return A JSON Object * @since 16.01.18 */ private ObjectNode buildPartialObject(final int depth, String fields, final Class<?> clazz, final Object instance, final ObjectNode partialObject) { if (depth <= this.maximumDepth) { if (clazz.isAnnotationPresent(com.zero_x_baadf00d.partialize.annotation.Partialize.class)) { final List<String> closedFields = new ArrayList<>(); List<String> allowedFields = Arrays.asList(clazz .getAnnotation(com.zero_x_baadf00d.partialize.annotation.Partialize.class).allowedFields()); List<String> defaultFields = Arrays.asList(clazz .getAnnotation(com.zero_x_baadf00d.partialize.annotation.Partialize.class).defaultFields()); if (allowedFields.isEmpty()) { allowedFields = new ArrayList<>(); for (final Method m : clazz.getDeclaredMethods()) { final String methodName = m.getName(); if (methodName.startsWith("get") || methodName.startsWith("has")) { final char[] c = methodName.substring(3).toCharArray(); c[0] = Character.toLowerCase(c[0]); allowedFields.add(new String(c)); } else if (methodName.startsWith("is")) { final char[] c = methodName.substring(2).toCharArray(); c[0] = Character.toLowerCase(c[0]); allowedFields.add(new String(c)); } } } if (defaultFields.isEmpty()) { defaultFields = allowedFields.stream().map(f -> { if (this.aliases != null && this.aliases.containsValue(f)) { for (Map.Entry<String, String> e : this.aliases.entrySet()) { if (e.getValue().compareToIgnoreCase(f) == 0) { return e.getKey(); } } } return f; }).collect(Collectors.toList()); } if (fields == null || fields.length() == 0) { fields = defaultFields.stream().collect(Collectors.joining(",")); } Scanner scanner = new Scanner(fields); scanner.useDelimiter(com.zero_x_baadf00d.partialize.Partialize.SCANNER_DELIMITER); while (scanner.hasNext()) { String word = scanner.next(); String args = null; if (word.compareTo("*") == 0) { final StringBuilder sb = new StringBuilder(); if (scanner.hasNext()) { scanner.useDelimiter("\n"); sb.append(","); sb.append(scanner.next()); } final Scanner newScanner = new Scanner( allowedFields.stream().filter(f -> !closedFields.contains(f)).map(f -> { if (this.aliases != null && this.aliases.containsValue(f)) { for (Map.Entry<String, String> e : this.aliases.entrySet()) { if (e.getValue().compareToIgnoreCase(f) == 0) { return e.getKey(); } } } return f; }).collect(Collectors.joining(",")) + sb.toString()); newScanner.useDelimiter(com.zero_x_baadf00d.partialize.Partialize.SCANNER_DELIMITER); scanner.close(); scanner = newScanner; } if (word.contains("(")) { while (scanner.hasNext() && (StringUtils.countMatches(word, "(") != StringUtils.countMatches(word, ")"))) { word += "," + scanner.next(); } final Matcher m = this.fieldArgsPattern.matcher(word); if (m.find()) { word = m.group(1); args = m.group(2); } } final String aliasField = word; final String field = this.aliases != null && this.aliases.containsKey(aliasField) ? this.aliases.get(aliasField) : aliasField; if (allowedFields.stream().anyMatch( f -> f.toLowerCase(Locale.ENGLISH).compareTo(field.toLowerCase(Locale.ENGLISH)) == 0)) { if (this.accessPolicyFunction != null && !this.accessPolicyFunction.apply(new AccessPolicy(clazz, instance, field))) { continue; } closedFields.add(aliasField); try { final Method method = clazz.getMethod("get" + WordUtils.capitalize(field)); final Object object = method.invoke(instance); this.internalBuild(depth, aliasField, field, args, partialObject, clazz, object); } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException ignore) { try { final Method method = clazz.getMethod(field); final Object object = method.invoke(instance); this.internalBuild(depth, aliasField, field, args, partialObject, clazz, object); } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException ex) { if (this.exceptionConsumer != null) { this.exceptionConsumer.accept(ex); } } } } } return partialObject; } else if (instance instanceof Map<?, ?>) { if (fields == null || fields.isEmpty() || fields.compareTo("*") == 0) { for (Map.Entry<?, ?> e : ((Map<?, ?>) instance).entrySet()) { this.internalBuild(depth, String.valueOf(e.getKey()), String.valueOf(e.getKey()), null, partialObject, e.getValue() == null ? Object.class : e.getValue().getClass(), e.getValue()); } } else { final Map<?, ?> tmpMap = (Map<?, ?>) instance; for (final String k : fields.split(",")) { if (k.compareTo("*") != 0) { final Object o = tmpMap.get(k); this.internalBuild(depth, k, k, null, partialObject, o == null ? Object.class : o.getClass(), o); } else { for (Map.Entry<?, ?> e : ((Map<?, ?>) instance).entrySet()) { this.internalBuild(depth, String.valueOf(e.getKey()), String.valueOf(e.getKey()), null, partialObject, e.getValue() == null ? Object.class : e.getValue().getClass(), e.getValue()); } } } } } else { throw new RuntimeException("Can't convert " + clazz.getCanonicalName()); } } return partialObject; }
From source file:com.sinosoft.one.mvc.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 : MvcConstants.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 w w w .j ava 2 s . co 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:org.thiesen.helenaorm.HelenaDAO.java
HelenaDAO(final Class<T> clz, final String hostname, final int port, final SerializeUnknownClasses serializationPolicy, final ImmutableMap<Class<?>, TypeMapping<?>> typeMappings) { if (!clz.isAnnotationPresent(HelenaBean.class)) { throw new IllegalArgumentException( "Trying to get a HelenaDAO for a class that is not mapped with @HelenaBean"); }/*from w w w.j a va 2 s.c om*/ final HelenaBean annotation = clz.getAnnotation(HelenaBean.class); _typeConverter = new TypeConverter(typeMappings, serializationPolicy); _clz = clz; _propertyDescriptors = PropertyUtils.getPropertyDescriptors(clz); _columnFamily = annotation.columnFamily(); _hostname = hostname; _port = port; _keyspace = annotation.keyspace(); if (annotation.consistency() != null) { this.setConsistencyLevel(annotation.consistency()); } _fields = new HashMap<String, Field>(); for (Field field : clz.getDeclaredFields()) { _fields.put(field.getName(), field); if (field.isAnnotationPresent(KeyProperty.class)) { _keyField = field; } } final Builder<byte[]> setBuilder = ImmutableSet.<byte[]>builder(); for (final PropertyDescriptor descriptor : _propertyDescriptors) { setBuilder.add(_typeConverter.stringToBytes(descriptor.getName())); if (isKeyProperty(descriptor)) { _keyPropertyDescriptor = descriptor; } if (isSuperColumnProperty(descriptor)) { _superColumnPropertyDescriptor = descriptor; } } _columnNames = ImmutableList.copyOf(setBuilder.build()); if (_keyField == null && _keyPropertyDescriptor == null) { throw new HelenaRuntimeException( "Could not find key of class " + clz.getName() + ", did you annotate with @KeyProperty"); } }
From source file:com.sinosoft.one.mvc.web.impl.module.ModulesBuilderImpl.java
private List<InterceptorDelegate> findInterceptors(XmlWebApplicationContext context) throws FileNotFoundException, ParserConfigurationException, SAXException, IOException { String[] interceptorNames = SpringUtils.getBeanNames(context.getBeanFactory(), ControllerInterceptor.class); ArrayList<InterceptorDelegate> interceptors = new ArrayList<InterceptorDelegate>(interceptorNames.length); for (String beanName : interceptorNames) { ControllerInterceptor interceptor = (ControllerInterceptor) context.getBean(beanName); Class<?> userClass = ClassUtils.getUserClass(interceptor); if (userClass.isAnnotationPresent(Ignored.class)) { if (logger.isDebugEnabled()) { logger.debug("Ignored interceptor (Ignored):" + interceptor); }/*from ww w . ja va 2 s.c om*/ continue; } if (userClass.isAnnotationPresent(NotForSubModules.class) && !context.getBeanFactory().containsBeanDefinition(beanName)) { if (logger.isDebugEnabled()) { logger.debug("Ignored interceptor (NotForSubModules):" + interceptor); } continue; } if (!userClass.getSimpleName().endsWith(MvcConstants.INTERCEPTOR_SUFFIX)) { logger.error("", new IllegalArgumentException("Interceptor must be end with '" + MvcConstants.INTERCEPTOR_SUFFIX + "': " + userClass.getName())); continue; } InterceptorBuilder builder = new InterceptorBuilder(interceptor); Interceptor annotation = userClass.getAnnotation(Interceptor.class); if (annotation != null) { builder.oncePerRequest(annotation.oncePerRequest()); } String interceporName; if (beanName.startsWith(AUTO_BEAN_NAME_PREFIX)) { interceporName = StringUtils.removeEnd(StringUtils.uncapitalize(userClass.getSimpleName()), MvcConstants.INTERCEPTOR_SUFFIX); } else { interceporName = StringUtils.removeEnd(beanName, MvcConstants.INTERCEPTOR_SUFFIX); } final String mvc = "mvc"; if (interceporName.startsWith(mvc) && (interceporName.length() == mvc.length() || Character.isUpperCase(interceporName.charAt(mvc.length()))) && !userClass.getName().startsWith("com.sinosoft.one.mvc.")) { throw new IllegalArgumentException("illegal interceptor name '" + interceporName + "' for " + userClass.getName() + ": don't starts with 'mvc', it's reserved"); } builder.name(interceporName); InterceptorDelegate wrapper = builder.build(); interceptors.add(wrapper); if (logger.isDebugEnabled()) { int priority = 0; if (interceptor instanceof Ordered) { priority = ((Ordered) interceptor).getPriority(); } logger.debug("recognized interceptor[priority=" + priority + "]: " // \r\n + wrapper.getName() + "=" + userClass.getName()); } } // start by kylin List<String> rList = ResourceLoaderUtil.getResource("interceptors-order.xml", true); if (rList != null) { Collections.sort(interceptors); int tempGlobalPriority = 1; for (String configInterName : rList) { for (int j = 0, length = interceptors.size(); j < length; j++) { InterceptorDelegate interceptorDelegate = interceptors.get(j); ControllerInterceptor temp = InterceptorDelegate .getMostInnerInterceptor(interceptorDelegate.getInterceptor()); if (temp.getClass().getName().startsWith("com.sinosoft.one.mvc.web") || temp.getClass().getName().startsWith("com.sinosoft.one.mvc.controllers")) { continue; } if (rList.toString().contains(temp.getClass().getName())) { if (configInterName.trim().equals(temp.getClass().getName())) { if (temp instanceof ControllerInterceptorAdapter) { ((ControllerInterceptorAdapter) temp).setPriority( this.GLOBAL_INTERCEPTOR_CONFIG_START_PRIORITY - tempGlobalPriority++); continue; } else { if (temp instanceof ControllerInterceptorAdapter) { ((ControllerInterceptorAdapter) temp).setPriority( this.INTERCEPTOR_NOT_CONFIG_START_PRIORITY - tempGlobalPriority++); } } } } else { if (temp instanceof ControllerInterceptorAdapter) { ((ControllerInterceptorAdapter) temp) .setPriority(this.INTERCEPTOR_NOT_CONFIG_START_PRIORITY - tempGlobalPriority++); } } if (logger.isDebugEnabled()) { logger.debug("Interceptor's Priority:" + temp.getClass().getName() + ":" + ((ControllerInterceptorAdapter) temp).getPriority()); } } } } // end by kylin Collections.sort(interceptors); throwExceptionIfDuplicatedNames(interceptors); return interceptors; }
From source file:com.vmware.photon.controller.swagger.resources.SwaggerJsonListing.java
/** * Parses annotations and turns them into API representations. It goes through a resource class that is annotated * with @Api and will generate docs for all HTTP endpoints, the parameters they take, the values they return, * and create JSON models of every non-primitive type that is encountered so that swagger-ui can accurately display * the information for parameter and return types. It also will recursively call itself when it finds return values * in methods that are subresources./*ww w . j ava 2 s .c o m*/ * * @param models A hashmap of the class name to a SwaggerModel api representation. This is passed all around so * that anytime a new type is encountered it can be documented. * @param resource The resource class we are documenting methods, parameters, return types for. * @param uriBuilder This uriBuilder is passed around so that subresources can keep track of the uri path of parent * resources. * @param parentParams The parameters that a parent resource takes, which a subresource would need to document. * @return */ private List<SwaggerApiListing> getApiListings(HashMap<String, SwaggerModel> models, Resource resource, UriBuilder uriBuilder, List<SwaggerParameter> parentParams, Map<Resource, Class<?>> resourcesMap) { Class<?> resourceClass = resourcesMap.get(resource); List<SwaggerApiListing> apiListings = new ArrayList<>(); if (resourceClass.isAnnotationPresent(Path.class)) { Path methodPath = resourceClass.getAnnotation(Path.class); uriBuilder.path(methodPath.value()); } if (resourceClass.isAnnotationPresent(Api.class)) { List<ResourceMethod> resourceMethods = new ArrayList<>(resource.getResourceMethods()); for (Resource childResource : resource.getChildResources()) { resourceMethods.addAll(childResource.getAllMethods()); } for (ResourceMethod method : resourceMethods) { apiListings = concatListings(apiListings, getMethodData(models, method, uriBuilder.clone(), parentParams, resourcesMap)); } } return apiListings; }
From source file:org.glassfish.tyrus.tests.qa.tools.GlassFishToolkit.java
private boolean isBlackListed(File clazz) throws ClassNotFoundException, MalformedURLException { //logger.log(Level.FINE, "File? {0}", clazzCanonicalName); Class tryMe = getClazzForFile(clazz); logger.log(Level.FINE, "File? {0}", tryMe.getCanonicalName()); logger.log(Level.FINE, "Interfaces:{0}", tryMe.getInterfaces()); if (Arrays.asList(tryMe.getInterfaces()).contains((ServerApplicationConfig.class))) { logger.log(Level.FINE, "ServerApplicationConfig : {0}", tryMe.getCanonicalName()); return true; }/* w w w . j av a 2 s . co m*/ if (tryMe.isAnnotationPresent(ServerEndpoint.class)) { logger.log(Level.FINE, "Annotated ServerEndpoint: {0}", tryMe.getCanonicalName()); return true; } if (tryMe.isAnnotationPresent(ClientEndpoint.class)) { logger.log(Level.FINE, "Annotated ClientEndpoint: {0}", tryMe.getCanonicalName()); return true; } //Endpoint itself is not blacklisted // TYRUS-150 //if (Endpoint.class.isAssignableFrom(tryMe)) { // logger.log(Level.INFO, "Programmatic Endpoint: {0}", tryMe.getCanonicalName()); // return true; //} return false; }
From source file:com.wit.android.support.fragment.manage.BaseFragmentFactory.java
/** * Creates a new instance of BaseFragmentFactory. If {@link com.wit.android.support.fragment.annotation.FactoryFragments @FactoryFragments} * or {@link com.wit.android.support.fragment.annotation.FragmentFactories @FragmentFactories} * annotations are presented above a sub-class of this BaseFragmentFactory, they will be processed * here.// ww w . j a v a2s. com */ public BaseFragmentFactory() { final Class<?> classOfFactory = ((Object) this).getClass(); /** * Process class annotations. */ final SparseArray<FragmentItem> items = new SparseArray<>(); // Obtain fragment ids. if (classOfFactory.isAnnotationPresent(FactoryFragments.class)) { final FactoryFragments fragments = classOfFactory.getAnnotation(FactoryFragments.class); final int[] ids = fragments.value(); if (ids.length > 0) { for (int id : ids) { items.put(id, new FragmentItem(id, getFragmentTag(id), null)); } } } this.processAnnotatedFragments(classOfFactory, items); if (items.size() > 0) { this.mItems = items; } // Obtain joined factories. final List<Class<? extends FragmentController.FragmentFactory>> factories = this.gatherJoinedFactories( classOfFactory, new ArrayList<Class<? extends FragmentController.FragmentFactory>>()); if (!factories.isEmpty()) { for (Class<? extends FragmentController.FragmentFactory> factory : factories) { FragmentController.FragmentFactory fragmentFactory = null; try { fragmentFactory = factory.newInstance(); } catch (InstantiationException | IllegalAccessException e) { Log.e(TAG, "Failed to instantiate the fragment factory class of(" + factory.getSimpleName() + ")." + "Make sure this fragment factory has public empty constructor.", e); } if (fragmentFactory != null) { joinFactory(fragmentFactory); } } } }
From source file:cn.annoreg.mc.s11n.SerializationManager.java
public <T> DataSerializer<T> getDataSerializer(Class<T> clazz) { DataSerializer<T> ser = dataSerializers.get(clazz); if (ser == null && clazz.isAnnotationPresent(RegSerializable.class)) { ser = createAutoSerializerFor(clazz); }/*from w w w . j a va 2s . com*/ return ser; }