Java Code Examples for org.apache.commons.beanutils.PropertyUtils.getPropertyDescriptors()

The following are Jave code examples for showing how to use getPropertyDescriptors() of the org.apache.commons.beanutils.PropertyUtils class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: ureport   File: DatasourceServletAction.java   View Source Code Vote up 6 votes
public void buildClass(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	String clazz=req.getParameter("clazz");
	List<Field> result=new ArrayList<Field>();
	try{
		Class<?> targetClass=Class.forName(clazz);
		PropertyDescriptor[] propertyDescriptors=PropertyUtils.getPropertyDescriptors(targetClass);
		for(PropertyDescriptor pd:propertyDescriptors){
			String name=pd.getName();
			if("class".equals(name)){
				continue;
			}
			result.add(new Field(name));
		}
		writeObjectToJson(resp, result);
	}catch(Exception ex){
		throw new ReportDesignException(ex);
	}
}
 
Example 2
Project: abina-common-util   File: ParamsUtils.java   View Source Code Vote up 6 votes
/**
 * 对象拷贝 数据对象空值不拷贝到目标对象
 * 
 * @param databean 待拷贝对象
 * @param tobean 目标对象
 * @throws NoSuchMethodException
 */
public static void copyBeanNotNull2Bean(Object databean, Object tobean) throws Exception {
	PropertyDescriptor origDescriptors[] = PropertyUtils.getPropertyDescriptors(databean);
	for (int i = 0; i < origDescriptors.length; i++) {
		String name = origDescriptors[i].getName();
		// String type = origDescriptors[i].getPropertyType().toString();
		if ("class".equals(name)) {
			continue; // No point in trying to set an object's class
		}
		if (PropertyUtils.isReadable(databean, name) && PropertyUtils.isWriteable(tobean, name)) {
			try {
				Object value = PropertyUtils.getSimpleProperty(databean, name);
				if (value != null) {
					getInstance().setSimpleProperty(tobean, name, value);
				}
			} catch (java.lang.IllegalArgumentException ie) {
				; // Should not happen
			} catch (Exception e) {
				; // Should not happen
			}

		}
	}
}
 
Example 3
Project: ERDesignerNG   File: ModelItemProperties.java   View Source Code Vote up 6 votes
public void copyTo(T aObject) {

		ModelProperties theProperties = aObject.getProperties();

		try {
			for (PropertyDescriptor theDescriptor : PropertyUtils.getPropertyDescriptors(this)) {
				if (theDescriptor.getReadMethod() != null && theDescriptor.getWriteMethod() != null) {
					Object theValue = PropertyUtils.getProperty(this, theDescriptor.getName());
					if (theValue != null) {
						theProperties.setProperty(theDescriptor.getName(), theValue.toString());
					} else {
						theProperties.setProperty(theDescriptor.getName(), null);
					}
				}
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
 
Example 4
Project: TranskribusSwtGui   File: TrpConfig.java   View Source Code Vote up 6 votes
private static void updateConfigFromBean(APropertyChangeSupport bean, String... forceAddThisProperties) {
		List<String> addThoseL = Arrays.asList(forceAddThisProperties);

		logger.debug("updating config from bean: "+bean.getClass().getName()+ ", adding those props: "+CoreUtils.toListString(addThoseL));
		
		for (PropertyDescriptor pd :  PropertyUtils.getPropertyDescriptors(bean)) {
			Object value = null;
			try {
//				logger.debug("property name: "+pd.getName());
				value = PropertyUtils.getProperty(bean, pd.getName());
				String strVal = getValue(value);
				if (config.getProperty(pd.getName())!=null) {
					logger.trace("updating property "+pd.getName()+" to "+strVal);
					config.setProperty(pd.getName(), strVal);
				} else if (addThoseL.contains(pd.getName())) {
					logger.debug("adding new property "+pd.getName()+" to "+strVal);
					config.addProperty(pd.getName(), strVal);
				}
			} catch (Exception e) {
				logger.warn("Could not set property "+pd.getName()+" to "+value+", error: "+e.getMessage());
			}
		}
	}
 
Example 5
Project: javabean-marshaller   File: JavaBeanMarshaller.java   View Source Code Vote up 6 votes
public String generateBeanCode(Object bean) {
    if (processedBeans.contains(bean)) {
        return getVariableName(bean);
    }
    processedBeans.add(bean);
    String varName = generateVariableName(bean);
    method.addStatement("$T " + varName + " = new $T()", bean.getClass(), bean.getClass());
    PropertyDescriptor[] properties = PropertyUtils.getPropertyDescriptors(bean.getClass());
    for (PropertyDescriptor propertyDescriptor : properties) {
        try {
            generatePropertySetter(bean, varName, propertyDescriptor);
        } catch (IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }
    return varName;
}
 
Example 6
Project: OpenCyclos   File: BaseCustomFieldServiceImpl.java   View Source Code Vote up 6 votes
@SuppressWarnings("unchecked")
private void copyParentProperties(final CustomField parent, final CustomField child) {
    final PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(parent);
    for (final PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        final String name = propertyDescriptor.getName();
        final boolean isWritable = propertyDescriptor.getWriteMethod() != null;
        final boolean isReadable = propertyDescriptor.getReadMethod() != null;
        if (isReadable && isWritable && !EXCLUDED_PROPERTIES_FOR_DEPENDENT_FIELDS.contains(name)) {
            Object value = PropertyHelper.get(parent, name);
            if (value instanceof Collection) {
                value = new ArrayList<Object>((Collection<Object>) value);
            }
            PropertyHelper.set(child, name, value);
        }
    }
}
 
Example 7
Project: OpenCyclos   File: PropertyHelper.java   View Source Code Vote up 6 votes
/**
 * Copies all possible properties from source to dest, ignoring the given properties list. Exceptions are ignored
 */
public static void copyProperties(final Object source, final Object dest, final String... ignored) {
    if (source == null || dest == null) {
        return;
    }
    final PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(source);
    for (final PropertyDescriptor sourceDescriptor : propertyDescriptors) {
        try {
            final String name = sourceDescriptor.getName();
            // Check for ignored properties
            if (ArrayUtils.contains(ignored, name)) {
                continue;
            }
            final PropertyDescriptor destProperty = PropertyUtils.getPropertyDescriptor(dest, name);
            if (destProperty.getWriteMethod() == null) {
                // Ignore read-only properties
                continue;
            }
            final Object value = CoercionHelper.coerce(destProperty.getPropertyType(), get(source, name));
            set(dest, name, value);
        } catch (final Exception e) {
            // Ignore this property
        }
    }
}
 
Example 8
Project: OpenCyclos   File: EntityHelper.java   View Source Code Vote up 6 votes
/**
 * Returns a Map with basic properties for the given entity
 */
public static Map<String, PropertyDescriptor> propertyDescriptorsFor(final Entity entity) {
    final Class<? extends Entity> clazz = getRealClass(entity);
    SortedMap<String, PropertyDescriptor> properties = cachedPropertiesByClass.get(clazz);
    if (properties == null) {
        properties = new TreeMap<String, PropertyDescriptor>();
        final PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(clazz);
        for (final PropertyDescriptor descriptor : propertyDescriptors) {
            final String name = descriptor.getName();
            boolean ok = name.equals("id");
            if (!ok) {
                final Method readMethod = descriptor.getReadMethod();
                if (readMethod != null) {
                    final Class<?> declaringClass = readMethod.getDeclaringClass();
                    ok = !declaringClass.equals(Entity.class) && !declaringClass.equals(CustomFieldsContainer.class);
                }
            }
            if (ok) {
                properties.put(name, descriptor);
            }
        }
        properties = Collections.unmodifiableSortedMap(properties);
        cachedPropertiesByClass.put(clazz, properties);
    }
    return properties;
}
 
Example 9
Project: Biliomi   File: ObjectGraphs.java   View Source Code Vote up 5 votes
/**
 * Deep merge to POJO objects
 *
 * @param target The target POJO
 * @param source The source POJO
 * @param <T>    The POJO type
 * @return The merge result
 */
public static <T> T mergeObjects(T target, T source) {
  // Check that target and source are of the same type
  Preconditions.checkArgument(
      target.getClass().equals(source.getClass()),
      "Type mismatch %s -> %s",
      source.getClass().getSimpleName(),
      target.getClass().getSimpleName()
  );

  PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(target);

  EStream.from(descriptors).forEach(propertyDescriptor -> {

    Object targetValue = PropertyUtils.getProperty(target, propertyDescriptor.getName());
    Object sourceValue = PropertyUtils.getProperty(source, propertyDescriptor.getName());

    if (sourceValue != null) {
      if (targetValue == null) {
        PropertyUtils.setProperty(target, propertyDescriptor.getName(), sourceValue);
      } else {
        if (isJavaType(propertyDescriptor)) {
          if (targetValue != sourceValue) {
            PropertyUtils.setProperty(target, propertyDescriptor.getName(), sourceValue);
          }
        } else {
          mergeObjects(targetValue, sourceValue);
        }
      }
    }
  });

  return target;
}
 
Example 10
Project: Biliomi   File: ObjectGraphs.java   View Source Code Vote up 5 votes
/**
 * Recursively initialize all non-primitive properties of an object
 *
 * @param o The object to initialize
 */
public static void initializeObjectGraph(Object o) {
  PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(o);

  EStream.from(descriptors)
      .filter(propertyDescriptor -> !isJavaType(propertyDescriptor))
      .filter(propertyDescriptor -> PropertyUtils.getProperty(o, propertyDescriptor.getName()) == null)
      .forEach(propertyDescriptor -> {
        Class<?> type = propertyDescriptor.getPropertyType();
        Object subO = type.getDeclaredConstructor().newInstance();
        PropertyUtils.setProperty(o, propertyDescriptor.getName(), subO);
        initializeObjectGraph(subO);
      });
}
 
Example 11
Project: validator-web   File: DefaultContainer.java   View Source Code Vote up 5 votes
protected void initializeBean(Object bean) {
    for (PropertyDescriptor pd : PropertyUtils.getPropertyDescriptors(bean)) {
        Method writeMethod = pd.getWriteMethod();
        if (writeMethod == null) {
            continue;
        }
        injectBean(bean, pd);
        injectValue(bean, pd);
    }
}
 
Example 12
Project: sistra   File: ConectorConfigurator.java   View Source Code Vote up 5 votes
public static List /*String*/ getConectorPropertyNames(Conector conector) {
    PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(conector);
    List list = new ArrayList(descriptors.length);
    for (int i = 0; i < descriptors.length; i++) {
        PropertyDescriptor descriptor = descriptors[i];
        if (descriptor.getWriteMethod() != null) {
            list.add(descriptor.getName());
        }
    }
    return list;
}
 
Example 13
Project: sistra   File: ConectorConfigurator.java   View Source Code Vote up 5 votes
public static List /*String*/ getConectorPropertyNames(Class clazz) {
    PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(clazz);
    List list = new ArrayList(descriptors.length);
    for (int i = 0; i < descriptors.length; i++) {
        PropertyDescriptor descriptor = descriptors[i];
        if (descriptor.getWriteMethod() != null) {
            list.add(descriptor.getName());
        }
    }
    return list;
}
 
Example 14
Project: sonar-checkstyle   File: ChecksTest.java   View Source Code Vote up 5 votes
private static Set<String> getProperties(Class<?> clss) {
    final Set<String> result = new TreeSet<>();
    final PropertyDescriptor[] map = PropertyUtils.getPropertyDescriptors(clss);

    for (PropertyDescriptor p : map) {
        if (p.getWriteMethod() != null) {
            result.add(p.getName());
        }
    }

    return result;
}
 
Example 15
Project: camel-alma   File: UserServiceWrapper.java   View Source Code Vote up 5 votes
private void copyPropertiesFromTo(User from, User to) throws Exception {
    for (PropertyDescriptor property : PropertyUtils.getPropertyDescriptors(User.class)) {
        if (NO_UPDATE_PROPERTIES.contains(property.getName())) {
            log.debug("Copying property {}", property.getName());
            Method read = property.getReadMethod();
            Method write = property.getWriteMethod();
            if (read.invoke(from) != null) {
                write.invoke(to, read.invoke(from));
            }
        }
    }
}
 
Example 16
Project: my-paper   File: BaseDirective.java   View Source Code Vote up 5 votes
/**
 * 获取筛选
 * 
 * @param params
 *            参数
 * @param type
 *            参数类型
 * @param ignoreProperties
 *            忽略属性
 * @return 筛选
 */
protected List<Filter> getFilters(Map<String, TemplateModel> params, Class<?> type, String... ignoreProperties) throws TemplateModelException {
	List<Filter> filters = new ArrayList<Filter>();
	PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(type);
	for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
		String propertyName = propertyDescriptor.getName();
		Class<?> propertyType = propertyDescriptor.getPropertyType();
		if (!ArrayUtils.contains(ignoreProperties, propertyName) && params.containsKey(propertyName)) {
			Object value = FreemarkerUtils.getParameter(propertyName, propertyType, params);
			filters.add(Filter.eq(propertyName, value));
		}
	}
	return filters;
}
 
Example 17
Project: audible   File: TypeSafeCopy.java   View Source Code Vote up 5 votes
@SuppressWarnings("unchecked")
public void copyProperties(Object dest, Object orig) throws IllegalAccessException, InvocationTargetException {
    PropertyDescriptor[] origDescriptors =
            PropertyUtils.getPropertyDescriptors(orig);
    for (PropertyDescriptor origDescriptor : origDescriptors) {
        String name = origDescriptor.getName();
        if ("class".equals(name)) {
            continue; // No point in trying to set an object's class
        }
        if (PropertyUtils.isReadable(orig, name) &&
                PropertyUtils.isWriteable(dest, name)) {


            try {
                Class origPropClass = PropertyUtils.getPropertyType(orig, name);
                Class destPropClass = PropertyUtils.getPropertyType(dest, name);

                if (destPropClass.isAssignableFrom(origPropClass)) {
                    Object value =
                            PropertyUtils.getSimpleProperty(orig, name);
                    BeanUtils.copyProperty(dest, name, value);
                }
            } catch (NoSuchMethodException e) {
                // Should not happen
            }
        }
    }
}
 
Example 18
Project: graylog-plugin-pipeline-processor   File: CodeGenerator.java   View Source Code Vote up 5 votes
@Override
public void exitFieldAccess(FieldAccessExpression expr) {
    final CodeBlock object = codeSnippet.get(expr.object());
    final CodeBlock field = codeSnippet.get(expr.field());

    final Object objectRef = blockOrMissing(object, expr.object());

    final Expression o = expr.object();
    final PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(o.getType());
    final ImmutableMap<String, PropertyDescriptor> propertyByName = Maps.uniqueIndex(Iterators.forArray(propertyDescriptors), FeatureDescriptor::getName);

    final String fieldName = field.toString();
    final CodeBlock block;
    if (propertyByName.containsKey(fieldName)) {
        // we have the property, resolve the read method name for it
        final PropertyDescriptor descriptor = propertyByName.get(fieldName);
        final String methodName = descriptor.getReadMethod().getName();
        block = CodeBlock.of("$L.$L()", objectRef, methodName);
    } else if (o instanceof Map) {
        // there wasn't any property, but the object is a Map, translate into .get() call
        block = CodeBlock.of("$L.get($S)", objectRef, field);
    } else {
        // this is basically an error, because we expected either a property to match or a map lookup.
        log.warn("Unable to determine field accessor for property {}", field);
        block = CodeBlock.of("null");
    }

    codeSnippet.put(expr, block);
}
 
Example 19
Project: checkstyle-backport-jre6   File: XdocsPagesTest.java   View Source Code Vote up 5 votes
private static Set<String> getProperties(Class<?> clss) {
    final Set<String> result = new TreeSet<String>();
    final PropertyDescriptor[] map = PropertyUtils.getPropertyDescriptors(clss);

    for (PropertyDescriptor p : map) {
        if (p.getWriteMethod() != null) {
            result.add(p.getName());
        }
    }

    return result;
}
 
Example 20
Project: ERDesignerNG   File: ModelItemProperties.java   View Source Code Vote up 5 votes
public void initializeFrom(T aObject) {
	ModelProperties theProperties = aObject.getProperties();

	try {
		for (PropertyDescriptor theDescriptor : PropertyUtils.getPropertyDescriptors(this)) {
			if (theDescriptor.getReadMethod() != null && theDescriptor.getWriteMethod() != null) {
				String theValue = theProperties.getProperty(theDescriptor.getName());
				if (!StringUtils.isEmpty(theValue)) {
					Class theType = theDescriptor.getPropertyType();

					if (theType.isEnum()) {
						PropertyUtils.setProperty(this, theDescriptor.getName(), Enum.valueOf(theType, theValue));
					}
					if (String.class.equals(theType)) {
						PropertyUtils.setProperty(this, theDescriptor.getName(), theValue);
					}
					if (Long.class.equals(theType) || long.class.equals(theType)) {
						PropertyUtils.setProperty(this, theDescriptor.getName(), Long.parseLong(theValue));
					}
					if (Integer.class.equals(theType) || int.class.equals(theType)) {
						PropertyUtils.setProperty(this, theDescriptor.getName(), Integer.parseInt(theValue));
					}
					if (Boolean.class.equals(theType) || boolean.class.equals(theType)) {
						PropertyUtils.setProperty(this, theDescriptor.getName(), Boolean.parseBoolean(theValue));
					}
				}
			}
		}
	} catch (Exception e) {
		throw new RuntimeException(e);
	}

}
 
Example 21
Project: java-platform   File: PropertyUtil.java   View Source Code Vote up 5 votes
public static Class<?> getPropertyType(Class<?> beanClass, String propertyName) {
	PropertyDescriptor[] propertyDescriptors = propertyDescriptorCache.get(beanClass);
	if (propertyDescriptors == null) {
		propertyDescriptors = PropertyUtils.getPropertyDescriptors(beanClass);
		propertyDescriptorCache.put(beanClass, propertyDescriptors);
	}
	for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
		if (Objects.equal(propertyDescriptor.getName(), propertyName)) {
			return propertyDescriptor.getPropertyType();
		}
	}

	return null;
}
 
Example 22
Project: easycode   File: DefaultJdbcHandler.java   View Source Code Vote up 5 votes
/**
 * 验证是否存在指定的property
 * @param clazz
 * @param name
 * @return
 */
private boolean existProperty(Class<?> clazz, String name) {
	PropertyDescriptor[] pds = PropertyUtils.getPropertyDescriptors(clazz);
	for (PropertyDescriptor pd : pds) {
		if (name.equals(pd.getName())) {
			return true;
		}
	}
	return false;
}
 
Example 23
Project: easycode   File: DefaultJdbcHandler.java   View Source Code Vote up 5 votes
/**
 * 设置指定属性的值,该属性值为null设值,不为null则不设值
 */
private void setBeanProperty(Object obj, String name, Object val) {
	PropertyDescriptor prop = null;
	PropertyDescriptor[] pds = PropertyUtils.getPropertyDescriptors(obj);
	for (PropertyDescriptor pd : pds) {
		if (name.equals(pd.getName())) {
			prop = pd;
			break;
		}
	}
	if(prop != null) {
		try {
			Method read = prop.getReadMethod();
			if (!Modifier.isPublic(read.getModifiers())) {
				read.setAccessible(true);
			}
			if (read.invoke(obj) == null) {
				Method write = prop.getWriteMethod();
				if (!Modifier.isPublic(write.getModifiers())) {
					write.setAccessible(true);
				}
				//设置值
				write.invoke(obj, val);
			}
		} catch (Exception e) {
			log.warn("read or write object({}) property({}) error.", obj, name, e);
		}
	}
}
 
Example 24
Project: OpenCyclos   File: JpaQueryHelper.java   View Source Code Vote up 5 votes
/**
 * Returns a set of properties that will be fetched directly on the HQL
 */
private static Set<String> getDirectRelationshipProperties(final Class<? extends Entity> entityType, final Collection<Relationship> fetch) {
    // Populate the direct properties cache for this entity if not yet exists
    Set<String> cachedDirectProperties = directPropertiesCache.get(entityType);
    if (cachedDirectProperties == null) {
        cachedDirectProperties = new HashSet<String>();
        final PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(entityType);
        // Scan for child -> parent relationships
        for (final PropertyDescriptor descriptor : propertyDescriptors) {
            if (descriptor.getReadMethod() != null && descriptor.getWriteMethod() != null && Entity.class.isAssignableFrom(descriptor.getPropertyType())) {
                // This is a child -> parent relationship. Add it to the cache
                cachedDirectProperties.add(descriptor.getName());
            }
        }
        directPropertiesCache.put(entityType, cachedDirectProperties);
    }

    // Build the properties to add to HQL fetch from a given relationship set
    final Set<String> propertiesToAddToFetch = new HashSet<String>();
    for (final Relationship relationship : fetch) {
        final String name = PropertyHelper.firstProperty(relationship.getName());
        if (cachedDirectProperties.contains(name)) {
            propertiesToAddToFetch.add(name);
        }
    }
    return propertiesToAddToFetch;
}
 
Example 25
Project: jerrydog   File: StandardServer.java   View Source Code Vote up 4 votes
/**
 * Store the relevant attributes of the specified JavaBean.
 *
 * @param writer PrintWriter to which we are storing
 * @param include Should we include a <code>className</code> attribute?
 * @param bean Bean whose properties are to be rendered as attributes,
 *
 * @exception Exception if an exception occurs while storing
 */
private void storeAttributes(PrintWriter writer, boolean include,
                             Object bean) throws Exception {

    // Render a className attribute if requested
    if (include) {
        writer.print(" className=\"");
        writer.print(bean.getClass().getName());
        writer.print("\"");
    }

    // Acquire the list of properties for this bean
    PropertyDescriptor descriptors[] =
        PropertyUtils.getPropertyDescriptors(bean);
    if (descriptors == null) {
        descriptors = new PropertyDescriptor[0];
    }

    // Render the relevant properties of this bean
    String className = bean.getClass().getName();
    for (int i = 0; i < descriptors.length; i++) {
        if (descriptors[i] instanceof IndexedPropertyDescriptor) {
            continue; // Indexed properties are not persisted
        }
        if (!isPersistable(descriptors[i].getPropertyType()) ||
            (descriptors[i].getReadMethod() == null) ||
            (descriptors[i].getWriteMethod() == null)) {
            continue; // Must be a read-write primitive or String
        }
        Object value =
            PropertyUtils.getSimpleProperty(bean,
                                            descriptors[i].getName());
        if (value == null) {
            continue; // Null values are not persisted
        }
        if (isException(className, descriptors[i].getName())) {
            continue; // Skip the specified exceptions
        }
        if (!(value instanceof String)) {
            value = value.toString();
        }
        writer.print(' ');
        writer.print(descriptors[i].getName());
        writer.print("=\"");
        String strValue = convertStr((String) value);
        writer.print(strValue);
        writer.print("\"");
    }

}