List of usage examples for java.lang.reflect Field getDeclaredAnnotations
public Annotation[] getDeclaredAnnotations()
From source file:org.dasein.persist.PersistentCache.java
static public PersistentCache<? extends CachedItem> getCacheWithSchema( @Nonnull Class<? extends CachedItem> forClass, @Nullable String entityName, @Nonnull String schemaVersion, @Nullable SchemaMapper... mappers) throws PersistenceException { Class<?> cls = forClass; while (!cls.getName().equals(Object.class.getName())) { for (Field field : cls.getDeclaredFields()) { for (Annotation annotation : field.getDeclaredAnnotations()) { if (annotation instanceof Index) { Index idx = (Index) annotation; if (idx.type().equals(IndexType.PRIMARY)) { return getCacheWithSchema(forClass, entityName, field.getName(), schemaVersion, mappers); }/*from w w w. j av a 2 s.c om*/ } } } cls = cls.getSuperclass(); } throw new PersistenceException("No primary key field identified for: " + forClass.getName()); }
From source file:org.seasar.struts.customizer.ActionCustomizer.java
/** * ????// w w w . ja v a 2 s .co m * * * @param actionMapping * * @param validatorResources * */ protected void setupValidator(S2ActionMapping actionMapping, S2ValidatorResources validatorResources) { Map<String, Form> forms = new HashMap<String, Form>(); for (String methodName : actionMapping.getExecuteMethodNames()) { if (actionMapping.getExecuteConfig(methodName).isValidator()) { Form form = new Form(); form.setName(actionMapping.getName() + "_" + methodName); forms.put(methodName, form); } } for (Class<?> clazz = actionMapping.getActionFormBeanDesc().getBeanClass(); clazz != null && clazz != Object.class; clazz = clazz.getSuperclass()) { for (Field field : ClassUtil.getDeclaredFields(clazz)) { for (Annotation anno : field.getDeclaredAnnotations()) { processAnnotation(field.getName(), anno, validatorResources, forms); } } } for (Iterator<Form> i = forms.values().iterator(); i.hasNext();) { validatorResources.addForm(i.next()); } }
From source file:org.dasein.persist.PersistentCache.java
@SuppressWarnings("unchecked") static public PersistentCache<? extends CachedItem> getCacheWithSchema( @Nonnull Class<? extends CachedItem> forClass, @Nullable String alternateEntytName, @Nonnull String primaryKey, @Nonnull String schemaVersion, @Nullable SchemaMapper... mappers) throws PersistenceException { PersistentCache<? extends CachedItem> cache = null; String className = forClass.getName(); synchronized (caches) { cache = caches.get(className);/*from ww w . j a v a 2 s .c o m*/ if (cache != null) { return cache; } } Properties props = new Properties(); try { InputStream is = DaseinSequencer.class.getResourceAsStream(DaseinSequencer.PROPERTIES); if (is != null) { props.load(is); } } catch (Exception e) { logger.error("Problem reading " + DaseinSequencer.PROPERTIES + ": " + e.getMessage(), e); } TreeSet<Key> keys = new TreeSet<Key>(); Class<?> cls = forClass; while (!cls.getName().equals(Object.class.getName())) { for (Field field : cls.getDeclaredFields()) { for (Annotation annotation : field.getDeclaredAnnotations()) { if (annotation instanceof Index) { if (logger.isDebugEnabled()) { logger.debug("Processing Index for: " + cls.getName() + "." + field.getName()); } Index idx = (Index) annotation; if (logger.isDebugEnabled()) { logger.debug("Index is: " + idx); } if (idx.type().equals(IndexType.SECONDARY) || idx.type().equals(IndexType.FOREIGN)) { String keyName = field.getName(); if (idx.multi() != null && idx.multi().length > 0) { if (idx.cascade()) { int len = idx.multi().length; keys.add(new Key(keyName)); for (int i = 0; i < len; i++) { String[] parts = new String[i + 2]; parts[0] = keyName; for (int j = 0; j <= i; j++) { parts[j + 1] = idx.multi()[j]; } keys.add(new Key(parts)); } } else { String[] parts = new String[idx.multi().length + 1]; int i = 1; parts[0] = keyName; for (String name : idx.multi()) { parts[i++] = name; } Key k = new Key(parts); keys.add(k); } } else { Key k; if (idx.type().equals(IndexType.FOREIGN) && !idx.identifies().equals(CachedItem.class)) { k = new Key(idx.identifies(), keyName); } else { k = new Key(keyName); } keys.add(k); } } } } } cls = cls.getSuperclass(); } String propKey = "dsn.persistentCache." + className; String prop; while (cache == null && !propKey.equals("dsn.persistentCache")) { prop = props.getProperty(propKey); if (prop != null) { try { cache = (PersistentCache<? extends CachedItem>) Class.forName(prop).newInstance(); cache.initBase(forClass, alternateEntytName, schemaVersion, mappers, new Key(primaryKey), keys.toArray(new Key[keys.size()])); break; } catch (Throwable t) { logger.error("Unable to load persistence cache " + prop + ": " + t.getMessage()); throw new PersistenceException( "Unable to load persistence cache " + prop + ": " + t.getMessage()); } } int idx = propKey.lastIndexOf('.'); propKey = propKey.substring(0, idx); } if (cache == null) { prop = props.getProperty("dsn.cache.default"); if (prop == null) { throw new PersistenceException("No persistent cache implementations defined."); } try { cache = (PersistentCache<? extends CachedItem>) Class.forName(prop).newInstance(); cache.initBase(forClass, alternateEntytName, schemaVersion, mappers, new Key(primaryKey), keys.toArray(new Key[keys.size()])); } catch (Throwable t) { String err = "Unable to load persistence cache " + prop + ": " + t.getMessage(); logger.error(err, t); throw new PersistenceException(err); } } synchronized (caches) { PersistentCache<? extends CachedItem> c = caches.get(className); if (c != null) { cache = c; } else { caches.put(className, cache); } } return cache; }
From source file:com.impetus.kundera.validation.rules.AttributeConstraintRule.java
@Override public boolean validate(Field f, Object validationObject) { boolean checkvalidation = true; for (Annotation annotation : f.getDeclaredAnnotations()) { AttributeConstraintType eruleType = getERuleType(annotation.annotationType().getSimpleName()); if (eruleType != null) { Object fieldValue = PropertyAccessorHelper.getObject(validationObject, f); switch (eruleType) { case ASSERT_FALSE: checkvalidation = validateFalse(fieldValue, annotation); break; case ASSERT_TRUE: checkvalidation = validateTrue(fieldValue, annotation); break; case DECIMAL_MAX: checkvalidation = validateMaxDecimal(fieldValue, annotation); break; case DECIMAL_MIN: checkvalidation = validateMinDecimal(fieldValue, annotation); break; case DIGITS: checkvalidation = validateDigits(fieldValue, annotation); break; case FUTURE: checkvalidation = validateFuture(fieldValue, annotation); break; case MAX: checkvalidation = validateMaxValue(fieldValue, annotation); break; case MIN: checkvalidation = validateMinValue(fieldValue, annotation); break; case NOT_NULL: checkvalidation = validateNotNull(fieldValue, annotation); break; case NULL: checkvalidation = validateNull(fieldValue, annotation); break; case PAST: checkvalidation = validatePast(fieldValue, annotation); break; case PATTERN: checkvalidation = validatePattern(fieldValue, annotation); break; case SIZE: checkvalidation = validateSize(fieldValue, annotation); break; }/* w w w. j a v a2s . co m*/ } } return checkvalidation; }
From source file:org.finra.herd.dao.impl.AbstractHerdDao.java
/** * Updates the audit fields if the entity is of type AuditableEntity. * * @param entity the entity//from w ww .j a va 2s .c o m * @param <T> the type of entity */ @SuppressWarnings("rawtypes") private <T> void updateAuditFields(T entity) { if (entity instanceof AuditableEntity) { AuditableEntity auditableEntity = (AuditableEntity) entity; // Get the currently logged in username. String username = herdDaoSecurityHelper.getCurrentUsername(); // Always set the updated by field, but only set the created by field when it is null (i.e. this is a new record). if (auditableEntity.getCreatedBy() == null) { auditableEntity.setCreatedBy(username); } auditableEntity.setUpdatedBy(username); // Always set the updated on field to the current time, but only update the created on field when it is null (i.e. the first time). Timestamp currentTime = new Timestamp(System.currentTimeMillis()); auditableEntity.setUpdatedOn(currentTime); if (auditableEntity.getCreatedOn() == null) { auditableEntity.setCreatedOn(currentTime); } } // Try to update children one-to-many cascadable auditable entities. // Note that this assumes that OneToMany annotations are done on the field (as opposed to the method) and that all OneToMany fields are collections. // This approach also assumes that there are loops where children refer back to our entity (i.e. an infinite loop). // If there are other scenarios, we should modify this code to handle them. // Loop through all the fields of this entity. for (Field field : entity.getClass().getDeclaredFields()) { // Get all the annotations for the field. for (Annotation annotation : field.getDeclaredAnnotations()) { // Only look for OneToMany that cascade with "persist" or "merge". if (annotation instanceof OneToMany) { OneToMany oneToManyAnnotation = (OneToMany) annotation; List<CascadeType> cascadeTypes = new ArrayList<>(Arrays.asList(oneToManyAnnotation.cascade())); if ((cascadeTypes.contains(CascadeType.ALL)) || (cascadeTypes.contains(CascadeType.PERSIST)) || cascadeTypes.contains(CascadeType.MERGE)) { try { // Modify the accessibility to true so we can get the field (even if it's private) and get the value of the field for our entity. field.setAccessible(true); Object fieldValue = field.get(entity); // If the field is a collection (which OneToMany annotated fields should be), then iterate through the collection and look for // child auditable entities. if (fieldValue instanceof Collection) { Collection collection = (Collection) fieldValue; for (Object object : collection) { if (object instanceof AuditableEntity) { // We found a child auditable entity so recurse to update it's audit fields as well. updateAuditFields(object); } } } } catch (IllegalAccessException ex) { // Because we're setting accessible to true above, we shouldn't get here. throw new IllegalStateException("Unable to get field value for field \"" + field.getName() + "\" due to access restriction.", ex); } } } } } }
From source file:com.cnd.greencube.server.dao.jdbc.JdbcDAO.java
@SuppressWarnings("rawtypes") private Column2Property getIdFromObject(Class clazz) throws Exception { // ???//from w w w. ja v a 2s.c om for (Field field : clazz.getDeclaredFields()) { String columnName = null; Annotation[] annotations = field.getDeclaredAnnotations(); for (Annotation a : annotations) { if (a instanceof Id) { PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz); Column2Property c = new Column2Property(); c.propertyName = pd.getName(); c.setterMethodName = pd.getWriteMethod().getName(); c.getterMethodName = pd.getReadMethod().getName(); c.columnName = columnName; return c; } } } return null; }
From source file:cn.edu.zafu.corepage.base.BaseActivity.java
/** * ???/*from www .ja va 2 s .c o m*/ * * @param savedInstanceState Bundle */ private void loadActivitySavedData(Bundle savedInstanceState) { Field[] fields = this.getClass().getDeclaredFields(); Field.setAccessible(fields, true); Annotation[] ans; for (Field f : fields) { ans = f.getDeclaredAnnotations(); for (Annotation an : ans) { if (an instanceof SaveWithActivity) { try { String fieldName = f.getName(); @SuppressWarnings("rawtypes") Class cls = f.getType(); if (cls == int.class || cls == Integer.class) { f.setInt(this, savedInstanceState.getInt(fieldName)); } else if (String.class.isAssignableFrom(cls)) { f.set(this, savedInstanceState.getString(fieldName)); } else if (Serializable.class.isAssignableFrom(cls)) { f.set(this, savedInstanceState.getSerializable(fieldName)); } else if (cls == long.class || cls == Long.class) { f.setLong(this, savedInstanceState.getLong(fieldName)); } else if (cls == short.class || cls == Short.class) { f.setShort(this, savedInstanceState.getShort(fieldName)); } else if (cls == boolean.class || cls == Boolean.class) { f.setBoolean(this, savedInstanceState.getBoolean(fieldName)); } else if (cls == byte.class || cls == Byte.class) { f.setByte(this, savedInstanceState.getByte(fieldName)); } else if (cls == char.class || cls == Character.class) { f.setChar(this, savedInstanceState.getChar(fieldName)); } else if (CharSequence.class.isAssignableFrom(cls)) { f.set(this, savedInstanceState.getCharSequence(fieldName)); } else if (cls == float.class || cls == Float.class) { f.setFloat(this, savedInstanceState.getFloat(fieldName)); } else if (cls == double.class || cls == Double.class) { f.setDouble(this, savedInstanceState.getDouble(fieldName)); } else if (String[].class.isAssignableFrom(cls)) { f.set(this, savedInstanceState.getStringArray(fieldName)); } else if (Parcelable.class.isAssignableFrom(cls)) { f.set(this, savedInstanceState.getParcelable(fieldName)); } else if (Bundle.class.isAssignableFrom(cls)) { f.set(this, savedInstanceState.getBundle(fieldName)); } } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } } } }
From source file:com.maomao.framework.dao.jdbc.JdbcDAO.java
@SuppressWarnings("rawtypes") private Column2Property getIdFromObject(Class clazz) throws Exception { // ???//from w ww . j av a2s . c o m Column2Property c = null; for (Field field : clazz.getDeclaredFields()) { String columnName = null; Annotation[] annotations = field.getDeclaredAnnotations(); for (Annotation a : annotations) { if (a instanceof Id) { PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz); c = new Column2Property(); c.propertyName = pd.getName(); c.setterMethodName = pd.getWriteMethod().getName(); c.getterMethodName = pd.getReadMethod().getName(); c.columnName = columnName; break; } } } if (c == null) { Class superClass = clazz.getSuperclass(); for (Field field : superClass.getDeclaredFields()) { String columnName = null; Annotation[] annotations = field.getDeclaredAnnotations(); for (Annotation a : annotations) { if (a instanceof Id) { PropertyDescriptor pd = new PropertyDescriptor(field.getName(), superClass); c = new Column2Property(); c.propertyName = pd.getName(); c.setterMethodName = pd.getWriteMethod().getName(); c.getterMethodName = pd.getReadMethod().getName(); c.columnName = columnName; break; } } } } return c; }
From source file:cn.edu.zafu.corepage.base.BaseActivity.java
/** * ??//from w w w. ja va 2 s .com * * @param outState Bundle */ @Override protected void onSaveInstanceState(Bundle outState) { Field[] fields = this.getClass().getDeclaredFields(); Field.setAccessible(fields, true); Annotation[] ans; for (Field f : fields) { ans = f.getDeclaredAnnotations(); for (Annotation an : ans) { if (an instanceof SaveWithActivity) { try { Object o = f.get(this); if (o == null) { continue; } String fieldName = f.getName(); if (o instanceof Integer) { outState.putInt(fieldName, f.getInt(this)); } else if (o instanceof String) { outState.putString(fieldName, (String) f.get(this)); } else if (o instanceof Long) { outState.putLong(fieldName, f.getLong(this)); } else if (o instanceof Short) { outState.putShort(fieldName, f.getShort(this)); } else if (o instanceof Boolean) { outState.putBoolean(fieldName, f.getBoolean(this)); } else if (o instanceof Byte) { outState.putByte(fieldName, f.getByte(this)); } else if (o instanceof Character) { outState.putChar(fieldName, f.getChar(this)); } else if (o instanceof CharSequence) { outState.putCharSequence(fieldName, (CharSequence) f.get(this)); } else if (o instanceof Float) { outState.putFloat(fieldName, f.getFloat(this)); } else if (o instanceof Double) { outState.putDouble(fieldName, f.getDouble(this)); } else if (o instanceof String[]) { outState.putStringArray(fieldName, (String[]) f.get(this)); } else if (o instanceof Parcelable) { outState.putParcelable(fieldName, (Parcelable) f.get(this)); } else if (o instanceof Serializable) { outState.putSerializable(fieldName, (Serializable) f.get(this)); } else if (o instanceof Bundle) { outState.putBundle(fieldName, (Bundle) f.get(this)); } } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } } } super.onSaveInstanceState(outState); }
From source file:ru.gkpromtech.exhibition.db.Table.java
public String getCreateQuery() throws InvalidPropertiesFormatException { String query = "CREATE TABLE " + mTableName + " ("; for (int i = 0; i < mFields.length; ++i) { Field field = mFields[i]; if (i != 0) query += ","; query += "\n " + field.getName() + " " + getSqlType(mType[i]); String clauses = ""; boolean isNull = false; boolean isTr = false; boolean isAutoincrement = false; for (Annotation annotation : field.getDeclaredAnnotations()) { if (annotation instanceof Null) { isNull = true;//from w w w . jav a 2 s. co m } else if (annotation instanceof Translatable) { isTr = true; } else if (annotation instanceof FK) { FK refs = (FK) annotation; clauses += " REFERENCES " + refs.entity().getAnnotation(TableRef.class).name() + "(" + refs.field() + ")"; if (!refs.onDelete().isEmpty()) clauses += " ON DELETE " + refs.onDelete(); if (!refs.onUpdate().isEmpty()) clauses += " ON UPDATE " + refs.onUpdate(); } else if (annotation instanceof PK) { clauses += " PRIMARY KEY"; if (isAutoincrement) clauses += " AUTOINCREMENT"; } else if (annotation instanceof Autoincrement) { isAutoincrement = true; } else if (annotation instanceof Unique) { clauses += " UNIQUE"; } else if (annotation instanceof Default) { clauses += " DEFAULT('" + ((Default) annotation).value() + "')"; } else { throw new InvalidPropertiesFormatException( "Unsupported annotation [" + annotation.getClass().getCanonicalName() + "] for entity [" + mEntityClass.getCanonicalName() + "]"); } } if (!isNull && !isTr) query += " NOT"; query += " NULL" + clauses; } query += ");"; return query; }