List of usage examples for java.lang Class isAnnotationPresent
@Override public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass)
From source file:org.debux.webmotion.jpa.GenericDAO.java
/** * Complete entity with parameters. Try to convert parameter, if the type not * match. To create an association on entity, you must pass only identifier. * //from ww w . j a v a2 s . c om * @param entity entity * @param parameters parameters * @return entity completed */ protected IdentifiableEntity extract(IdentifiableEntity entity, Parameters parameters) { try { Field[] fields = entityClass.getDeclaredFields(); for (Field field : fields) { String name = field.getName(); Class<?> type = field.getType(); Object[] values = parameters.get(name); // The identifier can't be set if (!IdentifiableEntity.ATTRIBUTE_NAME_ID.equals(name) && values != null) { if (values.length == 0) { // Null value beanUtil.setProperty(entity, name, null); } else if (type.isAnnotationPresent(javax.persistence.Entity.class)) { // Association List<Object> references = new ArrayList<Object>(values.length); for (Object value : values) { Object reference = manager.find(type, value); if (reference != null) { references.add(reference); } } Object converted = null; if (List.class.isAssignableFrom(type)) { converted = references; } else if (Set.class.isAssignableFrom(type)) { converted = new HashSet<Object>(references); } else if (SortedSet.class.isAssignableFrom(type)) { converted = new TreeSet<Object>(references); } else if (type.isArray()) { converted = references.toArray(); } else if (Map.class.isAssignableFrom(type)) { String keyName = IdentifiableEntity.ATTRIBUTE_NAME_ID; MapKey annotation = type.getAnnotation(MapKey.class); if (annotation != null) { String annotationName = annotation.name(); if (annotationName != null && !annotationName.isEmpty()) { keyName = annotationName; } } Map<Object, Object> map = new HashMap<Object, Object>(); for (Object object : references) { Object key = propertyUtils.getProperty(object, keyName); map.put(key, object); } converted = map; } else if (!references.isEmpty()) { converted = references.get(0); } beanUtil.setProperty(entity, name, converted); } else { // Basic object if (Collection.class.isAssignableFrom(type)) { Class convertType = String.class; Type genericType = field.getGenericType(); if (genericType != null && genericType instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) genericType; convertType = (Class) parameterizedType.getActualTypeArguments()[0]; } Collection<Object> collection = null; if (Set.class.isAssignableFrom(type)) { collection = new HashSet<Object>(); } else if (SortedSet.class.isAssignableFrom(type)) { collection = new TreeSet(); } else { collection = new ArrayList<Object>(); } for (Object object : values) { Object convertedObject = convertUtils.convert(object, convertType); collection.add(convertedObject); } beanUtil.setProperty(entity, name, collection); } else if (Map.class.isAssignableFrom(type)) { throw new UnsupportedOperationException( "Map is not supported, you must create a specific entity."); } else { Object converted = convertUtils.convert(values, type); beanUtil.setProperty(entity, name, converted); } } } } return entity; } catch (IllegalAccessException iae) { throw new WebMotionException("Error during create instance", iae); } catch (InvocationTargetException ite) { throw new WebMotionException("Error during set field on instance", ite); } catch (NoSuchMethodException nsme) { throw new WebMotionException("Error during set field on instance", nsme); } }
From source file:org.red5.io.amf3.Output.java
/** {@inheritDoc} */ @Override/* w w w . j a v a 2s . co m*/ protected void writeArbitraryObject(Object object, Serializer serializer) { Class<?> objectClass = object.getClass(); String className = objectClass.getName(); if (className.startsWith("org.red5.compatibility.")) { // Strip compatibility prefix from classname className = className.substring(23); } // If we need to serialize class information... if (!objectClass.isAnnotationPresent(Anonymous.class)) { putString(className); } else { putString(""); } // Store key/value pairs amf3_mode += 1; // Get public field values Map<String, Object> values = new HashMap<String, Object>(); // Iterate thru fields of an object to build "name-value" map from it for (Field field : objectClass.getFields()) { if (field.isAnnotationPresent(DontSerialize.class)) { if (log.isDebugEnabled()) { log.debug("Skipping " + field.getName() + " because its marked with @DontSerialize"); } continue; } else { int modifiers = field.getModifiers(); if (Modifier.isTransient(modifiers)) { log.warn("Using \"transient\" to declare fields not to be serialized is " + "deprecated and will be removed in Red5 0.8, use \"@DontSerialize\" instead."); continue; } } Object value; try { // Get field value value = field.get(object); } catch (IllegalAccessException err) { // Swallow on private and protected properties access exception continue; } // Put field to the map of "name-value" pairs values.put(field.getName(), value); } // Output public values Iterator<Map.Entry<String, Object>> it = values.entrySet().iterator(); // Iterate thru map and write out properties with separators while (it.hasNext()) { Map.Entry<String, Object> entry = it.next(); // Write out prop name putString(entry.getKey()); // Write out serializer.serialize(this, entry.getValue()); } amf3_mode -= 1; // Write out end of object marker putString(""); }
From source file:org.broadinstitute.sting.utils.help.GenericDocumentationHandler.java
@Override public boolean includeInDocs(ClassDoc doc) { try {/*from w w w .jav a2 s . com*/ Class type = HelpUtils.getClassForDoc(doc); boolean hidden = !getDoclet().showHiddenFeatures() && type.isAnnotationPresent(Hidden.class); return !hidden && JVMUtils.isConcrete(type); } catch (ClassNotFoundException e) { return false; } }
From source file:org.solmix.datax.support.DefaultDataServiceManager.java
@SuppressWarnings("unchecked") @Override// w ww. j a v a2 s .c o m public <T> T getService(Class<T> serviceClass) { if (serviceClass == null) { throw new IllegalArgumentException("DataService proxy interface is null!"); } Object proxy = proxys.get(serviceClass); if (proxy == null) { if (!serviceClass.isInterface()) { throw new IllegalArgumentException( "DataService proxy Type:[" + serviceClass.getName() + "] is not a interface!"); } if (!serviceClass.isAnnotationPresent(org.solmix.datax.annotation.DataService.class)) { throw new IllegalArgumentException( "DataService proxy Type:[" + serviceClass.getName() + "] ,without @," + org.solmix.datax.annotation.DataService.class.getSimpleName() + " Annotation!"); } DataServiceProxy<T> dsp = new DataServiceProxy<T>(serviceClass, new DataxSessionImpl(this)); Object instance = dsp.newInstance(); proxys.putIfAbsent(serviceClass, instance); return (T) proxys.get(serviceClass); } else { return (T) proxy; } }
From source file:org.j2free.invoker.InvokerFilter.java
/** * Locks to prevent request processing while mapping is added. * * Finds all classes annotated with ServletConfig and maps the class to * the url specified in the annotation. Wildcard mapping are allowed in * the form of *.extension or /some/path/* * * @param context an active ServletContext */// ww w . ja v a 2s .c o m public void load(final ServletContext context) { try { write.lock(); LinkedList<URL> urlList = new LinkedList<URL>(); urlList.addAll(Arrays.asList(ClasspathUrlFinder.findResourceBases(EMPTY))); urlList.addAll(Arrays.asList(WarUrlFinder.findWebInfLibClasspaths(context))); URL[] urls = new URL[urlList.size()]; urls = urlList.toArray(urls); AnnotationDB annoDB = new AnnotationDB(); annoDB.setScanClassAnnotations(true); annoDB.setScanFieldAnnotations(false); annoDB.setScanMethodAnnotations(false); annoDB.setScanParameterAnnotations(false); annoDB.scanArchives(urls); HashMap<String, Set<String>> annotationIndex = (HashMap<String, Set<String>>) annoDB .getAnnotationIndex(); if (annotationIndex != null && !annotationIndex.isEmpty()) { //----------------------------------------------------------- // Look for any classes annotated with @ServletConfig Set<String> classNames = annotationIndex.get(ServletConfig.class.getName()); if (classNames != null) { for (String c : classNames) { try { final Class<? extends HttpServlet> klass = (Class<? extends HttpServlet>) Class .forName(c); if (klass.isAnnotationPresent(ServletConfig.class)) { final ServletConfig config = (ServletConfig) klass .getAnnotation(ServletConfig.class); // If the config specifies String mapppings... if (config.mappings() != null) { for (String url : config.mappings()) { // Leave the asterisk, we'll add it when matching... //if (url.matches("(^\\*[^*]*?)|([^*]*?/\\*$)")) // url = url.replace("*", EMPTY); url = url.toLowerCase(); // all comparisons are lower-case if (urlMap.putIfAbsent(url, klass) == null) { if (log.isDebugEnabled()) log.debug("Mapping servlet " + klass.getName() + " to path " + url); } else log.error("Unable to map servlet " + klass.getName() + " to path " + url + ", path already mapped to " + urlMap.get(url).getName()); } } // If the config specifies a regex mapping... if (!empty(config.regex())) { regexMap.putIfAbsent(config.regex(), klass); if (log.isDebugEnabled()) log.debug("Mapping servlet " + klass.getName() + " to regex path " + config.regex()); } // Create an instance of the servlet and init it HttpServlet servlet = klass.newInstance(); servlet.init(new ServletConfigImpl(klass.getName(), context)); // Store a reference servletMap.put(klass, new ServletMapping(servlet, config)); } } catch (Exception e) { log.error("Error registering servlet [name=" + c + "]", e); } } } //----------------------------------------------------------- // Look for any classes annotated with @FiltersConfig classNames = annotationIndex.get(FilterConfig.class.getName()); if (classNames != null) { for (String c : classNames) { try { final Class<? extends Filter> klass = (Class<? extends Filter>) Class.forName(c); if (klass.isAnnotationPresent(FilterConfig.class)) { final FilterConfig config = (FilterConfig) klass.getAnnotation(FilterConfig.class); // Create an instance of the servlet and init it Filter filter = klass.newInstance(); filter.init(new FilterConfigImpl(klass.getName(), context)); if (log.isDebugEnabled()) log.debug("Mapping filter " + klass.getName() + " to path " + config.match()); // Store a reference filters.add(new FilterMapping(filter, config)); } } catch (Exception e) { log.error("Error registering servlet [name=" + c + "]", e); } } } } } catch (IOException e) { log.error("Error loading urlMappings", e); } finally { write.unlock(); // ALWAYS Release the configure lock } }
From source file:org.artifactory.spring.ArtifactoryApplicationContext.java
@Override protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) { super.prepareBeanFactory(beanFactory); //Add our own post processor that registers all reloadable beans auto-magically after construction beanFactory.addBeanPostProcessor(new BeanPostProcessor() { @Override// w w w .j a v a2s . c o m public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { Class<?> targetClass = AopUtils.getTargetClass(bean); if (ReloadableBean.class.isAssignableFrom(targetClass)) { Reloadable annotation; if (targetClass.isAnnotationPresent(Reloadable.class)) { annotation = targetClass.getAnnotation(Reloadable.class); Class<? extends ReloadableBean> beanClass = annotation.beanClass(); addReloadableBean(beanClass); } else { throw new IllegalStateException("Bean " + targetClass.getName() + " requires initialization beans to be initialized, but no such beans were found"); } } return bean; } @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { //Do nothing return bean; } }); }
From source file:com.eclecticlogic.pedal.dialect.postgresql.CopyCommand.java
private String extractColumnName(Method method, Class<? extends Serializable> clz) { String beanPropertyName = null; try {/*from www . j av a 2s .c o m*/ BeanInfo info; info = Introspector.getBeanInfo(clz); for (PropertyDescriptor propDesc : info.getPropertyDescriptors()) { if (method.equals(propDesc.getReadMethod())) { beanPropertyName = propDesc.getName(); break; } } } catch (IntrospectionException e) { throw new RuntimeException(e.getMessage(), e); } String columnName = null; if (clz.isAnnotationPresent(AttributeOverrides.class)) { for (AttributeOverride annotation : clz.getAnnotation(AttributeOverrides.class).value()) { if (annotation.name().equals(beanPropertyName)) { columnName = annotation.column().name(); break; } } } else if (clz.isAnnotationPresent(AttributeOverride.class)) { AttributeOverride annotation = clz.getAnnotation(AttributeOverride.class); if (annotation.name().equals(beanPropertyName)) { columnName = annotation.column().name(); } } return columnName == null ? method.getAnnotation(Column.class).name() : columnName; }
From source file:com.lucidtechnics.blackboard.Blackboard.java
private List<String> determineEventNames(Object _event) { List<String> eventNameList = new ArrayList<String>(); Class eventClass = _event.getClass(); if (eventClass.isAnnotationPresent(Event.class) == true) { Event event = (Event) eventClass.getAnnotation(Event.class); if (event.name() != null) { String[] nameArray = event.name().split(","); for (int i = 0; i < nameArray.length; i++) { eventNameList.add(createFullEventName(event.appName(), event.workspaceName(), nameArray[i])); }// w w w. ja va 2 s.c o m } } return eventNameList; }
From source file:org.grails.datastore.mapping.model.config.GormMappingConfigurationStrategy.java
/** * Tests whether an class is a persistent entity * * Based on the same method in Grails core within the DomainClassArtefactHandler class * @param clazz The java class//from w w w. j a v a 2 s .c o m * * @return True if it is a persistent entity */ public boolean isPersistentEntity(Class clazz) { // its not a closure if (clazz == null) return false; if (Closure.class.isAssignableFrom(clazz)) { return false; } if (Enum.class.isAssignableFrom(clazz)) return false; if (clazz.isAnnotationPresent(Entity.class)) { return true; } // this is done so we don't need a statically typed reference to the Grails annotation for (Annotation annotation : clazz.getAnnotations()) { if (annotation.toString().equals("@grails.persistence.Entity()")) return true; } Class testClass = clazz; boolean result = false; while (testClass != null && !testClass.equals(GroovyObject.class) && !testClass.equals(Object.class)) { try { // make sure the identify and version field exist testClass.getDeclaredField(IDENTITY_PROPERTY); testClass.getDeclaredField(VERSION_PROPERTY); // passes all conditions return true result = true; break; } catch (SecurityException e) { // ignore } catch (NoSuchFieldException e) { // ignore } testClass = testClass.getSuperclass(); } return result; }
From source file:org.broadinstitute.gatk.utils.help.GenericDocumentationHandler.java
/** * Utility function that determines the default downsampling settings for an instance of class c. * * @param myClass the class to query for the settings * @param dsSettings an empty HashMap in which to collect the info * @return a hash set of the downsampling settings, otherwise an empty set *//* w ww . ja v a 2 s.c om*/ private HashMap<String, Object> getDownSamplingSettings(Class myClass, HashMap<String, Object> dsSettings) { // // Retrieve annotation if (myClass.isAnnotationPresent(Downsample.class)) { final Annotation thisAnnotation = myClass.getAnnotation(Downsample.class); if (thisAnnotation instanceof Downsample) { final Downsample dsAnnotation = (Downsample) thisAnnotation; dsSettings.put("by", dsAnnotation.by().toString()); dsSettings.put("to_cov", dsAnnotation.toCoverage()); } } return dsSettings; }