List of usage examples for java.beans BeanInfo getPropertyDescriptors
PropertyDescriptor[] getPropertyDescriptors();
From source file:com.eclecticlogic.pedal.dialect.postgresql.CopyCommand.java
private String extractColumnName(Method method, Class<? extends Serializable> clz) { String beanPropertyName = null; try {//from w w w .ja va 2 s . c o m BeanInfo info; info = Introspector.getBeanInfo(clz); for (PropertyDescriptor propDesc : info.getPropertyDescriptors()) { if (method.equals(propDesc.getReadMethod())) { beanPropertyName = propDesc.getName(); break; } } } catch (IntrospectionException e) { throw new RuntimeException(e.getMessage(), e); } String columnName = null; if (clz.isAnnotationPresent(AttributeOverrides.class)) { for (AttributeOverride annotation : clz.getAnnotation(AttributeOverrides.class).value()) { if (annotation.name().equals(beanPropertyName)) { columnName = annotation.column().name(); break; } } } else if (clz.isAnnotationPresent(AttributeOverride.class)) { AttributeOverride annotation = clz.getAnnotation(AttributeOverride.class); if (annotation.name().equals(beanPropertyName)) { columnName = annotation.column().name(); } } return columnName == null ? method.getAnnotation(Column.class).name() : columnName; }
From source file:org.rhq.plugins.postgres.PostgresServerComponent.java
public double getObjectProperty(Object object, String name) { try {// ww w. j a v a 2 s. c o m BeanInfo info = Introspector.getBeanInfo(object.getClass()); for (PropertyDescriptor pd : info.getPropertyDescriptors()) { if (pd.getName().equals(name)) { return ((Number) pd.getReadMethod().invoke(object)).doubleValue(); } } } catch (Exception e) { log.error("Error occurred while retrieving property '" + name + "' from object [" + object + "]", e); } return Double.NaN; }
From source file:com.siberhus.tdfl.mapping.BeanWrapLineMapper.java
@SuppressWarnings("unchecked") protected Properties getBeanProperties(Object bean, Properties properties) throws IntrospectionException { Class<?> cls = bean.getClass(); String[] namesCache = propertyNamesCache.get(cls); if (namesCache == null) { List<String> setterNames = new ArrayList<String>(); BeanInfo beanInfo = Introspector.getBeanInfo(cls); PropertyDescriptor propDescs[] = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor propDesc : propDescs) { if (propDesc.getWriteMethod() != null) { setterNames.add(propDesc.getName()); }//from w ww.j a va 2 s . c o m } propertyNamesCache.put(cls, setterNames.toArray(new String[0])); } // Map from field names to property names Map<String, String> matches = propertiesMatched.get(cls); if (matches == null) { matches = new HashMap<String, String>(); propertiesMatched.put(cls, matches); } @SuppressWarnings("rawtypes") Set<String> keys = new HashSet(properties.keySet()); for (String key : keys) { if (matches.containsKey(key)) { switchPropertyNames(properties, key, matches.get(key)); continue; } String name = findPropertyName(bean, key); if (name != null) { matches.put(key, name); switchPropertyNames(properties, key, name); } } return properties; }
From source file:de.jwic.base.Control.java
/** * Builds Json object string of all methods marked with * IncludeJsOption Annotation.//from ww w. j a va 2s. c o m * If Enums are used getCode needs to be implemented, which returns the value * @return */ public String buildJsonOptions() { try { StringWriter sw = new StringWriter(); JSONWriter writer = new JSONWriter(sw); writer.object(); BeanInfo beanInfo; beanInfo = Introspector.getBeanInfo(getClass()); PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor pd : pds) { Method getter = pd.getReadMethod(); if (getter != null && pd.getReadMethod().getAnnotation(IncludeJsOption.class) != null) { Object o = getter.invoke(this); if (o != null) { if (o instanceof Enum) { Method m = o.getClass().getMethod("getCode", null); if (m != null) { writer.key(pd.getDisplayName()).value(m.invoke(o)); continue; } } else if (o instanceof Date) { writer.key(pd.getDisplayName()) .value(new JsDateString((Date) o, getSessionContext().getTimeZone())); continue; } // if name has been changed use that one. IncludeJsOption annotation = pd.getReadMethod().getAnnotation(IncludeJsOption.class); if (annotation.jsPropertyName() != null && annotation.jsPropertyName().length() > 0) { writer.key(annotation.jsPropertyName()); } else { writer.key(pd.getDisplayName()); } writer.value(o); } } } writer.endObject(); return sw.toString(); } catch (Exception e) { throw new RuntimeException("Error while configuring Json Option for " + this.getClass().getName()); } }
From source file:com.boylesoftware.web.impl.UserInputControllerMethodArgHandler.java
/** * Create new handler.//from w w w. j a v a2 s. c o m * * @param validatorFactory Validator factory. * @param beanClass User input bean class. * @param validationGroups Validation groups to apply during bean * validation, or empty array to use the default group. * * @throws UnavailableException If an error happens. */ UserInputControllerMethodArgHandler(final ValidatorFactory validatorFactory, final Class<?> beanClass, final Class<?>[] validationGroups) throws UnavailableException { this.validatorFactory = validatorFactory; this.beanClass = beanClass; this.validationGroups = validationGroups; try { final BeanInfo beanInfo = Introspector.getBeanInfo(this.beanClass); final PropertyDescriptor[] propDescs = beanInfo.getPropertyDescriptors(); final List<FieldDesc> beanFields = new ArrayList<>(); for (final PropertyDescriptor propDesc : propDescs) { final String propName = propDesc.getName(); final Class<?> propType = propDesc.getPropertyType(); final Method propGetter = propDesc.getReadMethod(); final Method propSetter = propDesc.getWriteMethod(); if ((propGetter == null) || (propSetter == null)) continue; Field propField = null; for (Class<?> c = this.beanClass; !c.equals(Object.class); c = c.getSuperclass()) { try { propField = c.getDeclaredField(propName); break; } catch (final NoSuchFieldException e) { // nothing, continue the loop } } final boolean noTrim = (((propField != null) && propField.isAnnotationPresent(NoTrim.class)) || (propGetter.isAnnotationPresent(NoTrim.class))); Class<? extends Binder> binderClass = null; String format = null; String errorMessage = Bind.DEFAULT_MESSAGE; Bind bindAnno = null; if (propField != null) bindAnno = propField.getAnnotation(Bind.class); if (bindAnno == null) bindAnno = propGetter.getAnnotation(Bind.class); if (bindAnno != null) { binderClass = bindAnno.binder(); format = bindAnno.format(); errorMessage = bindAnno.message(); } if (binderClass == null) { if ((String.class).isAssignableFrom(propType)) binderClass = StringBinder.class; else if ((Boolean.class).isAssignableFrom(propType) || propType.equals(Boolean.TYPE)) binderClass = BooleanBinder.class; else if ((Integer.class).isAssignableFrom(propType) || propType.equals(Integer.TYPE)) binderClass = IntegerBinder.class; else if (propType.isEnum()) binderClass = EnumBinder.class; else // TODO: add more standard binders throw new UnavailableException( "Unsupported user input bean field type " + propType.getName() + "."); } beanFields.add(new FieldDesc(propDesc, noTrim, binderClass.newInstance(), format, errorMessage)); } this.beanFields = beanFields.toArray(new FieldDesc[beanFields.size()]); } catch (final IntrospectionException e) { this.log.error("error introspecting user input bean", e); throw new UnavailableException("Specified user input bean" + " class could not be introspected."); } catch (final IllegalAccessException | InstantiationException e) { this.log.error("error instatiating binder", e); throw new UnavailableException("Used user input bean field binder" + " could not be instantiated."); } this.beanPool = new FastPool<>(new PoolableObjectFactory<PoolableUserInput>() { @Override public PoolableUserInput makeNew(final FastPool<PoolableUserInput> pool, final int pooledObjectId) { try { return new PoolableUserInput(pool, pooledObjectId, beanClass.newInstance()); } catch (final InstantiationException | IllegalAccessException e) { throw new RuntimeException("Error instatiating user input bean.", e); } } }, "UserInputBeansPool_" + beanClass.getSimpleName()); }
From source file:com.google.feedserver.util.BeanUtil.java
/** * Compares two JavaBeans for equality by comparing their properties and the * class of the beans./* w w w. ja v a 2 s . c o m*/ * * @param bean1 Bean to compare * @param bean2 Bean to compare * @return True if {@code bean2} has the same properties with the same values * as {@code bean1} and if they share the same class. */ public boolean equals(Object bean1, Object bean2) throws IntrospectionException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { if ((null == bean1) && (null == bean2)) { return true; } else if ((null == bean1) || (null == bean2)) { return false; } if (bean1.getClass() != bean2.getClass()) { return false; } if (bean1.getClass().isArray() && bean2.getClass().isArray()) { if (Array.getLength(bean1) != Array.getLength(bean2)) { return false; } for (int i = 0; i < Array.getLength(bean1); i++) { if (!equals(Array.get(bean1, i), Array.get(bean2, i))) { return false; } } return true; } else if (bean1.getClass().isArray()) { return false; } else if (bean2.getClass().isArray()) { return false; } else if (isBean(bean1.getClass())) { BeanInfo bean1Info; try { bean1Info = Introspector.getBeanInfo(bean1.getClass(), Object.class); } catch (IntrospectionException e) { return false; } for (PropertyDescriptor p : bean1Info.getPropertyDescriptors()) { Method reader = p.getReadMethod(); if (reader != null) { try { Object value1 = reader.invoke(bean1); Object value2 = reader.invoke(bean2); if (!equals(value1, value2)) { return false; } } catch (IllegalArgumentException e) { return false; } catch (IllegalAccessException e) { return false; } catch (InvocationTargetException e) { return false; } } } return true; } else { return bean1.equals(bean2); } }
From source file:net.yasion.common.core.bean.wrapper.ExtendedBeanInfo.java
/** * Wrap the given {@link BeanInfo} instance; copy all its existing property descriptors locally, wrapping each in a custom {@link SimpleIndexedPropertyDescriptor indexed} or {@link SimplePropertyDescriptor non-indexed} {@code PropertyDescriptor} variant that bypasses default * JDK weak/soft reference management; then search through its method descriptors to find any non-void returning write methods and update or create the corresponding {@link PropertyDescriptor} for each one found. * //from w w w . ja v a2 s. co m * @param delegate * the wrapped {@code BeanInfo}, which is never modified * @throws IntrospectionException * if any problems occur creating and adding new property descriptors * @see #getPropertyDescriptors() */ public ExtendedBeanInfo(BeanInfo delegate) throws IntrospectionException { this.delegate = delegate; for (PropertyDescriptor pd : delegate.getPropertyDescriptors()) { try { this.propertyDescriptors.add(pd instanceof IndexedPropertyDescriptor ? new SimpleIndexedPropertyDescriptor((IndexedPropertyDescriptor) pd) : new SimplePropertyDescriptor(pd)); } catch (IntrospectionException ex) { // Probably simply a method that wasn't meant to follow the JavaBeans pattern... if (logger.isDebugEnabled()) { logger.debug("Ignoring invalid bean property '" + pd.getName() + "': " + ex.getMessage()); } } } MethodDescriptor[] methodDescriptors = delegate.getMethodDescriptors(); if (methodDescriptors != null) { for (Method method : findCandidateWriteMethods(methodDescriptors)) { try { handleCandidateWriteMethod(method); } catch (IntrospectionException ex) { // We're only trying to find candidates, can easily ignore extra ones here... if (logger.isDebugEnabled()) { logger.debug("Ignoring candidate write method [" + method + "]: " + ex.getMessage()); } } } } }
From source file:org.rimudb.DataObjectNode.java
public PropertyDescriptor getPropertyDescriptor(String name) { PropertyDescriptor pd = (PropertyDescriptor) pdescMap.get(name); if (pd == null) { try {/*w w w.ja va2s. c om*/ BeanInfo info = Introspector.getBeanInfo(doClass); PropertyDescriptor pdesc[] = info.getPropertyDescriptors(); for (int i = 0; i < pdesc.length; i++) { String propname = pdesc[i].getName(); if (propname.equals(name)) { // these are properties to keep pdescMap.put(propname, pdesc[i]); pd = pdesc[i]; } } } catch (IntrospectionException e) { error("property " + name + " does not exist in " + getName()); } } return pd; }
From source file:org.rimudb.DataObjectNode.java
public DataObjectNode(CompoundDatabase cdb, DataObjectNode parentNode, String name, Table table) { this.cdb = cdb; this.name = name; this.table = table; this.parentNode = parentNode; try {/* w w w. j a v a 2 s. co m*/ // get property descriptors to use doClass = table.getDataObjectClass(); pdescMap = new TreeMap<String, PropertyDescriptor>(); BeanInfo info = Introspector.getBeanInfo(doClass); PropertyDescriptor pdesc[] = info.getPropertyDescriptors(); for (int i = 0; i < pdesc.length; i++) { String propname = pdesc[i].getName(); TableMetaData tableMetaData = table.getTableMetaData(); ColumnMetaData columnMetaData = tableMetaData.getMetaDataByPropertyName(propname); if (columnMetaData != null) { // these are properties to keep pdescMap.put(propname, pdesc[i]); } } doConst1 = doClass.getConstructor(new Class[] { CompoundDatabase.class }); } catch (Exception e) { log.error("in DataObjectNode.DataObjectNode", e); } catch (Error err) { log.info("name=" + name + " table=" + table + " doClass=" + doClass); log.error("in DataObjectNode.DataObjectNode", err); throw err; } }
From source file:com.github.hateoas.forms.spring.xhtml.XhtmlResourceMessageConverter.java
Object recursivelyCreateObject(Class<?> clazz, MultiValueMap<String, String> formValues, String parentParamName) { if (Map.class.isAssignableFrom(clazz)) { throw new IllegalArgumentException("Map not supported"); } else if (Collection.class.isAssignableFrom(clazz)) { throw new IllegalArgumentException("Collection not supported"); } else {//w w w . jav a2 s. c o m try { Constructor[] constructors = clazz.getConstructors(); Constructor constructor = PropertyUtils.findDefaultCtor(constructors); if (constructor == null) { constructor = PropertyUtils.findJsonCreator(constructors, JsonCreator.class); } Assert.notNull(constructor, "no default constructor or JsonCreator found"); int parameterCount = constructor.getParameterTypes().length; Object[] args = new Object[parameterCount]; if (parameterCount > 0) { Annotation[][] annotationsOnParameters = constructor.getParameterAnnotations(); Class[] parameters = constructor.getParameterTypes(); int paramIndex = 0; for (Annotation[] annotationsOnParameter : annotationsOnParameters) { for (Annotation annotation : annotationsOnParameter) { if (JsonProperty.class == annotation.annotationType()) { JsonProperty jsonProperty = (JsonProperty) annotation; String paramName = jsonProperty.value(); List<String> formValue = formValues.get(parentParamName + paramName); Class<?> parameterType = parameters[paramIndex]; if (DataType.isSingleValueType(parameterType)) { if (formValue != null) { if (formValue.size() == 1) { args[paramIndex++] = DataType.asType(parameterType, formValue.get(0)); } else { // // TODO create proper collection type throw new IllegalArgumentException("variable list not supported"); // List<Object> listValue = new ArrayList<Object>(); // for (String item : formValue) { // listValue.add(DataType.asType(parameterType, formValue.get(0))); // } // args[paramIndex++] = listValue; } } else { args[paramIndex++] = null; } } else { args[paramIndex++] = recursivelyCreateObject(parameterType, formValues, parentParamName + paramName + "."); } } } } Assert.isTrue(args.length == paramIndex, "not all constructor arguments of @JsonCreator are " + "annotated with @JsonProperty"); } Object ret = constructor.newInstance(args); BeanInfo beanInfo = Introspector.getBeanInfo(clazz); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { Method writeMethod = propertyDescriptor.getWriteMethod(); String name = propertyDescriptor.getName(); List<String> strings = formValues.get(name); if (writeMethod != null && strings != null && strings.size() == 1) { writeMethod.invoke(ret, DataType.asType(propertyDescriptor.getPropertyType(), strings.get(0))); // TODO lists, consume values from ctor } } return ret; } catch (Exception e) { throw new RuntimeException("Failed to instantiate bean " + clazz.getName(), e); } } }