List of usage examples for java.beans PropertyDescriptor getWriteMethod
public synchronized Method getWriteMethod()
From source file:org.springmodules.validation.bean.conf.loader.annotation.AnnotationBeanValidationConfigurationLoader.java
/** * Handles all the property level annotations of the given class and manipulates the given validation configuration * accordingly. The property level annotations can either be placed on the <code>setter</code> methods of the * properties or on the appropriate class fields. * * @param clazz The annotated class./*from w ww .j av a2s . c om*/ * @param configuration The bean validation configuration to mainpulate. */ protected void handlePropertyAnnotations(Class clazz, MutableBeanValidationConfiguration configuration) { // extracting & handling all property annotation placed on property fields List<Field> fields = extractFieldFromClassHierarchy(clazz); for (Field field : fields) { String fieldName = field.getName(); PropertyDescriptor descriptor = BeanUtils.getPropertyDescriptor(clazz, fieldName); if (descriptor != null) { Annotation[] annotations = field.getAnnotations(); handleProprtyAnnotations(annotations, clazz, descriptor, configuration); } } // extracting & handling all property annotations placed on property setters PropertyDescriptor[] descriptors = BeanUtils.getPropertyDescriptors(clazz); for (PropertyDescriptor descriptor : descriptors) { Method writeMethod = descriptor.getWriteMethod(); if (writeMethod == null) { continue; } Annotation[] annotations = writeMethod.getAnnotations(); handleProprtyAnnotations(annotations, clazz, descriptor, configuration); } }
From source file:com.expedia.tesla.compiler.plugins.JavaTypeMapper.java
/** * Generate Tesla schema from Java class by reflection. * <p>//from w w w . ja v a 2 s. c om * Tesla can generate schema from existing Java classes that follow the * JavaBeans Spec. Only properties with following attributes will be * included: * <li>public accessible.</li> * <li>writable (has both getter and setter).</li> * <li>has no {@code SkipField} annotation.</li> * <p> * Tesla will map Java type to it's closest Tesla type by default. * Developers can override this by either providing their own * {@code TypeMapper}, or with Tesla annoations. * <p> * Tesla will map all Java object types to nullable types only for class * properties. If you want an property to be not nullable, use annotation * {@code NotNullable}. * * @param schemaBuilder * All non-primitive Tesla types must be defined inside a schema. * This is the schema object into which the Tesla type will be * generated. * * @param javaType * The java class object. * * @return The Tesla type created from the java class by reflection. * * @throws TeslaSchemaException */ public Type fromJavaClass(Schema.SchemaBuilder schemaBuilder, java.lang.Class<?> javaType) throws TeslaSchemaException { String className = javaType.getCanonicalName(); if (className == null) { throw new TeslaSchemaException( String.format("Tesla cannot generate schema for local class '%s'.", javaType.getName())); } String classTypeId = Class.nameToId(className); Class clss = (Class) schemaBuilder.findType(classTypeId); if (clss != null) { return clss; } clss = (Class) schemaBuilder.addType(classTypeId); Class superClass = null; java.lang.Class<?> base = javaType.getSuperclass(); if (base != null && base != java.lang.Object.class) { superClass = (Class) fromJavaClass(schemaBuilder, javaType.getSuperclass()); } List<Field> fields = new ArrayList<>(); for (PropertyDescriptor propDesc : PropertyUtils.getPropertyDescriptors(javaType)) { Type fieldType = null; String fieldName = propDesc.getName(); Method readMethod = propDesc.getReadMethod(); Method writeMethod = propDesc.getWriteMethod(); // Ignore the property it missing getter or setter method. if (writeMethod == null || readMethod == null) { continue; } if ((superClass != null && superClass.hasField(fieldName)) || clss.hasField(fieldName)) { continue; } // Ignore the property if it is annotated with "SkipField". if (readMethod.getAnnotation(com.expedia.tesla.schema.annotation.SkipField.class) != null) { continue; } com.expedia.tesla.schema.annotation.TypeId tidAnnotation = readMethod .getAnnotation(com.expedia.tesla.schema.annotation.TypeId.class); String typeId = null; if (tidAnnotation != null) { typeId = tidAnnotation.value(); } java.lang.reflect.Type propType = readMethod.getGenericReturnType(); fieldType = fromJava(schemaBuilder, propType); if (typeId != null) { fieldType = schemaBuilder.addType(typeId); } else { if (!(propType instanceof java.lang.Class<?> && ((java.lang.Class<?>) propType).isPrimitive())) { fieldType = schemaBuilder.addType(String.format("nullable<%s>", fieldType.getTypeId())); } com.expedia.tesla.schema.annotation.NotNullable anntNotNullable = readMethod .getAnnotation(com.expedia.tesla.schema.annotation.NotNullable.class); com.expedia.tesla.schema.annotation.Nullable anntNullable = readMethod .getAnnotation(com.expedia.tesla.schema.annotation.Nullable.class); if (anntNotNullable != null && anntNullable != null) { throw new TeslaSchemaException(String.format( "Property '%' of class '%s' has conflict annotations." + "'NotNullable' and 'Nullable'", fieldName)); } if (fieldType.isNullable() && anntNotNullable != null) { fieldType = ((Nullable) fieldType).getElementType(); } if (!fieldType.isReference() && readMethod.getAnnotation(com.expedia.tesla.schema.annotation.Reference.class) != null) { fieldType = schemaBuilder.addType(String.format("reference<%s>", fieldType.getTypeId())); } } com.expedia.tesla.schema.annotation.FieldName fnAnnotation = readMethod .getAnnotation(com.expedia.tesla.schema.annotation.FieldName.class); if (fnAnnotation != null) { fieldName = fnAnnotation.value(); } String fieldDisplayName = propDesc.getDisplayName(); String getter = readMethod.getName(); String setter = propDesc.getWriteMethod().getName(); com.expedia.tesla.schema.annotation.DisplayName dnAnnotation = readMethod .getAnnotation(com.expedia.tesla.schema.annotation.DisplayName.class); if (dnAnnotation != null) { fieldDisplayName = dnAnnotation.value(); } java.util.Map<String, String> attributes = new java.util.HashMap<String, String>(); attributes.put("getter", getter); attributes.put("setter", setter); fields.add(new Field(fieldName, fieldDisplayName, fieldType, attributes, null)); } clss.define(superClass == null ? null : Arrays.asList(new Class[] { superClass }), fields, null); return clss; }
From source file:org.neovera.jdiablo.internal.BuilderImpl.java
private List<OptionPropertySpi> buildOptions(final Class<?> claz, Object instance) { List<OptionPropertySpi> list = new ArrayList<OptionPropertySpi>(); Class<?> clz = claz;// ww w . j a va2 s. c o m while (clz != null) { for (Field field : clz.getDeclaredFields()) { Option option = field.getAnnotation(Option.class); if (option != null) { String fieldName = field.getName(); if (fieldName.startsWith("_")) { fieldName = fieldName.substring(1); } Method method = BeanUtils.getWriteMethod(fieldName, clz); if (method != null) { OptionPropertySpi po = new OptionPropertyImpl(); po.setOption(option); po.setPropertyName(fieldName); po.setSetterMethod(method); list.add(po); } else { _logger.error("No setter method for " + fieldName); } } } // for (Field field : ... PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(clz); for (Method method : clz.getDeclaredMethods()) { Option option = method.getAnnotation(Option.class); if (option != null) { for (PropertyDescriptor propertyDescriptor : descriptors) { if (propertyDescriptor.getReadMethod() != null && propertyDescriptor.getReadMethod().equals(method)) { String fieldName = propertyDescriptor.getName(); if (propertyDescriptor.getWriteMethod() == null) { _logger.error("No setter method for {}" + fieldName); } else { OptionPropertySpi po = new OptionPropertyImpl(); po.setOption(option); po.setPropertyName(fieldName); po.setSetterMethod(propertyDescriptor.getWriteMethod()); list.add(po); } // end else break; } } // for (PropertyDescriptor ... } } // for (Method method : ... clz = clz.getSuperclass(); } return list; }
From source file:com.espertech.esperio.csv.CSVInputAdapter.java
private Map<String, Object> constructPropertyTypes(String eventTypeName, Map<String, Object> propertyTypesGiven, EventAdapterService eventAdapterService) { Map<String, Object> propertyTypes = new HashMap<String, Object>(); EventType eventType = eventAdapterService.getExistsTypeByName(eventTypeName); if (eventType == null) { if (propertyTypesGiven != null) { eventAdapterService.addNestableMapType(eventTypeName, new HashMap<String, Object>(propertyTypesGiven), null, true, true, true, false, false); }/*from w w w . jav a2 s. c o m*/ return propertyTypesGiven; } if (!eventType.getUnderlyingType().equals(Map.class)) { beanClass = eventType.getUnderlyingType(); } if (propertyTypesGiven != null && eventType.getPropertyNames().length != propertyTypesGiven.size()) { // allow this scenario for beans as we may want to bring in a subset of properties if (beanClass != null) { return propertyTypesGiven; } else { throw new EPException("Event type " + eventTypeName + " has already been declared with a different number of parameters"); } } for (String property : eventType.getPropertyNames()) { Class type; try { type = eventType.getPropertyType(property); } catch (PropertyAccessException e) { // thrown if trying to access an invalid property on an EventBean throw new EPException(e); } if (propertyTypesGiven != null && propertyTypesGiven.get(property) == null) { throw new EPException( "Event type " + eventTypeName + "has already been declared with different parameters"); } if (propertyTypesGiven != null && !propertyTypesGiven.get(property).equals(type)) { throw new EPException("Event type " + eventTypeName + "has already been declared with a different type for property " + property); } // we can't set read-only properties for bean if (!eventType.getUnderlyingType().equals(Map.class)) { PropertyDescriptor[] pds = ReflectUtils.getBeanProperties(beanClass); PropertyDescriptor pd = null; for (PropertyDescriptor p : pds) { if (p.getName().equals(property)) pd = p; } if (pd == null) { continue; } if (pd.getWriteMethod() == null) { if (propertyTypesGiven == null) { continue; } else { throw new EPException( "Event type " + eventTypeName + "property " + property + " is read only"); } } } propertyTypes.put(property, type); } // flatten nested types Map<String, Object> flattenPropertyTypes = new HashMap<String, Object>(); for (String p : propertyTypes.keySet()) { Object type = propertyTypes.get(p); if (type instanceof Class && ((Class) type).getName().equals("java.util.Map") && eventType instanceof MapEventType) { MapEventType mapEventType = (MapEventType) eventType; Map<String, Object> nested = (Map) mapEventType.getTypes().get(p); for (String nestedProperty : nested.keySet()) { flattenPropertyTypes.put(p + "." + nestedProperty, nested.get(nestedProperty)); } } else if (type instanceof Class) { Class c = (Class) type; if (!c.isPrimitive() && !c.getName().startsWith("java")) { PropertyDescriptor[] pds = ReflectUtils.getBeanProperties(c); for (PropertyDescriptor pd : pds) { if (pd.getWriteMethod() != null) flattenPropertyTypes.put(p + "." + pd.getName(), pd.getPropertyType()); } } else { flattenPropertyTypes.put(p, type); } } else { flattenPropertyTypes.put(p, type); } } return flattenPropertyTypes; }
From source file:org.thiesen.helenaorm.HelenaDAO.java
private boolean safeIsAnnotationPresent(final PropertyDescriptor d, final Class<? extends Annotation> annotation) { return nullSafeAnnotationPresent(annotation, _fields.get(d.getName())) || nullSafeAnnotationPresent(annotation, d.getReadMethod()) || nullSafeAnnotationPresent(annotation, d.getWriteMethod()); }
From source file:com.nway.spring.jdbc.bean.JavassistBeanProcessor.java
private <T> T createBeanByJavassist(ResultSet rs, Class<T> mappedClass, String key) throws SQLException { DbBeanFactory dynamicRse = DBBEANFACTORY_CACHE.get(key); // //w ww . ja v a2s. c om if (dynamicRse != null) { return dynamicRse.createBean(rs, mappedClass); } T bean = this.newInstance(mappedClass); ResultSetMetaData rsmd = rs.getMetaData(); PropertyDescriptor[] props = BeanUtils.getPropertyDescriptors(mappedClass); int[] columnToProperty = this.mapColumnsToProperties(rsmd, props); StringBuilder handlerScript = new StringBuilder(); handlerScript.append("{").append(mappedClass.getName()).append(" bean = new ").append(mappedClass.getName()) .append("();\n"); PropertyDescriptor desc = null; for (int i = 1; i < columnToProperty.length; i++) { if (columnToProperty[i] == PROPERTY_NOT_FOUND) { continue; } desc = props[columnToProperty[i]]; Class<?> propType = desc.getPropertyType(); Object value = processColumn(rs, i, propType, desc.getWriteMethod().getName(), handlerScript); this.callSetter(bean, desc, value); } handlerScript.append("return bean;"); handlerScript.append("}"); try { ClassPool classPool = ClassPool.getDefault(); classPool.appendClassPath(new LoaderClassPath(ClassUtils.getDefaultClassLoader())); CtClass ctHandler = classPool.makeClass(DynamicClassUtils.getBeanProcessorName(mappedClass)); ctHandler.setSuperclass(classPool.get("com.nway.spring.jdbc.bean.DbBeanFactory")); CtMethod mapRow = CtNewMethod.make( "public Object createBean(java.sql.ResultSet rs, Class type) throws java.sql.SQLException{return null;}", ctHandler); mapRow.setGenericSignature("<T:Ljava/lang/Object;>(Ljava/sql/ResultSet;Ljava/lang/Class<TT;>;)TT;"); mapRow.setBody(handlerScript.toString()); ctHandler.addMethod(mapRow); DBBEANFACTORY_CACHE.put(key, (DbBeanFactory) ctHandler.toClass().newInstance()); } catch (Exception e) { throw new DynamicObjectException("javassist [ " + mappedClass.getName() + " ] ", e); } return bean; }
From source file:net.sf.qooxdoo.rpc.RemoteCallUtils.java
/** * Converts JSON types to "normal" java types. * * @param obj the object to convert (must not be * <code>null</code>, but can be * <code>JSONObject.NULL</code>). * @param targetType the desired target type (must not be * <code>null</code>). * * @return the converted object./*from w ww . j a v a 2 s . c o m*/ * * @exception IllegalArgumentException thrown if the desired * conversion is not possible. */ public Object toJava(Object obj, Class targetType) { try { if (obj == JSONObject.NULL) { if (targetType == Integer.TYPE || targetType == Double.TYPE || targetType == Boolean.TYPE || targetType == Long.TYPE || targetType == Float.TYPE) { // null does not work for primitive types throw new Exception(); } return null; } if (obj instanceof JSONArray) { Class componentType; if (targetType == null || targetType == Object.class) { componentType = null; } else { componentType = targetType.getComponentType(); } JSONArray jsonArray = (JSONArray) obj; int length = jsonArray.length(); Object retVal = Array.newInstance((componentType == null ? Object.class : componentType), length); for (int i = 0; i < length; ++i) { Array.set(retVal, i, toJava(jsonArray.get(i), componentType)); } return retVal; } if (obj instanceof JSONObject) { JSONObject jsonObject = (JSONObject) obj; JSONArray names = jsonObject.names(); if (targetType == Map.class || targetType == HashMap.class || targetType == null || targetType == Object.class) { HashMap retVal = new HashMap(); if (names != null) { int length = names.length(); String name; for (int i = 0; i < length; ++i) { name = names.getString(i); retVal.put(name, toJava(jsonObject.get(name), null)); } } return retVal; } Object bean; String requestedTypeName = jsonObject.optString("class", null); if (requestedTypeName != null) { Class clazz = resolveClassHint(requestedTypeName, targetType); if (clazz == null || !targetType.isAssignableFrom(clazz)) { throw new Exception(); } bean = clazz.newInstance(); // TODO: support constructor parameters } else { bean = targetType.newInstance(); } if (names != null) { int length = names.length(); String name; PropertyDescriptor desc; for (int i = 0; i < length; ++i) { name = names.getString(i); if (!"class".equals(name)) { desc = PropertyUtils.getPropertyDescriptor(bean, name); if (desc != null && desc.getWriteMethod() != null) { PropertyUtils.setSimpleProperty(bean, name, toJava(jsonObject.get(name), desc.getPropertyType())); } } } } return bean; } if (targetType == null || targetType == Object.class) { return obj; } Class actualTargetType; Class sourceType = obj.getClass(); if (targetType == Integer.TYPE) { actualTargetType = Integer.class; } else if (targetType == Boolean.TYPE) { actualTargetType = Boolean.class; } else if ((targetType == Double.TYPE || targetType == Double.class) && Number.class.isAssignableFrom(sourceType)) { return new Double(((Number) obj).doubleValue()); // TODO: maybe return obj directly if it's a Double } else if ((targetType == Float.TYPE || targetType == Float.class) && Number.class.isAssignableFrom(sourceType)) { return new Float(((Number) obj).floatValue()); } else if ((targetType == Long.TYPE || targetType == Long.class) && Number.class.isAssignableFrom(sourceType)) { return new Long(((Number) obj).longValue()); } else { actualTargetType = targetType; } if (!actualTargetType.isAssignableFrom(sourceType)) { throw new Exception(); } return obj; } catch (IllegalArgumentException e) { throw e; } catch (Exception e) { throw new IllegalArgumentException("Cannot convert " + (obj == null ? null : obj.getClass().getName()) + " to " + (targetType == null ? null : targetType.getName())); } }
From source file:com.boylesoftware.web.impl.UserInputControllerMethodArgHandler.java
@Override public boolean prepareUserInput(final RouterRequest request) throws ServletException { boolean success = false; final PoolableUserInput pooledUserInput = this.beanPool.getSync(); try {/*from w w w . ja v a 2s.co m*/ request.setAttribute(POOLED_OBJ_ATTNAME, pooledUserInput); final Object bean = pooledUserInput.getBean(); request.setAttribute(Attributes.USER_INPUT, bean); final UserInputErrors errors = request.getUserInputErrors(); request.setAttribute(Attributes.USER_INPUT_ERRORS, errors); // bind the bean properties final int numProps = this.beanFields.length; for (int i = 0; i < numProps; i++) { final FieldDesc fieldDesc = this.beanFields[i]; final PropertyDescriptor propDesc = fieldDesc.getPropDesc(); final String propName = propDesc.getName(); final String propValStr = (fieldDesc.isNoTrim() ? StringUtils.nullIfEmpty(request.getParameter(propName)) : StringUtils.trimToNull(request.getParameter(propName))); final Method propSetter = propDesc.getWriteMethod(); try { propSetter.invoke(bean, fieldDesc.getBinder().convert(request, propValStr, fieldDesc.getFormat(), propDesc.getPropertyType())); } catch (final BindingException e) { if (this.log.isDebugEnabled()) this.log.debug("binding error", e); propSetter.invoke(bean, e.getDefaultValue()); errors.add(propName, fieldDesc.getErrorMessage()); } } // validate the bean final Validator validator = this.validatorFactory.usingContext() .messageInterpolator(request.getMessageInterpolator()).getValidator(); Class<?>[] validationGroups = this.validationGroups; if ((this.validationGroups.length == 0) && (bean instanceof DynamicValidationGroups)) validationGroups = ((DynamicValidationGroups) bean).getValidationGroups(request); final Set<ConstraintViolation<Object>> cvs = validator.validate(bean, validationGroups); final boolean valid = cvs.isEmpty(); if (!valid) { for (final ConstraintViolation<Object> cv : cvs) errors.add(cv.getPropertyPath().toString(), cv.getMessage()); } success = true; return valid; } catch (final IllegalAccessException | InvocationTargetException e) { throw new ServletException("Error working with user input bean.", e); } finally { if (!success) pooledUserInput.recycle(); } }
From source file:com.ebay.jetstream.management.HtmlResourceFormatter.java
protected void formatProperty(Object bean, PropertyDescriptor pd) throws Exception { PrintWriter pw = getWriter(); Method getter = pd.getReadMethod(); Class<?> pclass = pd.getPropertyType(); ManagedAttribute attr = getter.getAnnotation(ManagedAttribute.class); String text = attr != null ? attr.description() : null; if (CommonUtils.isEmptyTrimmed(text)) { text = pd.getDisplayName();/*from w ww .ja v a2 s . co m*/ } else { text = pd.getDisplayName() + " (" + text + ")"; } pw.print(text + ": " + pclass.getName() + " = "); getter.setAccessible(true); Object value = getter.invoke(bean); Method setter = pd.getWriteMethod(); attr = setter == null ? null : setter.getAnnotation(ManagedAttribute.class); boolean isComplex = !(String.class.isAssignableFrom(pclass) || ClassUtils.isPrimitiveOrWrapper(pclass)); if (isComplex) { value = StringEscapeUtils.escapeXml(getSerializer().getXMLStringRepresentation(value)); } if (attr == null) { if (isComplex) { pushElement("code", null); } pw.println(value); if (isComplex) { popElement(); } } else { pw.println(attr.description()); pushElement("form", "action=" + makePath(getPrefix(), getPath(), isComplex ? "?form" : "?" + pd.getName()) + " method=" + (isComplex ? "POST" : "GET")); if (isComplex) { pw.print("<TEXTAREA name=" + pd.getName() + " rows=4 cols=32>" + value + "</TEXTAREA>"); } else { pw.print("<input type=text name=" + pd.getName() + " value=\"" + value + "\"/>"); } pw.println("<input type=submit Value=\"Go\"/>"); popElement(); } pw.println("<P/>"); }
From source file:com.nortal.petit.beanmapper.BeanMappingFactoryImpl.java
@SuppressWarnings("unchecked") private <B> void initProperty(Map<String, Property<B, Object>> props, List<Property<B, Object>> idProps, String name, Class<B> type) { PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(type, name); if (!isPropertyReadableAndWritable(pd)) { return;/*from w ww.ja v a2 s. c o m*/ } List<Annotation> ans = BeanMappingReflectionUtils.readAnnotations(type, pd.getName()); if (BeanMappingReflectionUtils.getAnnotation(ans, Transient.class) != null) { return; } Column column = BeanMappingReflectionUtils.getAnnotation(ans, Column.class); ReflectionProperty<B, Object> prop = new ReflectionProperty<B, Object>(name, (Class<Object>) pd.getPropertyType(), inferColumn(name, column), pd.getWriteMethod(), pd.getReadMethod()); if (column != null) { prop.readOnly(!column.insertable()); } if (BeanMappingReflectionUtils.getAnnotation(ans, Id.class) != null) { idProps.add(prop); } if (useAdditionalConfiguration()) { prop.getConfiguration().setAnnotations(ans); if (Collection.class.isAssignableFrom(pd.getPropertyType())) { prop.getConfiguration().setCollectionTypeArguments( ((ParameterizedType) pd.getReadMethod().getGenericReturnType()).getActualTypeArguments()); } } if (BeanMappingReflectionUtils.getAnnotation(ans, Embedded.class) != null) { props.putAll(getCompositeProperties(prop, ans)); } else { props.put(prop.name(), prop); } }