List of usage examples for java.lang.reflect Field getAnnotations
public Annotation[] getAnnotations()
From source file:org.apache.syncope.core.persistence.dao.impl.SubjectSearchDAOImpl.java
@SuppressWarnings("rawtypes") private String getQuery(final SubjectCond cond, final boolean not, final List<Object> parameters, final SubjectType type, final SearchSupport svs) { final AttributableUtil attrUtil = AttributableUtil.getInstance(type.asAttributableType()); Field subjectField = ReflectionUtils.findField(attrUtil.attributableClass(), cond.getSchema()); if (subjectField == null) { LOG.warn("Ignoring invalid schema '{}'", cond.getSchema()); return EMPTY_ATTR_QUERY; }//w w w . j a va 2s .c o m AbstractNormalSchema schema = attrUtil.newSchema(); schema.setName(subjectField.getName()); for (AttributeSchemaType attrSchemaType : AttributeSchemaType.values()) { if (subjectField.getType().isAssignableFrom(attrSchemaType.getType())) { schema.setType(attrSchemaType); } } // Deal with subject Integer fields logically mapping to boolean values // (SyncopeRole.inheritAttributes, for example) boolean foundBooleanMin = false; boolean foundBooleanMax = false; if (Integer.class.equals(subjectField.getType())) { for (Annotation annotation : subjectField.getAnnotations()) { if (Min.class.equals(annotation.annotationType())) { foundBooleanMin = ((Min) annotation).value() == 0; } else if (Max.class.equals(annotation.annotationType())) { foundBooleanMax = ((Max) annotation).value() == 1; } } } if (foundBooleanMin && foundBooleanMax) { if ("true".equalsIgnoreCase(cond.getExpression())) { cond.setExpression("1"); schema.setType(AttributeSchemaType.Long); } else if ("false".equalsIgnoreCase(cond.getExpression())) { cond.setExpression("0"); schema.setType(AttributeSchemaType.Long); } } // Deal with subject fields representing relationships to other entities // Only _id and _name are suppored if (subjectField.getType().getAnnotation(Entity.class) != null) { if (BeanUtils.findDeclaredMethodWithMinimalParameters(subjectField.getType(), "getId") != null) { cond.setSchema(cond.getSchema() + "_id"); schema.setType(AttributeSchemaType.Long); } if (BeanUtils.findDeclaredMethodWithMinimalParameters(subjectField.getType(), "getName") != null) { cond.setSchema(cond.getSchema() + "_name"); schema.setType(AttributeSchemaType.String); } } AbstractAttrValue attrValue = attrUtil.newAttrValue(); try { if (cond.getType() != AttributeCond.Type.LIKE && cond.getType() != AttributeCond.Type.ISNULL && cond.getType() != AttributeCond.Type.ISNOTNULL) { schema.getValidator().validate(cond.getExpression(), attrValue); } } catch (ValidationException e) { LOG.error("Could not validate expression '" + cond.getExpression() + "'", e); return EMPTY_ATTR_QUERY; } final StringBuilder query = new StringBuilder("SELECT DISTINCT subject_id FROM ").append(svs.field().name) .append(" WHERE "); fillAttributeQuery(query, attrValue, schema, cond, not, parameters, svs); return query.toString(); }
From source file:org.apache.syncope.core.persistence.jpa.dao.JPASubjectSearchDAO.java
@SuppressWarnings("rawtypes") private String getQuery(final SubjectCond cond, final boolean not, final List<Object> parameters, final SubjectType type, final SearchSupport svs) { final AttributableUtil attrUtil = attrUtilFactory.getInstance(type.asAttributableType()); // Keeps track of difference between entity's getKey() and JPA @Id fields if ("key".equals(cond.getSchema())) { cond.setSchema("id"); }//from w w w .ja v a2s .c o m Field subjectField = ReflectionUtils.findField(attrUtil.attributableClass(), cond.getSchema()); if (subjectField == null) { LOG.warn("Ignoring invalid schema '{}'", cond.getSchema()); return EMPTY_ATTR_QUERY; } PlainSchema schema = attrUtil.newPlainSchema(); schema.setKey(subjectField.getName()); for (AttrSchemaType attrSchemaType : AttrSchemaType.values()) { if (subjectField.getType().isAssignableFrom(attrSchemaType.getType())) { schema.setType(attrSchemaType); } } // Deal with subject Integer fields logically mapping to boolean values // (JPARole.inheritPlainAttrs, for example) boolean foundBooleanMin = false; boolean foundBooleanMax = false; if (Integer.class.equals(subjectField.getType())) { for (Annotation annotation : subjectField.getAnnotations()) { if (Min.class.equals(annotation.annotationType())) { foundBooleanMin = ((Min) annotation).value() == 0; } else if (Max.class.equals(annotation.annotationType())) { foundBooleanMax = ((Max) annotation).value() == 1; } } } if (foundBooleanMin && foundBooleanMax) { schema.setType(AttrSchemaType.Boolean); } // Deal with subject fields representing relationships to other entities if (subjectField.getType().getAnnotation(Entity.class) != null) { Method relMethod = null; try { relMethod = ClassUtils.getPublicMethod(subjectField.getType(), "getKey", new Class[0]); } catch (Exception e) { LOG.error("Could not find {}#getKey", subjectField.getType(), e); } if (relMethod != null) { if (Long.class.isAssignableFrom(relMethod.getReturnType())) { cond.setSchema(cond.getSchema() + "_id"); schema.setType(AttrSchemaType.Long); } if (String.class.isAssignableFrom(relMethod.getReturnType())) { cond.setSchema(cond.getSchema() + "_name"); schema.setType(AttrSchemaType.String); } } } PlainAttrValue attrValue = attrUtil.newPlainAttrValue(); if (cond.getType() != AttributeCond.Type.LIKE && cond.getType() != AttributeCond.Type.ISNULL && cond.getType() != AttributeCond.Type.ISNOTNULL) { try { schema.getValidator().validate(cond.getExpression(), attrValue); } catch (ValidationException e) { LOG.error("Could not validate expression '" + cond.getExpression() + "'", e); return EMPTY_ATTR_QUERY; } } final StringBuilder query = new StringBuilder("SELECT DISTINCT subject_id FROM ").append(svs.field().name) .append(" WHERE "); fillAttributeQuery(query, attrValue, schema, cond, not, parameters, svs); return query.toString(); }
From source file:com.fluidops.iwb.ui.configuration.ConfigurationFormBase.java
/** * Retrieves all {@link FormElementConfig}s for the given configuration class. * //from w w w .j av a2 s . c o m * This is * a) a configuration for each {@link Field} that is annotated with {@link ParameterConfigDoc} * * The elements are sorted according to the rules as defined in {@link #getConfigFieldsSorted(Class)}. * * Note that deprecated fields are only rendered if there exists a preset value for it. * * This method also applies the {@link HiddenIfUnset} annotation concept. * * @param configClass * @return */ List<FormElementConfig> getFormElementConfigurations(Class<?> configClass) { if (configClass.equals(String.class)) return Lists.newArrayList(new FormElementConfig("", FormElementConfig.toParameterConfigDoc("", Type.SIMPLE, true), String.class, presetValues)); List<FormElementConfig> res = Lists.newArrayList(); for (Field f : ConfigurationFormUtil.getConfigFieldsSorted(configClass)) { if (!keepFieldAsFormElement(f)) continue; String fieldName = f.getName(); Class<?> nestedConfigClass = f.getType(); if (List.class.isAssignableFrom(nestedConfigClass)) { // use the list generic type nestedConfigClass = (Class<?>) ((ParameterizedType) f.getGenericType()).getActualTypeArguments()[0]; } Operator formElementDefaultValue = getChildOperator(presetValues, fieldName); FormElementConfig fCfg = new FormElementConfig(fieldName, f.getAnnotation(ParameterConfigDoc.class), nestedConfigClass, formElementDefaultValue); // show deprecated fields only if they have value (bug 10999) if (f.getAnnotation(Deprecated.class) != null) { if (!formElementDefaultValue.isNoop()) fCfg.setDeprecated(true); else continue; } // allow hidden elements which are only shown if a value is set if (f.getAnnotation(HiddenIfUnset.class) != null) { if (formElementDefaultValue.isNoop()) continue; } // remember the annotations in the configuration (for later use) fCfg.addAnnotations(f.getAnnotations()); res.add(fCfg); } return res; }
From source file:org.sinekartads.dto.BaseDTO.java
protected void formatValues(Map<DTOPropertyType, String> dtoPropertyFormats) throws IllegalArgumentException { // Mapping annotation -> dtoPropertyType restricted on the managed annotations Map<Class<? extends Annotation>, DTOPropertyType> annotationTypes = new HashMap<Class<? extends Annotation>, DTOPropertyType>(); for (Map.Entry<DTOPropertyType, String> entry : dtoPropertyFormats.entrySet()) { annotationTypes.put(entry.getKey().getAnnot(), entry.getKey()); }//from ww w . j a va 2 s . com try { String newFormat; DateFormat newDateFormat = null; DateFormat newTimeFormat = null; DateFormat newDateTimeFormat = null; NumberFormat newIntegerFormat = null; NumberFormat newDecimalFormat = null; // create the the custom formatters newFormat = dtoPropertyFormats.get(DTOPropertyType.Date); if (newFormat != null) { newDateFormat = new SimpleDateFormat(newFormat); } newFormat = dtoPropertyFormats.get(DTOPropertyType.Time); if (newFormat != null) { newTimeFormat = new SimpleDateFormat(newFormat); } newFormat = dtoPropertyFormats.get(DTOPropertyType.DateTime); if (newFormat != null) { newDateTimeFormat = new SimpleDateFormat(newFormat); } newFormat = dtoPropertyFormats.get(DTOPropertyType.Integer); if (newFormat != null) { newIntegerFormat = new DecimalFormat(newFormat); } newFormat = dtoPropertyFormats.get(DTOPropertyType.Decimal); if (newFormat != null) { newDecimalFormat = new DecimalFormat(newFormat); } // change formats into the dto and all its children Field[] fields = getClass().getDeclaredFields(); String property; Class<?> fieldType; DTOPropertyType dtoPropertyType; for (Field field : fields) { // ignore the static field if ((field.getModifiers() & java.lang.reflect.Modifier.STATIC) > 0) continue; property = field.getName(); fieldType = field.getType(); if (BaseDTO.class.isAssignableFrom(fieldType)) { // recursion on the children (as single member) BaseDTO dto = (BaseDTO) PropertyUtils.getProperty(this, property); dto.formatValues(dtoPropertyFormats); } else if (BaseDTO[].class.isAssignableFrom(fieldType)) { // recursion on the children (as an array) for (BaseDTO dto : (BaseDTO[]) PropertyUtils.getProperty(this, property)) { dto.formatValues(dtoPropertyFormats); } } else { // format the other (String) values String strValue = (String) PropertyUtils.getProperty(this, property); if (StringUtils.isNotBlank(strValue)) { Object value = null; for (Annotation annot : field.getAnnotations()) { // dtoPropertyType of the current field (or null) dtoPropertyType = annotationTypes.get(annot.annotationType()); // newFormat to be applied to the current field's dtoPropertyType newFormat = dtoPropertyFormats.get(dtoPropertyType); // if not null (the annotation is owned by a managed DtoPropertyType) if (newFormat != null) { // in every managed case, parse the value and apply to it the new format switch (dtoPropertyType) { case Flag: { value = BooleanUtils.toBoolean(strValue); PropertyUtils.setProperty(this, property, value); break; } case Date: { value = dateFormat.parse(strValue); PropertyUtils.setProperty(this, property, newDateFormat.format(value)); break; } case Time: { value = timeFormat.parse(strValue); PropertyUtils.setProperty(this, property, newTimeFormat.format(value)); break; } case DateTime: { value = dateTimeFormat.parse(strValue); PropertyUtils.setProperty(this, property, newDateTimeFormat.format(value)); break; } case Integer: { value = integerFormat.parse(strValue).intValue(); PropertyUtils.setProperty(this, property, newIntegerFormat.format(value)); break; } case Decimal: { value = decimalFormat.parse(strValue); PropertyUtils.setProperty(this, property, newDecimalFormat.format(value)); } default: throw new IllegalArgumentException( "unimplemented format: " + dtoPropertyType.name()); } // end switch } } // non-annotated fields are not modified } } } // update the internal formatters if (newDateFormat != null) dateFormat = newDateFormat; if (newTimeFormat != null) timeFormat = newTimeFormat; if (newDateTimeFormat != null) dateTimeFormat = newDateTimeFormat; if (newIntegerFormat != null) integerFormat = newIntegerFormat; if (newDecimalFormat != null) decimalFormat = newDecimalFormat; } catch (RuntimeException e) { throw e; } catch (Exception e) { // errors that should happen only during the test phase throw new RuntimeException(e); } }
From source file:com.jsmartframework.web.manager.BeanHandler.java
private void finalizeAuthBean(Object bean, HttpServletRequest request, HttpServletResponse response) { executePreDestroy(bean);// w w w.jav a 2 s.c o m AuthBean authBean = bean.getClass().getAnnotation(AuthBean.class); try { for (Field field : HELPER.getBeanFields(bean.getClass())) { if (field.getAnnotations().length > 0) { field.setAccessible(true); if (field.isAnnotationPresent(AuthField.class)) { AuthField authField = field.getAnnotation(AuthField.class); Object value = field.get(bean); if (value != null) { // Return encrypted auth fields as cookies to check if customer is still // logged on next request String cookieValue = AuthEncrypter.encrypt(request, authBean.secretKey(), value); Cookie cookie = getAuthenticationCookie(request, authField.value(), cookieValue, -1); response.addCookie(cookie); } else { // Case value is null we force Cookie deletion on client side Cookie cookie = getAuthenticationCookie(request, authField.value(), null, 0); response.addCookie(cookie); } } field.set(bean, null); } } } catch (Exception ex) { LOGGER.log(Level.SEVERE, "Finalize injection on AuthBean [" + bean + "] failed: " + ex.getMessage()); } request.removeAttribute(HELPER.getClassName(authBean, bean.getClass())); }
From source file:com.jsmartframework.web.manager.BeanHandler.java
private Object initializeAuthBean(String name, HttpServletRequest request) { Object bean = null;//from w w w. j ava 2s .co m try { bean = authBeans.get(name).newInstance(); AuthBean authBean = authBeans.get(name).getAnnotation(AuthBean.class); for (Field field : HELPER.getBeanFields(bean.getClass())) { if (field.getAnnotations().length == 0) { continue; } // Set authentication cookies when initializing @AuthBean if (request != null && field.isAnnotationPresent(AuthField.class)) { AuthField authField = field.getAnnotation(AuthField.class); field.setAccessible(true); String fieldValue = WebUtils.getCookie(request, authField.value()); if (fieldValue != null) { fieldValue = AuthEncrypter.decrypt(request, authBean.secretKey(), fieldValue); } field.set(bean, fieldValue); continue; } // Inject VarMapping case present if (field.isAnnotationPresent(ExposeVar.class)) { Map<?, ?> varMapping = HELPER.getExposeVarMapping(field); if (varMapping != null) { field.setAccessible(true); field.set(bean, varMapping); } } if (initialContext != null && jndiMapping.containsKey(field.getType())) { field.setAccessible(true); field.set(bean, initialContext.lookup(jndiMapping.get(field.getType()))); continue; } if (springContext != null) { String beanName = HELPER.getClassName(field.getType().getSimpleName()); if (springContext.containsBean(beanName) || field.isAnnotationPresent(Qualifier.class)) { field.setAccessible(true); field.set(bean, springContext.getBean(field.getType())); } else if (field.isAnnotationPresent(Value.class)) { String propertyName = field.getAnnotation(Value.class).value(); propertyName = SPRING_VALUE_PATTERN.matcher(propertyName).replaceAll(""); field.setAccessible(true); field.set(bean, springContext.getEnvironment().getProperty(propertyName, field.getType())); } } } executePostConstruct(bean); } catch (Exception ex) { LOGGER.log(Level.SEVERE, "Injection on AuthBean [" + bean + "] failed: " + ex.getMessage()); } return bean; }
From source file:com.odoo.orm.OModel.java
private Boolean validateFieldVersion(Field field) { if (mOdooVersion != null) { Annotation[] annotations = field.getAnnotations(); if (annotations.length > 0) { int versions = 0; for (Annotation annotation : annotations) { if (annotation.annotationType().getDeclaringClass().isAssignableFrom(Odoo.api.class)) { switch (mOdooVersion.getVersion_number()) { case 9: // Checks for v9 if (annotation.annotationType().isAssignableFrom(Odoo.api.v9alpha.class)) { versions++;//from www. ja va 2 s . c o m } break; case 8: // Checks for v8 if (annotation.annotationType().isAssignableFrom(Odoo.api.v8.class)) { versions++; } break; case 7: // Checks for v7 if (annotation.annotationType().isAssignableFrom(Odoo.api.v7.class)) { versions++; } break; } } Class<? extends Annotation> type = annotation.annotationType(); if (type.isAssignableFrom(Odoo.Functional.class) || type.isAssignableFrom(Odoo.onChange.class) || type.isAssignableFrom(Odoo.hasDomainFilter.class)) { versions++; } } return (versions > 0) ? true : false; } return true; } return false; }
From source file:com.jsmartframework.web.manager.BeanHandler.java
void executeInjection(Object object) { try {/* ww w . jav a2s . c om*/ HttpSession session = WebContext.getSession(); HttpServletRequest request = WebContext.getRequest(); for (Field field : HELPER.getBeanFields(object.getClass())) { if (field.getAnnotations().length == 0) { continue; } if (field.isAnnotationPresent(Inject.class)) { WebBean webBean = field.getType().getAnnotation(WebBean.class); if (webBean != null) { field.setAccessible(true); field.set(object, instantiateBean(HELPER.getClassName(webBean, field.getType()), null)); continue; } AuthBean authBean = field.getType().getAnnotation(AuthBean.class); if (authBean != null) { field.setAccessible(true); if (authBean.type() == AuthType.SESSION) { field.set(object, instantiateAuthBean(HELPER.getClassName(authBean, field.getType()), session)); } else if (authBean.type() == AuthType.REQUEST) { field.set(object, instantiateAuthBean(HELPER.getClassName(authBean, field.getType()), request)); } continue; } } // Inject URL Parameters if (field.isAnnotationPresent(QueryParam.class)) { QueryParam queryParam = field.getAnnotation(QueryParam.class); String paramValue = request.getParameter(queryParam.value()); if (paramValue != null) { field.setAccessible(true); field.set(object, ExpressionHandler.EXPRESSIONS.decodeUrl(paramValue)); } continue; } // Inject VarMapping case present if (field.isAnnotationPresent(ExposeVar.class)) { Map<?, ?> varMapping = HELPER.getExposeVarMapping(field); if (varMapping != null) { field.setAccessible(true); field.set(object, varMapping); } } // Inject dependencies if (initialContext != null && jndiMapping.containsKey(field.getType())) { field.setAccessible(true); field.set(object, initialContext.lookup(jndiMapping.get(field.getType()))); continue; } if (springContext != null) { String beanName = HELPER.getClassName(field.getType().getSimpleName()); if (springContext.containsBean(beanName) || field.isAnnotationPresent(Qualifier.class)) { field.setAccessible(true); field.set(object, springContext.getBean(field.getType())); } else if (field.isAnnotationPresent(Value.class)) { String propertyName = field.getAnnotation(Value.class).value(); propertyName = SPRING_VALUE_PATTERN.matcher(propertyName).replaceAll(""); field.setAccessible(true); field.set(object, springContext.getEnvironment().getProperty(propertyName, field.getType())); } } } } catch (Exception ex) { LOGGER.log(Level.SEVERE, "Injection on object [" + object + "] failed", ex); } }
From source file:de.knightsoftnet.validators.rebind.GwtSpecificValidatorCreator.java
private Annotation[] getAnnotations(final PropertyDescriptor ppropertyDescription, final boolean useField) { final Class<?> clazz = this.beanHelper.getClazz(); if (useField) { try {/*from w w w. j ava 2 s . c om*/ final Field field = clazz.getDeclaredField(ppropertyDescription.getPropertyName()); return field.getAnnotations(); } catch (final NoSuchFieldException ignore) { // NOPMD // Expected Case } } else { try { final Method method = clazz.getMethod(asGetter(ppropertyDescription)); return method.getAnnotations(); } catch (final NoSuchMethodException ignore) { // NOPMD // Expected Case } } return NO_ANNOTATIONS; }
From source file:org.batoo.jpa.parser.impl.metadata.type.ManagedTypeMetadatImpl.java
/** * Infers and returns the access type based on all persistence annotations being on fields or methods and parent parent access type. * /*from www . jav a 2 s. c o m*/ * @param parentAccessType * the parent access type * @return the inferred access type * * @since 2.0.0 */ private AccessType inferAccessType(AccessType parentAccessType) { boolean methodsHasAnnotations = false; boolean fieldsHasAnnotations = false; final List<String> alternated = Lists.newArrayList(); final Field[] fields = this.clazz.getDeclaredFields(); final Method[] methods = this.clazz.getDeclaredMethods(); // find the alternated ones with @Access for (final Method m : methods) { // skip static and private methods. final int mods = m.getModifiers(); if (Modifier.isStatic(mods) || !Modifier.isPublic(mods) || m.isBridge() || m.isSynthetic()) { continue; } if ((m.getParameterTypes().length != 0) || (m.getReturnType() == null)) { continue; } final Access access = m.getAnnotation(Access.class); if (access != null) { final String name = m.getName(); if ((m.getReturnType() == boolean.class) && name.startsWith("is")) { alternated.add(StringUtils.capitalize(name.substring(2))); } else if (name.startsWith("get")) { alternated.add(StringUtils.capitalize(name.substring(3))); } } } for (final Field f : fields) { final Access access = f.getAnnotation(Access.class); if (access != null) { alternated.add(StringUtils.capitalize(f.getName())); } } // check methods for (final Method m : methods) { for (final Annotation a : m.getAnnotations()) { // ignore @Access(PROPERTY) if (a instanceof Access) { if (((Access) a).value() != AccessType.PROPERTY) { continue; } } // ignore @Transient if (a instanceof Transient) { continue; } if ((m.getReturnType() == null) || (m.getParameterTypes().length > 0)) { continue; } String name = a.annotationType().getName(); // ignore the listener annotations if (name.startsWith("javax.persistence.Post") || name.startsWith("javax.persistence.Pre")) { continue; } if (name.startsWith("javax.persistence") || name.startsWith("org.batoo.jpa.annotation")) { name = m.getName(); if ((boolean.class == m.getReturnType()) || name.startsWith("is")) { name = name.substring(2); } else if (name.startsWith("get")) { name = name.substring(3); } if (alternated.contains(StringUtils.capitalize(name))) { continue; } methodsHasAnnotations = true; break; } } } // check fields for (final Field f : fields) { for (final Annotation a : f.getAnnotations()) { // ignore @Access(FIELD) if (a instanceof Access) { if (((Access) a).value() != AccessType.FIELD) { continue; } } // ignore @Transient if (a instanceof Transient) { continue; } final String name = a.annotationType().getName(); if (name.startsWith("javax.persistence") || name.startsWith("org.batoo.jpa.annotation")) { if (alternated.contains(StringUtils.capitalize(f.getName()))) { continue; } fieldsHasAnnotations = true; break; } } } if (fieldsHasAnnotations && methodsHasAnnotations) { throw new PersistenceException( "At least one field and one method has persistence annotations: " + this.clazz.getName()); } if (methodsHasAnnotations) { return AccessType.PROPERTY; } if (fieldsHasAnnotations) { return AccessType.FIELD; } if (parentAccessType != null) { return parentAccessType; } return AccessType.FIELD; }