List of usage examples for java.lang.reflect Field getAnnotation
public <T extends Annotation> T getAnnotation(Class<T> annotationClass)
From source file:net.elsched.utils.SettingsBinder.java
/** * Bind configuration parameters into Guice Module. * //from w w w . java2s. c o m * @return a Guice module configured with setting support. * @throws ConfigurationException * on configuration error */ public static Module bindSettings(String propertiesFileKey, Class<?>... settingsArg) throws ConfigurationException { final CompositeConfiguration config = new CompositeConfiguration(); config.addConfiguration(new SystemConfiguration()); String propertyFile = config.getString(propertiesFileKey); if (propertyFile != null) { config.addConfiguration(new PropertiesConfiguration(propertyFile)); } List<Field> fields = new ArrayList<Field>(); for (Class<?> settings : settingsArg) { fields.addAll(Arrays.asList(settings.getDeclaredFields())); } // Reflect on settings class and absorb settings final Map<Setting, Field> settings = new LinkedHashMap<Setting, Field>(); for (Field field : fields) { if (!field.isAnnotationPresent(Setting.class)) { continue; } // Validate target type SettingTypeValidator typeHelper = supportedSettingTypes.get(field.getType()); if (typeHelper == null || !typeHelper.check(field.getGenericType())) { throw new IllegalArgumentException(field.getType() + " is not one of the supported setting types"); } Setting setting = field.getAnnotation(Setting.class); settings.put(setting, field); } // Now validate them List<String> missingProperties = new ArrayList<String>(); for (Setting setting : settings.keySet()) { if (setting.defaultValue().isEmpty()) { if (!config.containsKey(setting.name())) { missingProperties.add(setting.name()); } } } if (missingProperties.size() > 0) { StringBuilder error = new StringBuilder(); error.append("The following required properties are missing from the server configuration: "); error.append(Joiner.on(", ").join(missingProperties)); } // bundle everything up in an injectable guice module return new AbstractModule() { @Override protected void configure() { // We must iterate the settings a third time when binding. // Note: do not collapse these loops as that will damage // early error detection. The runtime is still O(n) in setting // count. for (Map.Entry<Setting, Field> entry : settings.entrySet()) { Class<?> type = entry.getValue().getType(); Setting setting = entry.getKey(); if (int.class.equals(type)) { Integer defaultValue = null; if (!setting.defaultValue().isEmpty()) { defaultValue = Integer.parseInt(setting.defaultValue()); } bindConstant().annotatedWith(Names.named(setting.name())) .to(config.getInteger(setting.name(), defaultValue)); } else if (boolean.class.equals(type)) { Boolean defaultValue = null; if (!setting.defaultValue().isEmpty()) { defaultValue = Boolean.parseBoolean(setting.defaultValue()); } bindConstant().annotatedWith(Names.named(setting.name())) .to(config.getBoolean(setting.name(), defaultValue)); } else if (String.class.equals(type)) { bindConstant().annotatedWith(Names.named(setting.name())) .to(config.getString(setting.name(), setting.defaultValue())); } else { String[] value = config.getStringArray(setting.name()); if (value.length == 0 && !setting.defaultValue().isEmpty()) { value = setting.defaultValue().split(","); } bind(new TypeLiteral<List<String>>() { }).annotatedWith(Names.named(setting.name())).toInstance(ImmutableList.copyOf(value)); } } } }; }
From source file:cc.kune.wave.server.CustomSettingsBinder.java
/** * Bind configuration parameters into Guice Module. * * @param propertyFile the property file * @param settingsArg the settings arg// w w w .j av a2 s .co m * @return a Guice module configured with setting support. * @throws ConfigurationException on configuration error */ public static Module bindSettings(String propertyFile, Class<?>... settingsArg) throws ConfigurationException { final CompositeConfiguration config = new CompositeConfiguration(); config.addConfiguration(new SystemConfiguration()); config.addConfiguration(new PropertiesConfiguration(propertyFile)); List<Field> fields = new ArrayList<Field>(); for (Class<?> settings : settingsArg) { fields.addAll(Arrays.asList(settings.getDeclaredFields())); } // Reflect on settings class and absorb settings final Map<Setting, Field> settings = new LinkedHashMap<Setting, Field>(); for (Field field : fields) { if (!field.isAnnotationPresent(Setting.class)) { continue; } // Validate target type SettingTypeValidator typeHelper = supportedSettingTypes.get(field.getType()); if (typeHelper == null || !typeHelper.check(field.getGenericType())) { throw new IllegalArgumentException(field.getType() + " is not one of the supported setting types"); } Setting setting = field.getAnnotation(Setting.class); settings.put(setting, field); } // Now validate them List<String> missingProperties = new ArrayList<String>(); for (Setting setting : settings.keySet()) { if (setting.defaultValue().isEmpty()) { if (!config.containsKey(setting.name())) { missingProperties.add(setting.name()); } } } if (missingProperties.size() > 0) { StringBuilder error = new StringBuilder(); error.append("The following required properties are missing from the server configuration: "); error.append(Joiner.on(", ").join(missingProperties)); throw new ConfigurationException(error.toString()); } // bundle everything up in an injectable guice module return new AbstractModule() { @Override protected void configure() { // We must iterate the settings a third time when binding. // Note: do not collapse these loops as that will damage // early error detection. The runtime is still O(n) in setting count. for (Map.Entry<Setting, Field> entry : settings.entrySet()) { Class<?> type = entry.getValue().getType(); Setting setting = entry.getKey(); if (int.class.equals(type)) { Integer defaultValue = null; if (!setting.defaultValue().isEmpty()) { defaultValue = Integer.parseInt(setting.defaultValue()); } bindConstant().annotatedWith(Names.named(setting.name())) .to(config.getInteger(setting.name(), defaultValue)); } else if (boolean.class.equals(type)) { Boolean defaultValue = null; if (!setting.defaultValue().isEmpty()) { defaultValue = Boolean.parseBoolean(setting.defaultValue()); } bindConstant().annotatedWith(Names.named(setting.name())) .to(config.getBoolean(setting.name(), defaultValue)); } else if (String.class.equals(type)) { bindConstant().annotatedWith(Names.named(setting.name())) .to(config.getString(setting.name(), setting.defaultValue())); } else { String[] value = config.getStringArray(setting.name()); if (value.length == 0 && !setting.defaultValue().isEmpty()) { value = setting.defaultValue().split(","); } bind(new TypeLiteral<List<String>>() { }).annotatedWith(Names.named(setting.name())).toInstance(ImmutableList.copyOf(value)); } } } }; }
From source file:com.yukthi.utils.beans.PropertyMapper.java
/** * Checks in the cache if the specified bean type property details is already loaded. If loaded returns the same. If not, builds the property map * caches it and returns it.//from www. jav a 2s. co m * @param beanType Bean types for which property map needs to be fetched * @return Property details of specified bean type */ public static synchronized BeanInfo getBeanInfo(Class<?> beanType) { BeanInfo beanInfo = typeToProp.get(beanType); //if type is already loaded return the same if (beanInfo != null) { return beanInfo; } beanInfo = new BeanInfo(beanType); Field fields[] = null; NestedProperty nestedProp = null; IgnorePropertyDestination ignorePropertyDestination = null; while (!beanType.getName().startsWith("java")) { fields = beanType.getDeclaredFields(); //loop through property descriptors and add to bean property map for (Field field : fields) { try { nestedProp = NestedProperty.getNestedProperty(beanType, field.getName()); } catch (Exception ex) { logger.info("Ignoring {}.{} property, as property fetch resulted in error - {}", beanType.getName(), field.getName(), ex); continue; } ignorePropertyDestination = field.getAnnotation(IgnorePropertyDestination.class); beanInfo.addProperty(new PropertyInfo(nestedProp, ignorePropertyDestination != null)); getMappingsFromField(beanInfo, field); } beanType = beanType.getSuperclass(); } //cache and return property map typeToProp.put(beanType, beanInfo); return beanInfo; }
From source file:com.cloud.api.ApiDispatcher.java
@SuppressWarnings({ "unchecked", "rawtypes" }) public static void processParameters(BaseCmd cmd, Map<String, String> params) { List<Object> entitiesToAccess = new ArrayList<Object>(); Map<String, Object> unpackedParams = cmd.unpackParams(params); cmd = ComponentContext.getTargetObject(cmd); if (cmd instanceof BaseListCmd) { Object pageSizeObj = unpackedParams.get(ApiConstants.PAGE_SIZE); Long pageSize = null;/*from www . java 2 s .c o m*/ if (pageSizeObj != null) { pageSize = Long.valueOf((String) pageSizeObj); } if ((unpackedParams.get(ApiConstants.PAGE) == null) && (pageSize != null && pageSize != BaseListCmd.PAGESIZE_UNLIMITED)) { ServerApiException ex = new ServerApiException(ApiErrorCode.PARAM_ERROR, "\"page\" parameter is required when \"pagesize\" is specified"); ex.setCSErrorCode(CSExceptionErrorCode.getCSErrCode(ex.getClass().getName())); throw ex; } else if (pageSize == null && (unpackedParams.get(ApiConstants.PAGE) != null)) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "\"pagesize\" parameter is required when \"page\" is specified"); } } List<Field> fields = ReflectUtil.getAllFieldsForClass(cmd.getClass(), BaseCmd.class); for (Field field : fields) { Parameter parameterAnnotation = field.getAnnotation(Parameter.class); if ((parameterAnnotation == null) || !parameterAnnotation.expose()) { continue; } //TODO: Annotate @Validate on API Cmd classes, FIXME how to process Validate Validate validateAnnotation = field.getAnnotation(Validate.class); Object paramObj = unpackedParams.get(parameterAnnotation.name()); if (paramObj == null) { if (parameterAnnotation.required()) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Unable to execute API command " + cmd.getCommandName().substring(0, cmd.getCommandName().length() - 8) + " due to missing parameter " + parameterAnnotation.name()); } continue; } // marshall the parameter into the correct type and set the field value try { setFieldValue(field, cmd, paramObj, parameterAnnotation); } catch (IllegalArgumentException argEx) { if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to execute API command " + cmd.getCommandName() + " due to invalid value " + paramObj + " for parameter " + parameterAnnotation.name()); } throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Unable to execute API command " + cmd.getCommandName().substring(0, cmd.getCommandName().length() - 8) + " due to invalid value " + paramObj + " for parameter " + parameterAnnotation.name()); } catch (ParseException parseEx) { if (s_logger.isDebugEnabled()) { s_logger.debug("Invalid date parameter " + paramObj + " passed to command " + cmd.getCommandName().substring(0, cmd.getCommandName().length() - 8)); } throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Unable to parse date " + paramObj + " for command " + cmd.getCommandName().substring(0, cmd.getCommandName().length() - 8) + ", please pass dates in the format mentioned in the api documentation"); } catch (InvalidParameterValueException invEx) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Unable to execute API command " + cmd.getCommandName().substring(0, cmd.getCommandName().length() - 8) + " due to invalid value. " + invEx.getMessage()); } catch (CloudRuntimeException cloudEx) { s_logger.error("CloudRuntimeException", cloudEx); // FIXME: Better error message? This only happens if the API command is not executable, which typically //means // there was // and IllegalAccessException setting one of the parameters. throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Internal error executing API command " + cmd.getCommandName().substring(0, cmd.getCommandName().length() - 8)); } //check access on the resource this field points to try { ACL checkAccess = field.getAnnotation(ACL.class); CommandType fieldType = parameterAnnotation.type(); if (checkAccess != null) { // Verify that caller can perform actions in behalf of vm owner //acumulate all Controlled Entities together. //parse the array of resource types and in case of map check access on key or value or both as specified in @acl //implement external dao for classes that need findByName //for maps, specify access to be checkd on key or value. // find the controlled entity DBid by uuid if (parameterAnnotation.entityType() != null) { Class<?>[] entityList = parameterAnnotation.entityType()[0] .getAnnotation(EntityReference.class).value(); for (Class entity : entityList) { // Check if the parameter type is a single // Id or list of id's/name's switch (fieldType) { case LIST: CommandType listType = parameterAnnotation.collectionType(); switch (listType) { case LONG: case UUID: List<Long> listParam = (List<Long>) field.get(cmd); for (Long entityId : listParam) { Object entityObj = s_instance._entityMgr.findById(entity, entityId); entitiesToAccess.add(entityObj); } break; /* * case STRING: List<String> listParam = * new ArrayList<String>(); listParam = * (List)field.get(cmd); for(String * entityName: listParam){ * ControlledEntity entityObj = * (ControlledEntity * )daoClassInstance(entityId); * entitiesToAccess.add(entityObj); } * break; */ default: break; } break; case LONG: case UUID: Object entityObj = s_instance._entityMgr.findById(entity, (Long) field.get(cmd)); entitiesToAccess.add(entityObj); break; default: break; } if (ControlledEntity.class.isAssignableFrom(entity)) { if (s_logger.isDebugEnabled()) { s_logger.debug("ControlledEntity name is:" + entity.getName()); } } if (InfrastructureEntity.class.isAssignableFrom(entity)) { if (s_logger.isDebugEnabled()) { s_logger.debug("InfrastructureEntity name is:" + entity.getName()); } } } } } } catch (IllegalArgumentException e) { s_logger.error("Error initializing command " + cmd.getCommandName() + ", field " + field.getName() + " is not accessible."); throw new CloudRuntimeException("Internal error initializing parameters for command " + cmd.getCommandName() + " [field " + field.getName() + " is not accessible]"); } catch (IllegalAccessException e) { s_logger.error("Error initializing command " + cmd.getCommandName() + ", field " + field.getName() + " is not accessible."); throw new CloudRuntimeException("Internal error initializing parameters for command " + cmd.getCommandName() + " [field " + field.getName() + " is not accessible]"); } } //check access on the entities. getInstance().doAccessChecks(cmd, entitiesToAccess); }
From source file:com.github.gekoh.yagen.util.FieldInfo.java
private static void addAttributeOverrides(Map<String, String> overrides, String path, Class type) { for (Field field : type.getDeclaredFields()) { String curPath = path + field.getName() + "."; Column column;//from www . ja va2 s . com if (field.isAnnotationPresent(AttributeOverride.class)) { addAttributeOverride(overrides, addNamePrefixToAttributeOverride( formatAnnotation(field.getAnnotation(AttributeOverride.class)), curPath)); } else if (field.isAnnotationPresent(AttributeOverrides.class)) { for (AttributeOverride attributeOverride : field.getAnnotation(AttributeOverrides.class).value()) { addAttributeOverride(overrides, addNamePrefixToAttributeOverride(formatAnnotation(attributeOverride), curPath)); } } else if (((column = field.getAnnotation(Column.class)) != null && (!column.nullable() || column.unique())) || (field.isAnnotationPresent(Basic.class) && !field.getAnnotation(Basic.class).optional())) { String columnName = column != null ? column.name() : field.getName(); int length = column != null ? column.length() : 255; String override = "@javax.persistence.AttributeOverride(name=\"" + path + field.getName() + "\", column=" + "@javax.persistence.Column(name=\"" + columnName + "\", length=" + length + ", nullable=true, unique=false))"; addAttributeOverride(overrides, override); } if (field.isAnnotationPresent(Embedded.class)) { addAttributeOverrides(overrides, curPath, field.getType()); } } }
From source file:com.google.code.siren4j.util.ReflectionUtils.java
/** * Retrieve all fields deemed as Exposed, i.e. they are public or have a public accessor method or are marked by an * annotation to be exposed.//from w w w. jav a 2 s . co m * * @param clazz cannot be <code>null</code>. * @return */ public static List<ReflectedInfo> getExposedFieldInfo(final Class<?> clazz) { List<ReflectedInfo> results = null; try { results = fieldInfoCache.get(clazz, new Callable<List<ReflectedInfo>>() { /** * This method is called if the value is not found in the cache. This * is where the real reflection work is done. */ public List<ReflectedInfo> call() throws Exception { List<ReflectedInfo> exposed = new ArrayList<ReflectedInfo>(); for (Method m : clazz.getMethods()) { if (ReflectionUtils.isGetter(m) && !isIgnored(m)) { Field f = getGetterField(m); if (f != null && !isIgnored(f)) { f.setAccessible(true); Siren4JProperty propAnno = f.getAnnotation(Siren4JProperty.class); String effectiveName = propAnno != null ? StringUtils.defaultIfEmpty(propAnno.name(), f.getName()) : f.getName(); Siren4JSubEntity subAnno = f.getAnnotation(Siren4JSubEntity.class); if (subAnno != null && !ArrayUtils.isEmpty(subAnno.rel())) { effectiveName = subAnno.rel().length == 1 ? subAnno.rel()[0] : ArrayUtils.toString(subAnno.rel()); } exposed.add(new ReflectedInfo(f, m, ReflectionUtils.getSetter(clazz, f), effectiveName)); } } } return exposed; } }); } catch (ExecutionException e) { throw new Siren4JRuntimeException(e); } return results; }
From source file:com.zlfun.framework.excel.ExcelUtils.java
private static <T> void parent(Class<T> parentClass, Set<String> set, List<String> result) { Field[] fs = parentClass.getDeclaredFields(); for (Field f : fs) { WebParam itemField = f.getAnnotation(WebParam.class); if (itemField == null) { continue; }/*from w w w. j av a 2 s . c o m*/ if ("".equals(itemField.value())) { String fname = f.getName(); if (!set.contains(fname)) { set.add(fname); result.add(fname); } } else { String fname = itemField.value(); if (!set.contains(fname)) { set.add(fname); result.add(fname); } } } }
From source file:com.zlfun.framework.excel.ExcelUtils.java
public static <T> List<String> genItemFieldHeader(Class<T> clazz) { Set<String> set = new HashSet<String>(); List<String> result = new ArrayList<String>(); try {/*from w w w . j av a 2 s .c om*/ Field[] fs = clazz.getDeclaredFields(); for (Field f : fs) { WebParam itemField = f.getAnnotation(WebParam.class); if (itemField == null) { continue; } if ("".equals(itemField.value())) { String fname = f.getName(); if (!set.contains(fname)) { set.add(fname); result.add(fname); } } else { String fname = itemField.value(); if (!set.contains(fname)) { set.add(fname); result.add(fname); } } // ? Class<?> parent = clazz.getSuperclass(); while (parent != Object.class) { parent(parent, set, result); parent = parent.getSuperclass(); } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return result; }
From source file:gdv.xport.feld.Feld.java
/** * Ermittelt die FeldInfo aus dem uebergebenen Enum. * * @param feldX the feld x/*from w w w . j av a 2s . c o m*/ * @return the feld info */ protected static FeldInfo getFeldInfo(final Enum<?> feldX) { try { Field field = feldX.getClass().getField(feldX.name()); return field.getAnnotation(FeldInfo.class); } catch (NoSuchFieldException nsfe) { throw new InternalError("no field " + feldX + " (" + nsfe + ")"); } }
From source file:com.streamsets.datacollector.definition.ConfigDefinitionExtractor.java
public static List<String> getGroups(Field field, List<String> parentGroups, Object contextMsg, List<ErrorMessage> errors) { List<String> list = new ArrayList<>(); ConfigDefBean configDefBean = field.getAnnotation(ConfigDefBean.class); if (configDefBean != null) { String[] groups = configDefBean.groups(); if (groups.length > 0) { for (String group : groups) { list.add(resolveGroup(parentGroups, group, contextMsg, errors)); }/* w w w . j a v a 2 s .c o m*/ } else { // no groups in the annotation, we propagate all parent groups then list.addAll(parentGroups); } } else { throw new IllegalArgumentException(Utils.format("{} is not annotated with ConfigDefBean", contextMsg)); } return list; }