List of usage examples for java.lang.reflect Field isAnnotationPresent
@Override public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass)
From source file:com.jsmartframework.web.manager.BeanHandler.java
private void finalizeInjection(Object bean, Object servletObject) { try {// ww w . j a v a2 s . co m for (Field field : HELPER.getBeanFields(bean.getClass())) { if (field.isAnnotationPresent(Inject.class)) { if (field.getType().isAnnotationPresent(WebBean.class)) { field.setAccessible(true); if (servletObject instanceof HttpServletRequest) { finalizeWebBean(field.get(bean), (HttpServletRequest) servletObject); } else if (servletObject instanceof HttpSession) { finalizeWebBean(field.get(bean), (HttpSession) servletObject); } else if (servletObject instanceof ServletContext) { finalizeWebBean(field.get(bean), (ServletContext) servletObject); } field.set(bean, null); continue; } if (field.getType().isAnnotationPresent(AuthBean.class)) { field.setAccessible(true); field.set(bean, null); continue; } } } } catch (Exception ex) { LOGGER.log(Level.SEVERE, "Finalize injection on WebBean [" + bean + "] failed: " + ex.getMessage()); } }
From source file:org.apache.sqoop.SqoopOptions.java
/** * Return a Properties instance that encapsulates all the "sticky" * state of this SqoopOptions that should be written to a metastore * to restore the job later.//from www . j a v a 2 s. c o m */ public Properties writeProperties() { Properties props = new Properties(); try { Field[] fields = SqoopOptions.class.getDeclaredFields(); for (Field f : fields) { if (f.isAnnotationPresent(StoredAsProperty.class)) { Class typ = f.getType(); StoredAsProperty storedAs = f.getAnnotation(StoredAsProperty.class); String propName = storedAs.value(); if (typ.equals(int.class)) { putProperty(props, propName, Integer.toString(f.getInt(this))); } else if (typ.equals(boolean.class)) { putProperty(props, propName, Boolean.toString(f.getBoolean(this))); } else if (typ.equals(long.class)) { putProperty(props, propName, Long.toString(f.getLong(this))); } else if (typ.equals(String.class)) { putProperty(props, propName, (String) f.get(this)); } else if (typ.equals(Integer.class)) { putProperty(props, propName, f.get(this) == null ? "null" : f.get(this).toString()); } else if (typ.isEnum()) { putProperty(props, propName, f.get(this).toString()); } else { throw new RuntimeException("Could not set property " + propName + " for type: " + typ); } } } } catch (IllegalAccessException iae) { throw new RuntimeException("Illegal access to field in property setter", iae); } if (this.getConf().getBoolean(METASTORE_PASSWORD_KEY, METASTORE_PASSWORD_DEFAULT)) { // If the user specifies, we may store the password in the metastore. putProperty(props, "db.password", this.password); putProperty(props, "db.require.password", "false"); } else if (this.password != null) { // Otherwise, if the user has set a password, we just record // a flag stating that the password will need to be reentered. putProperty(props, "db.require.password", "true"); } else { // No password saved or required. putProperty(props, "db.require.password", "false"); } putProperty(props, "db.column.list", arrayToList(this.columns)); setDelimiterProperties(props, "codegen.input.delimiters", this.inputDelimiters); setDelimiterProperties(props, "codegen.output.delimiters", this.outputDelimiters); setArgArrayProperties(props, "tool.arguments", this.extraArgs); setPropertiesAsNestedProperties(props, "db.connect.params", this.connectionParams); setPropertiesAsNestedProperties(props, "map.column.hive", this.mapColumnHive); setPropertiesAsNestedProperties(props, "map.column.java", this.mapColumnJava); return props; }
From source file:org.apache.sqoop.SqoopOptions.java
@SuppressWarnings("unchecked") /**// w w w . j a v a 2 s . co m * Given a set of properties, load this into the current SqoopOptions * instance. */ public void loadProperties(Properties props) { try { Field[] fields = SqoopOptions.class.getDeclaredFields(); for (Field f : fields) { if (f.isAnnotationPresent(StoredAsProperty.class)) { Class typ = f.getType(); StoredAsProperty storedAs = f.getAnnotation(StoredAsProperty.class); String propName = storedAs.value(); if (typ.equals(int.class)) { f.setInt(this, getIntProperty(props, propName, f.getInt(this))); } else if (typ.equals(boolean.class)) { f.setBoolean(this, getBooleanProperty(props, propName, f.getBoolean(this))); } else if (typ.equals(long.class)) { f.setLong(this, getLongProperty(props, propName, f.getLong(this))); } else if (typ.equals(String.class)) { f.set(this, props.getProperty(propName, (String) f.get(this))); } else if (typ.equals(Integer.class)) { String value = props.getProperty(propName, f.get(this) == null ? "null" : f.get(this).toString()); f.set(this, value.equals("null") ? null : new Integer(value)); } else if (typ.isEnum()) { f.set(this, Enum.valueOf(typ, props.getProperty(propName, f.get(this).toString()))); } else { throw new RuntimeException("Could not retrieve property " + propName + " for type: " + typ); } } } } catch (IllegalAccessException iae) { throw new RuntimeException("Illegal access to field in property setter", iae); } // Now load properties that were stored with special types, or require // additional logic to set. if (getBooleanProperty(props, "db.require.password", false)) { // The user's password was stripped out from the metastore. // Require that the user enter it now. setPasswordFromConsole(); } else { this.password = props.getProperty("db.password", this.password); } if (this.jarDirIsAuto) { // We memoized a user-specific nonce dir for compilation to the data // store. Disregard that setting and create a new nonce dir. String localUsername = System.getProperty("user.name", "unknown"); this.jarOutputDir = getNonceJarDir(tmpDir + "sqoop-" + localUsername + "/compile"); } String colListStr = props.getProperty("db.column.list", null); if (null != colListStr) { this.columns = listToArray(colListStr); } this.inputDelimiters = getDelimiterProperties(props, "codegen.input.delimiters", this.inputDelimiters); this.outputDelimiters = getDelimiterProperties(props, "codegen.output.delimiters", this.outputDelimiters); this.extraArgs = getArgArrayProperty(props, "tool.arguments", this.extraArgs); this.connectionParams = getPropertiesAsNetstedProperties(props, "db.connect.params"); // Loading user mapping this.mapColumnHive = getPropertiesAsNetstedProperties(props, "map.column.hive"); this.mapColumnJava = getPropertiesAsNetstedProperties(props, "map.column.java"); // Delimiters were previously memoized; don't let the tool override // them with defaults. this.areDelimsManuallySet = true; // If we loaded true verbose flag, we need to apply it if (this.verbose) { LoggingUtils.setDebugLevel(); } // Custom configuration options this.invalidIdentifierPrefix = props.getProperty("invalid.identifier.prefix", "_"); }
From source file:com.jsmartframework.web.manager.BeanHandler.java
private void finalizeAuthBean(Object bean, HttpServletRequest request, HttpServletResponse response) { executePreDestroy(bean);//from w w w .j av a2s . 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
void executeInjection(Object object) { try {//from w w w . j a v a 2 s . c o m 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:adalid.core.Project.java
private void annotateModule(Field field) { _annotatedWithProjectModule = field.isAnnotationPresent(ProjectModule.class); if (_annotatedWithProjectModule) { ProjectModule annotation = field.getAnnotation(ProjectModule.class); _menuModule = annotation.menu().toBoolean(_menuModule); _roleModule = annotation.role().toBoolean(_roleModule); _helpFileName = StringUtils.defaultIfBlank(annotation.helpFile(), _helpFileName); }/*www .ja v a 2 s.c o m*/ }
From source file:com.jsmartframework.web.manager.BeanHandler.java
private Object initializeAuthBean(String name, HttpServletRequest request) { Object bean = null;/*from ww w .ja v a2s . 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.eucalyptus.objectstorage.pipeline.binding.ObjectStorageRESTBinding.java
protected List<String> populateObjectList(final GroovyObject obj, final Map.Entry<String, String> paramFieldPair, final Map<String, String> params, final int paramSize) { List<String> failedMappings = new ArrayList<String>(); try {/*from w w w . ja v a 2 s. c o m*/ Field declaredField = obj.getClass().getDeclaredField(paramFieldPair.getValue()); ArrayList theList = (ArrayList) obj.getProperty(paramFieldPair.getValue()); Class genericType = (Class) ((ParameterizedType) declaredField.getGenericType()) .getActualTypeArguments()[0]; // :: simple case: FieldName.# ::// if (String.class.equals(genericType)) { if (params.containsKey(paramFieldPair.getKey())) { theList.add(params.remove(paramFieldPair.getKey())); } else { List<String> keys = Lists.newArrayList(params.keySet()); for (String k : keys) { if (k.matches(paramFieldPair.getKey() + "\\.\\d*")) { theList.add(params.remove(k)); } } } } else if (declaredField.isAnnotationPresent(HttpEmbedded.class)) { HttpEmbedded annoteEmbedded = (HttpEmbedded) declaredField.getAnnotation(HttpEmbedded.class); // :: build the parameter map and call populate object recursively ::// if (annoteEmbedded.multiple()) { String prefix = paramFieldPair.getKey(); List<String> embeddedListFieldNames = new ArrayList<String>(); for (String actualParameterName : params.keySet()) if (actualParameterName.matches(prefix + ".1.*")) embeddedListFieldNames.add(actualParameterName.replaceAll(prefix + ".1.", "")); for (int i = 0; i < paramSize + 1; i++) { boolean foundAll = true; Map<String, String> embeddedParams = new HashMap<String, String>(); for (String fieldName : embeddedListFieldNames) { String paramName = prefix + "." + i + "." + fieldName; if (!params.containsKey(paramName)) { failedMappings.add("Mismatched embedded field: " + paramName); foundAll = false; } else embeddedParams.put(fieldName, params.get(paramName)); } if (foundAll) failedMappings.addAll(populateEmbedded(genericType, embeddedParams, theList)); else break; } } else failedMappings.addAll(populateEmbedded(genericType, params, theList)); } } catch (Exception e1) { failedMappings.add(paramFieldPair.getKey()); } return failedMappings; }
From source file:com.eucalyptus.objectstorage.pipeline.WalrusRESTBinding.java
private List<String> populateObjectList(final GroovyObject obj, final Map.Entry<String, String> paramFieldPair, final Map<String, String> params, final int paramSize) { List<String> failedMappings = new ArrayList<String>(); try {/*from ww w.ja v a 2s. c o m*/ Field declaredField = obj.getClass().getDeclaredField(paramFieldPair.getValue()); ArrayList theList = (ArrayList) obj.getProperty(paramFieldPair.getValue()); Class genericType = (Class) ((ParameterizedType) declaredField.getGenericType()) .getActualTypeArguments()[0]; // :: simple case: FieldName.# ::// if (String.class.equals(genericType)) { if (params.containsKey(paramFieldPair.getKey())) { theList.add(params.remove(paramFieldPair.getKey())); } else { List<String> keys = Lists.newArrayList(params.keySet()); for (String k : keys) { if (k.matches(paramFieldPair.getKey() + "\\.\\d*")) { theList.add(params.remove(k)); } } } } else if (declaredField.isAnnotationPresent(HttpEmbedded.class)) { HttpEmbedded annoteEmbedded = (HttpEmbedded) declaredField.getAnnotation(HttpEmbedded.class); // :: build the parameter map and call populate object recursively ::// if (annoteEmbedded.multiple()) { String prefix = paramFieldPair.getKey(); List<String> embeddedListFieldNames = new ArrayList<String>(); for (String actualParameterName : params.keySet()) if (actualParameterName.matches(prefix + ".1.*")) embeddedListFieldNames.add(actualParameterName.replaceAll(prefix + ".1.", "")); for (int i = 0; i < paramSize + 1; i++) { boolean foundAll = true; Map<String, String> embeddedParams = new HashMap<String, String>(); for (String fieldName : embeddedListFieldNames) { String paramName = prefix + "." + i + "." + fieldName; if (!params.containsKey(paramName)) { failedMappings.add("Mismatched embedded field: " + paramName); foundAll = false; } else embeddedParams.put(fieldName, params.get(paramName)); } if (foundAll) failedMappings.addAll(populateEmbedded(genericType, embeddedParams, theList)); else break; } } else failedMappings.addAll(populateEmbedded(genericType, params, theList)); } } catch (Exception e1) { failedMappings.add(paramFieldPair.getKey()); } return failedMappings; }
From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java
private static void processField(String className, PropertyDescriptor pd, Set<PropertyDescriptor> ids, Set<PropertyDescriptor> collections, Set<PropertyDescriptor> lazys, Set<PropertyDescriptor> eagers, Field f) { if (f.isAnnotationPresent(Id.class)) { ids.add(pd);//from w w w . ja v a 2s . c o m if (f.isAnnotationPresent(GeneratedValue.class)) { generatedIdClasses.add(className); } } OneToMany oneToMany = f.getAnnotation(OneToMany.class); CollectionTable collTable = f.getAnnotation(CollectionTable.class); if (oneToMany != null || collTable != null) { collections.add(pd); } else { ManyToMany manyToMany = f.getAnnotation(ManyToMany.class); if (manyToMany != null) { collections.add(pd); } else if (INakedObject.class.isAssignableFrom(f.getType())) { OneToOne oneToOne = f.getAnnotation(OneToOne.class); if (oneToOne != null) { if (oneToOne.fetch().equals(FetchType.LAZY)) { lazys.add(pd); } else { eagers.add(pd); } } else { ManyToOne manyToOne = f.getAnnotation(ManyToOne.class); if (manyToOne != null) { if (manyToOne.fetch().equals(FetchType.LAZY)) { lazys.add(pd); } else { eagers.add(pd); } } else { Basic basic = f.getAnnotation(Basic.class); if (basic != null) { if (basic.fetch().equals(FetchType.LAZY)) { lazys.add(pd); } else { eagers.add(pd); } } } } } } }