List of usage examples for java.beans BeanInfo getPropertyDescriptors
PropertyDescriptor[] getPropertyDescriptors();
From source file:com.artistech.protobuf.TuioProtoConverter.java
@Override public Object convertFromProtobuf(final GeneratedMessage obj) { Object target;//from w ww . j a v a2 s .c o m if (TuioProtos.Blob.class.isAssignableFrom(obj.getClass())) { target = new TUIO.TuioBlob(); } else if (TuioProtos.Time.class.isAssignableFrom(obj.getClass())) { target = new TUIO.TuioTime(); } else if (TuioProtos.Cursor.class.isAssignableFrom(obj.getClass())) { target = new TUIO.TuioCursor(); } else if (TuioProtos.Object.class.isAssignableFrom(obj.getClass())) { target = new TUIO.TuioObject(); } else if (TuioProtos.Point.class.isAssignableFrom(obj.getClass())) { target = new TUIO.TuioPoint(); } else { return null; } try { PropertyDescriptor[] targetProps = Introspector.getBeanInfo(target.getClass()).getPropertyDescriptors(); BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass()); PropertyDescriptor[] messageProps = beanInfo.getPropertyDescriptors(); Method[] methods = obj.getClass().getMethods(); for (PropertyDescriptor targetProp : targetProps) { for (PropertyDescriptor messageProp : messageProps) { if (targetProp.getName().equals(messageProp.getName())) { Method writeMethod = targetProp.getWriteMethod(); Method readMethod = null; for (Method m : methods) { if (writeMethod != null && m.getName().equals(writeMethod.getName().replaceFirst("set", "get"))) { readMethod = m; break; } } try { if (writeMethod != null && readMethod != null && targetProp.getReadMethod() != null) { boolean primitiveOrWrapper = ClassUtils .isPrimitiveOrWrapper(targetProp.getReadMethod().getReturnType()); if (readMethod.getParameterTypes().length > 0) { if (DeepCopy) { if (!Modifier.isAbstract(targetProp.getPropertyType().getModifiers())) { //basically, ArrayList Object newInstance = targetProp.getPropertyType().newInstance(); Method addMethod = newInstance.getClass().getMethod("add", Object.class); Method m = obj.getClass().getMethod(readMethod.getName() + "Count"); int size = (int) m.invoke(obj); for (int ii = 0; ii < size; ii++) { Object o = readMethod.invoke(obj, ii); addMethod.invoke(newInstance, o); } writeMethod.invoke(target, newInstance); } else if (Collection.class .isAssignableFrom(targetProp.getPropertyType())) { //do something if it is a collection or iterable... } } } else if (primitiveOrWrapper) { writeMethod.invoke(target, messageProp.getReadMethod().invoke(obj)); } else { if (GeneratedMessage.class .isAssignableFrom(messageProp.getReadMethod().getReturnType())) { GeneratedMessage invoke = (GeneratedMessage) messageProp.getReadMethod() .invoke(obj); Object val = null; for (ProtoConverter converter : services) { if (converter.supportsConversion(invoke)) { val = convertFromProtobuf(invoke); break; } } if (val != null) { writeMethod.invoke(target, val); } } // System.out.println("Prop1 Name!: " + targetProp.getName()); } } } catch (NullPointerException ex) { //Logger.getLogger(ZeroMqMouse.class.getName()).log(Level.SEVERE, null, ex); } catch (InstantiationException | NoSuchMethodException | IllegalArgumentException | SecurityException | IllegalAccessException | InvocationTargetException ex) { logger.error(ex); } break; } } } } catch (java.beans.IntrospectionException ex) { logger.fatal(ex); } return target; }
From source file:org.echocat.redprecursor.annotations.utils.AccessAlsoProtectedMembersReflectivePropertyAccessor.java
@Nonnull private Map<String, PropertyDescriptor> getPropertyNameToDescriptorFor(@Nonnull Class<?> clazz) { Map<String, PropertyDescriptor> propertyNameToDescriptor = TYPE_TO_PROPERTY_DESCRIPTORS.get(clazz); if (propertyNameToDescriptor == null) { propertyNameToDescriptor = new HashMap<String, PropertyDescriptor>(); final BeanInfo beanInfo; try {/*www . j a v a 2s . c om*/ beanInfo = Introspector.getBeanInfo(clazz); } catch (IntrospectionException e) { throw new RuntimeException("Could not load beanInfo of " + clazz.getName() + ".", e); } final PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { propertyNameToDescriptor.put(propertyDescriptor.getName(), propertyDescriptor); } TYPE_TO_PROPERTY_DESCRIPTORS.put(clazz, propertyNameToDescriptor); } return propertyNameToDescriptor; }
From source file:com.artistech.protobuf.TuioProtoConverter.java
@Override public GeneratedMessage.Builder convertToProtobuf(Object obj) { GeneratedMessage.Builder builder;/*from w ww . j a va 2 s.c o m*/ if (obj.getClass().getName().equals(TUIO.TuioTime.class.getName())) { builder = TuioProtos.Time.newBuilder(); } else if (obj.getClass().getName().equals(TUIO.TuioCursor.class.getName())) { builder = TuioProtos.Cursor.newBuilder(); } else if (obj.getClass().getName().equals(TUIO.TuioObject.class.getName())) { builder = TuioProtos.Object.newBuilder(); } else if (obj.getClass().getName().equals(TUIO.TuioBlob.class.getName())) { builder = TuioProtos.Blob.newBuilder(); } else if (obj.getClass().getName().equals(TUIO.TuioPoint.class.getName())) { builder = TuioProtos.Point.newBuilder(); } else { return null; } try { PropertyDescriptor[] objProps = Introspector.getBeanInfo(obj.getClass()).getPropertyDescriptors(); BeanInfo beanInfo = Introspector.getBeanInfo(builder.getClass()); PropertyDescriptor[] builderProps = beanInfo.getPropertyDescriptors(); Method[] methods = builder.getClass().getMethods(); for (PropertyDescriptor prop1 : objProps) { for (PropertyDescriptor prop2 : builderProps) { if (prop1.getName().equals(prop2.getName())) { Method readMethod = prop1.getReadMethod(); ArrayList<Method> methodsToTry = new ArrayList<>(); for (Method m : methods) { if (m.getName().equals(readMethod.getName().replaceFirst("get", "set"))) { methodsToTry.add(m); } } for (Method setMethod : methodsToTry) { try { if (Iterable.class.isAssignableFrom(readMethod.getReturnType())) { if (DeepCopy) { ArrayList<Method> methodsToTry2 = new ArrayList<>(); for (Method m : methods) { if (m.getName() .equals(readMethod.getName().replaceFirst("get", "add"))) { methodsToTry2.add(m); } } boolean success = false; for (Method setMethod2 : methodsToTry2) { Iterable iter = (Iterable) readMethod.invoke(obj); Iterator it = iter.iterator(); while (it.hasNext()) { Object o = it.next(); //call set.. for (ProtoConverter converter : services) { if (converter.supportsConversion(o)) { try { GeneratedMessage.Builder convertToProtobuf = converter .convertToProtobuf(o); setMethod2.invoke(builder, convertToProtobuf); success = true; break; } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { } } } } if (success) { break; } } } } else { boolean primitiveOrWrapper = ClassUtils .isPrimitiveOrWrapper(readMethod.getReturnType()); if (primitiveOrWrapper) { setMethod.invoke(builder, readMethod.invoke(obj)); } else { Object invoke = readMethod.invoke(obj); com.google.protobuf.GeneratedMessage.Builder val = convertToProtobuf( invoke); setMethod.invoke(builder, val); break; } } } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { // Logger.getLogger(TuioProtoConverter.class.getName()).log(Level.SEVERE, null, ex); } break; } } } } } catch (IntrospectionException ex) { logger.fatal(ex); } return builder; }
From source file:de.escalon.hypermedia.hydra.serialize.JacksonHydraSerializer.java
private Map<String, Object> getTerms(Object bean, Class<?> mixInClass) throws IntrospectionException, IllegalAccessException, NoSuchFieldException { // define terms from package or type in context final Class<?> beanClass = bean.getClass(); Map<String, Object> termsMap = getAnnotatedTerms(beanClass.getPackage(), beanClass.getPackage().getName()); Map<String, Object> classTermsMap = getAnnotatedTerms(beanClass, beanClass.getName()); Map<String, Object> mixinTermsMap = getAnnotatedTerms(mixInClass, beanClass.getName()); // class terms override package terms termsMap.putAll(classTermsMap);/*ww w .j ava 2 s . c o m*/ // mixin terms override class terms termsMap.putAll(mixinTermsMap); final Field[] fields = beanClass.getDeclaredFields(); for (Field field : fields) { final Expose fieldExpose = field.getAnnotation(Expose.class); if (Enum.class.isAssignableFrom(field.getType())) { Map<String, String> map = new LinkedHashMap<String, String>(); termsMap.put(field.getName(), map); if (fieldExpose != null) { map.put(AT_ID, fieldExpose.value()); } map.put(AT_TYPE, AT_VOCAB); final Enum value = (Enum) field.get(bean); final Expose enumValueExpose = getAnnotation(value.getClass().getField(value.name()), Expose.class); // TODO redefine actual enum value to exposed on enum value definition if (enumValueExpose != null) { termsMap.put(value.toString(), enumValueExpose.value()); } else { // might use upperToCamelCase if nothing is exposed final String camelCaseEnumValue = WordUtils .capitalizeFully(value.toString(), new char[] { '_' }).replaceAll("_", ""); termsMap.put(value.toString(), camelCaseEnumValue); } } else { if (fieldExpose != null) { termsMap.put(field.getName(), fieldExpose.value()); } } } // TODO do this recursively for nested beans and collect as long as // nested beans have same vocab // expose getters in context final BeanInfo beanInfo = Introspector.getBeanInfo(beanClass); final PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { final Method method = propertyDescriptor.getReadMethod(); final Expose expose = method.getAnnotation(Expose.class); if (expose != null) { termsMap.put(propertyDescriptor.getName(), expose.value()); } } return termsMap; }
From source file:com.medigy.persist.model.data.EntitySeedDataPopulator.java
protected void populateCachedReferenceEntities(final Class entityClass, final CachedReferenceEntity[] cachedEntities, final String[] propertyList, final Object[][] data) throws HibernateException { try {/* w w w. j a va 2 s . co m*/ final Hashtable pdsByName = new Hashtable(); final BeanInfo beanInfo = Introspector.getBeanInfo(entityClass); final PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors(); for (int i = 0; i < descriptors.length; i++) { final PropertyDescriptor descriptor = descriptors[i]; if (descriptor.getWriteMethod() != null) pdsByName.put(descriptor.getName(), descriptor.getWriteMethod()); } Map entityMapByCache = new HashMap<CachedReferenceEntity, Object>(); for (int i = 0; i < data.length; i++) { final Object entityObject = entityClass.newInstance(); for (int j = 0; j < propertyList.length; j++) { final Method setter = (Method) pdsByName.get(propertyList[j]); if (setter != null && data[i][j] != null) { setter.invoke(entityObject, new Object[] { data[i][j] }); } } entityMapByCache.put(cachedEntities[i], entityObject); if (!useEjb) session.save(entityObject); else entityManager.persist(entityObject); cachedEntities[i].setEntity((ReferenceEntity) entityObject); } } catch (Exception e) { log.error(e); throw new HibernateException(e); } }
From source file:com.medigy.persist.model.data.EntitySeedDataPopulator.java
protected void populateCachedCustomReferenceEntities(final Class entityClass, final CachedCustomReferenceEntity[] cachedEntities, final String[] propertyList, final Object[][] data) throws HibernateException { try {/*from ww w . j a v a2 s .c o m*/ final Hashtable pdsByName = new Hashtable(); final BeanInfo beanInfo = Introspector.getBeanInfo(entityClass); final PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors(); for (int i = 0; i < descriptors.length; i++) { final PropertyDescriptor descriptor = descriptors[i]; if (descriptor.getWriteMethod() != null) pdsByName.put(descriptor.getName(), descriptor.getWriteMethod()); } Map entityMapByCache = new HashMap<CachedCustomReferenceEntity, Object>(); for (int i = 0; i < data.length; i++) { final Object entityObject = entityClass.newInstance(); for (int j = 0; j < propertyList.length; j++) { final Method setter = (Method) pdsByName.get(propertyList[j]); if (setter != null && data[i][j] != null) { if (data[i][j] instanceof CachedCustomHierarchyReferenceEntity) { setter.invoke(entityObject, new Object[] { entityMapByCache.get(data[i][j]) }); } else setter.invoke(entityObject, new Object[] { data[i][j] }); } } entityMapByCache.put(cachedEntities[i], entityObject); if (!useEjb) session.save(entityObject); else entityManager.persist(entityObject); cachedEntities[i].setEntity((CustomReferenceEntity) entityObject); } } catch (Exception e) { log.error(ExceptionUtils.getStackTrace(e)); throw new HibernateException(e); } }
From source file:com.google.feedserver.util.BeanUtil.java
/** * Applies a collection of properties to a JavaBean. Converts String and * String[] values to correct property types * // w ww . j a v a 2 s. c o m * @param properties A map of the properties to set on the JavaBean * @param bean The JavaBean to set the properties on */ public void convertPropertiesToBean(Map<String, Object> properties, Object bean) throws IntrospectionException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, ParseException { BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass(), Object.class); for (PropertyDescriptor p : beanInfo.getPropertyDescriptors()) { String name = p.getName(); Object value = properties.get(name); Method reader = p.getReadMethod(); Method writer = p.getWriteMethod(); // we only care about "complete" properties if (reader != null && writer != null && value != null) { Class<?> propertyType = writer.getParameterTypes()[0]; if (isBean(propertyType)) { // this is a bean if (propertyType.isArray()) { propertyType = propertyType.getComponentType(); Object beanArray = Array.newInstance(propertyType, 1); if (value.getClass().isArray()) { Object[] valueArrary = (Object[]) value; int length = valueArrary.length; beanArray = Array.newInstance(propertyType, length); for (int index = 0; index < valueArrary.length; ++index) { Object valueObject = valueArrary[index]; fillBeanInArray(propertyType, beanArray, index, valueObject); } } else { fillBeanInArray(propertyType, beanArray, 0, value); } value = beanArray; } else if (propertyType == Timestamp.class) { value = new Timestamp(TIMESTAMP_FORMAT.parse((String) value).getTime()); } else { Object beanObject = createBeanObject(propertyType, value); value = beanObject; } } else { Class<?> valueType = value.getClass(); if (!propertyType.isAssignableFrom(valueType)) { // convert string input values to property type try { if (valueType == String.class) { value = ConvertUtils.convert((String) value, propertyType); } else if (valueType == String[].class) { value = ConvertUtils.convert((String[]) value, propertyType); } else if (valueType == Object[].class) { // best effort conversion Object[] objectValues = (Object[]) value; String[] stringValues = new String[objectValues.length]; for (int i = 0; i < objectValues.length; i++) { stringValues[i] = objectValues[i] == null ? null : objectValues[i].toString(); } value = ConvertUtils.convert(stringValues, propertyType); } else { } } catch (ConversionException e) { throw new IllegalArgumentException( "Conversion failed for " + "property '" + name + "' with value '" + value + "'", e); } } } // We only write values that are present in the map. This allows // defaults or previously set values in the bean to be retained. writer.invoke(bean, value); } } }
From source file:BeanPropertyTableModel.java
private void processBeanInfo(BeanInfo info, Vector<Object> columnData) throws InvocationTargetException, IllegalAccessException { BeanInfo[] extra = info.getAdditionalBeanInfo(); if (extra != null) { for (int i = 0; i < extra.length; ++i) { processBeanInfo(extra[i], columnData); }// w w w. ja v a 2 s .c o m } PropertyDescriptor[] propDesc = info.getPropertyDescriptors(); for (int i = 0; i < propDesc.length; ++i) { final String propName = propDesc[i].getName(); final Method getter = propDesc[i].getReadMethod(); if (propName != null && getter != null) { Vector<Object> line = generateLine(propName, _bean, getter); if (line != null) { columnData.add(line); } } } }
From source file:net.zcarioca.zcommons.config.data.BeanPropertySetterFactory.java
/** * Gets a collection of {@link BeanPropertySetter} to configure the bean. * * @param bean The bean to configure./*w w w. ja v a2 s . c o m*/ * @return Returns a collection of {@link BeanPropertySetter}. * @throws ConfigurationException */ public Collection<BeanPropertySetter> getPropertySettersForBean(Object bean) throws ConfigurationException { List<BeanPropertySetter> setters = new ArrayList<BeanPropertySetter>(); Map<String, PropertyDescriptor> descriptors = new HashMap<String, PropertyDescriptor>(); Class<?> beanClass = bean.getClass(); try { BeanInfo beanInfo = Introspector.getBeanInfo(beanClass); for (PropertyDescriptor desc : beanInfo.getPropertyDescriptors()) { Method reader = desc.getReadMethod(); Method writer = desc.getWriteMethod(); Field field = getField(beanClass, desc); if (reader != null) { descriptors.put(desc.getDisplayName(), desc); } if (writer != null) { if (writer.isAnnotationPresent(ConfigurableAttribute.class)) { setters.add(new WriterBeanPropertySetter(bean, desc, field, writer.getAnnotation(ConfigurableAttribute.class))); descriptors.remove(desc.getDisplayName()); } if (reader != null && reader.isAnnotationPresent(ConfigurableAttribute.class)) { setters.add(new WriterBeanPropertySetter(bean, desc, field, reader.getAnnotation(ConfigurableAttribute.class))); descriptors.remove(desc.getDisplayName()); } } } } catch (Throwable t) { throw new ConfigurationException("Could not introspect bean class", t); } do { Field[] fields = beanClass.getDeclaredFields(); for (Field field : fields) { if (field.isAnnotationPresent(ConfigurableAttribute.class)) { if (descriptors.containsKey(field.getName()) && descriptors.get(field.getName()).getWriteMethod() != null) { PropertyDescriptor desc = descriptors.get(field.getName()); setters.add(new WriterBeanPropertySetter(bean, desc, field, field.getAnnotation(ConfigurableAttribute.class))); } else { setters.add(new FieldBeanPropertySetter(bean, null, field, field.getAnnotation(ConfigurableAttribute.class))); } } else if (descriptors.containsKey(field.getName())) { // the annotation may have been set on the getter, not the field PropertyDescriptor desc = descriptors.get(field.getName()); if (desc.getReadMethod().isAnnotationPresent(ConfigurableAttribute.class)) { setters.add(new FieldBeanPropertySetter(bean, desc, field, desc.getReadMethod().getAnnotation(ConfigurableAttribute.class))); } } } } while ((beanClass = beanClass.getSuperclass()) != null); return setters; }
From source file:org.seasar.karrta.jcr.session.JcrSessionFactory.java
/** * add event listeners./*from w ww . j ava2 s.co m*/ * * @param session * @return * @throws JcrRepositoryRuntimeException */ protected void addEventListeners(Session session) throws JcrRepositoryRuntimeException { if (this.eventListeners == null || this.eventListeners.size() == 0) { return; } try { Workspace workspace = session.getWorkspace(); EventListenerDefinition eventDefinition = null; for (Iterator<?> i = this.eventListeners.iterator(); i.hasNext();) { Object bean = i.next(); eventDefinition = new EventListenerDefinition(); BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass()); for (PropertyDescriptor property : beanInfo.getPropertyDescriptors()) { Method getter = property.getReadMethod(); if (getter == null) continue; eventDefinition.setProperty(getter.getName(), getter.invoke(bean, null)); } workspace.getObservationManager().addEventListener(eventDefinition.getListener(), eventDefinition.getEventTypes(), eventDefinition.getAbsPath(), eventDefinition.isDeep(), eventDefinition.getUuids(), eventDefinition.getNodeTypeNames(), eventDefinition.getNoLocal()); } } catch (IllegalAccessException e) { throw new JcrRepositoryRuntimeException("", e); } catch (IntrospectionException e) { throw new JcrRepositoryRuntimeException("", e); } catch (InvocationTargetException e) { throw new JcrRepositoryRuntimeException("", e); } catch (RepositoryException e) { throw new JcrRepositoryRuntimeException("", e); } }