List of usage examples for org.springframework.beans BeanUtils getPropertyDescriptors
public static PropertyDescriptor[] getPropertyDescriptors(Class<?> clazz) throws BeansException
From source file:org.jdal.swing.ListTableModel.java
/** * Initialize table. Load propertyDescriptors based on columNames or * model introspection. /*from w w w. ja v a 2 s .c o m*/ */ // FIXME: PropertyDescriptors are now unused, review to remove. public void init() { if (modelClass == null) { log.warn("Cannot initilize without modelClass, set a list of models o specify a model class"); return; } columnCount = 0; if (usingIntrospection) { pds = Arrays.asList(BeanUtils.getPropertyDescriptors(modelClass)); Collections.reverse(pds); columnNames = new ArrayList<String>(pds.size()); displayNames = new ArrayList<String>(pds.size()); for (PropertyDescriptor propertyDescriptor : pds) { columnNames.add(propertyDescriptor.getName()); displayNames.add(propertyDescriptor.getDisplayName()); } } else { pds = new ArrayList<PropertyDescriptor>(columnNames.size()); for (String name : columnNames) { PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(modelClass, name); if (pd == null) throw new RuntimeException( "Invalid property [" + name + "]" + " for model class [" + modelClass.getName() + "]"); pds.add(pd); } } columnCount += pds.size(); if (usingChecks) { columnCount++; buildCheckArray(); } if (usingActions) { columnCount += actions.size(); } }
From source file:org.hellojavaer.testcase.generator.TestCaseGenerator.java
@SuppressWarnings({ "unchecked", "rawtypes" }) private static <T> T produceBean(Class<T> clazz, ControlParam countrolParam, Stack<Class> parseClassList) { try {/*from w w w . j av a2 s . c om*/ T item = clazz.newInstance(); for (PropertyDescriptor pd : BeanUtils.getPropertyDescriptors(clazz)) { Method writeMethod = pd.getWriteMethod(); if (writeMethod == null || pd.getReadMethod() == null || // countrolParam.getExcludeFieldList() != null && countrolParam.getExcludeFieldList().contains(pd.getName())// ) {// continue; } Class fieldClazz = pd.getPropertyType(); Long numIndex = countrolParam.getNumIndex(); // int enumIndex = countrolParam.getEnumIndex(); Random random = countrolParam.getRandom(); long strIndex = countrolParam.getStrIndex(); int charIndex = countrolParam.getCharIndex(); Calendar time = countrolParam.getTime(); if (TypeUtil.isBaseType(fieldClazz)) { if (TypeUtil.isNumberType(fieldClazz)) { if (fieldClazz == Byte.class) { writeMethod.invoke(item, Byte.valueOf((byte) (numIndex & 0x7F))); } else if (fieldClazz == Short.class) { writeMethod.invoke(item, Short.valueOf((short) (numIndex & 0x7FFF))); } else if (fieldClazz == Integer.class) { writeMethod.invoke(item, Integer.valueOf((int) (numIndex & 0x7FFFFFFF))); } else if (fieldClazz == Long.class) { writeMethod.invoke(item, Long.valueOf((long) numIndex)); } else if (fieldClazz == Float.class) { writeMethod.invoke(item, Float.valueOf((float) numIndex)); } else if (fieldClazz == Double.class) { writeMethod.invoke(item, Double.valueOf((double) numIndex)); } else if (fieldClazz == byte.class) {// writeMethod.invoke(item, (byte) (numIndex & 0x7F)); } else if (fieldClazz == short.class) { writeMethod.invoke(item, (short) (numIndex & 0x7FFF)); } else if (fieldClazz == int.class) { writeMethod.invoke(item, (int) (numIndex & 0x7FFFFFFF)); } else if (fieldClazz == long.class) { writeMethod.invoke(item, (long) numIndex); } else if (fieldClazz == float.class) { writeMethod.invoke(item, (float) numIndex); } else if (fieldClazz == double.class) { writeMethod.invoke(item, (double) numIndex); } numIndex++; if (numIndex < 0) { numIndex &= 0x7FFFFFFFFFFFFFFFL; } countrolParam.setNumIndex(numIndex); } else if (fieldClazz == boolean.class) { writeMethod.invoke(item, random.nextBoolean()); } else if (fieldClazz == Boolean.class) { writeMethod.invoke(item, Boolean.valueOf(random.nextBoolean())); } else if (fieldClazz == char.class) { writeMethod.invoke(item, CHAR_RANGE[charIndex]); charIndex++; if (charIndex >= CHAR_RANGE.length) { charIndex = 0; } countrolParam.setCharIndex(charIndex); } else if (fieldClazz == Character.class) { writeMethod.invoke(item, Character.valueOf(CHAR_RANGE[charIndex])); charIndex++; if (charIndex >= CHAR_RANGE.length) { charIndex = 0; } countrolParam.setCharIndex(charIndex); } else if (fieldClazz == String.class) { if (countrolParam.getUniqueFieldList() != null && countrolParam.getUniqueFieldList().contains(pd.getName())) { StringBuilder sb = new StringBuilder(); convertNum(strIndex, STRING_RANGE, countrolParam.getRandom(), sb); writeMethod.invoke(item, sb.toString()); strIndex += countrolParam.getStrStep(); if (strIndex < 0) { strIndex &= 0x7FFFFFFFFFFFFFFFL; } countrolParam.setStrIndex(strIndex); } else { writeMethod.invoke(item, String.valueOf(CHAR_RANGE[charIndex])); charIndex++; if (charIndex >= CHAR_RANGE.length) { charIndex = 0; } countrolParam.setCharIndex(charIndex); } } else if (fieldClazz == Date.class) { writeMethod.invoke(item, time.getTime()); time.add(Calendar.DAY_OF_YEAR, 1); } else if (fieldClazz.isEnum()) { int index = random.nextInt(fieldClazz.getEnumConstants().length); writeMethod.invoke(item, fieldClazz.getEnumConstants()[index]); } else { // throw new RuntimeException("out of countrol Class " + fieldClazz.getName()); } } else { parseClassList.push(fieldClazz); // TODO ? Set<Class> set = new HashSet<Class>(parseClassList); if (parseClassList.size() - set.size() <= countrolParam.getRecursiveCycleLimit()) { Object bean = produceBean(fieldClazz, countrolParam, parseClassList); writeMethod.invoke(item, bean); } parseClassList.pop(); } } return item; } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.tylproject.vaadin.addon.MongoContainer.java
MongoContainer(Builder<Bean> bldr) { this.criteria = bldr.mongoCriteria; this.baseSort = bldr.sort; this.filterConverter = bldr.filterConverter; this.baseQuery = Query.query(criteria).with(baseSort); resetQuery();//from w w w . ja v a2 s . c o m this.mongoOps = bldr.mongoOps; this.beanClass = bldr.beanClass; this.beanFactory = bldr.beanFactory; if (bldr.hasCustomPropertyList) { this.simpleProperties = Collections.unmodifiableMap(bldr.simpleProperties); } else { // otherwise, get them via reflection this.simpleProperties = new LinkedHashMap<String, Class<?>>(); PropertyDescriptor[] descriptors = BeanUtils.getPropertyDescriptors(beanClass); for (PropertyDescriptor d : descriptors) { this.simpleProperties.put(d.getName(), d.getPropertyType()); } } if (bldr.hasNestedPropertyList) { this.nestedProperties = Collections.unmodifiableMap(bldr.nestedProperties); } else { nestedProperties = Collections.emptyMap(); } List<Object> allProps = new ArrayList<Object>(simpleProperties.keySet()); // remove "class" pseudo-property for compliance with BeanItem allProps.remove("class"); this.allProperties = Collections.unmodifiableList(allProps); allProps.addAll(nestedProperties.keySet()); this.pageSize = bldr.pageSize; }
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./* w w w . j a v a2 s .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:cn.chenlichao.web.ssm.service.impl.BaseServiceImpl.java
@Override public PageResults<E> queryPage(PageParams<E> pageParams) { if (pageParams == null) { throw new IllegalArgumentException("?null"); }// ww w.ja va 2s. c o m LOGGER.trace("..."); // ?? int pageNum = pageParams.getPageIndex(); int pageSize = pageParams.getPageSize(); if (pageSize > 100) { LOGGER.warn(", ?[{}] ?, ? 100 ?", pageSize); pageSize = 100; } // ? PageHelper.startPage(pageNum, pageSize); Example example = new Example(entityClass); // ?? E params = pageParams.getParamEntity(); if (params != null) { Example.Criteria criteria = example.createCriteria(); PropertyDescriptor[] propArray = BeanUtils.getPropertyDescriptors(entityClass); for (PropertyDescriptor pd : propArray) { if (pd.getPropertyType().equals(Class.class)) { continue; } try { Object value = pd.getReadMethod().invoke(params); if (value != null) { if (pd.getPropertyType() == String.class) { String strValue = (String) value; if (strValue.startsWith("%") || strValue.endsWith("%")) { criteria.andLike(pd.getName(), strValue); continue; } } criteria.andEqualTo(pd.getName(), value); } } catch (IllegalAccessException | InvocationTargetException e) { LOGGER.error("example: {}", e.getMessage(), e); } } } // ?? String orderBy = pageParams.getOrderBy(); if (StringUtils.hasText(orderBy)) { processOrder(example, orderBy, pageParams.isAsc()); } List<E> results = baseMapper.selectByExample(example); // if (results == null || !(results instanceof Page)) { return new PageResults<>(0, new ArrayList<E>(0), pageParams); } Page page = (Page) results; Long totalCount = page.getTotal(); return new PageResults<>(totalCount.intValue(), Collections.unmodifiableList(results), pageParams); }
From source file:com.ocs.dynamo.domain.model.impl.EntityModelFactoryImpl.java
/** * Constructs the model for an entity//from w w w .j a v a2 s . c o m * * @param entityClass * the class of the entity * @return */ @SuppressWarnings("unchecked") private synchronized <T> EntityModel<T> constructModel(String reference, Class<T> entityClass) { EntityModel<T> result = (EntityModel<T>) cache.get(reference); if (result == null) { boolean nested = reference.indexOf('.') > 0; // construct the basic model EntityModelImpl<T> model = constructModelInner(entityClass, reference); Map<String, String> attributeGroupMap = determineAttributeGroupMapping(model, entityClass); model.addAttributeGroup(EntityModel.DEFAULT_GROUP); alreadyProcessed.put(reference, entityClass); // keep track of main attributes - if no main attribute is defined, mark // either the // first string attribute or the first searchable attribute as the main boolean mainAttributeFound = false; AttributeModel firstStringAttribute = null; AttributeModel firstSearchableAttribute = null; PropertyDescriptor[] descriptors = BeanUtils.getPropertyDescriptors(entityClass); // create attribute models for all attributes List<AttributeModel> tempModelList = new ArrayList<>(); for (PropertyDescriptor descriptor : descriptors) { if (!skipAttribute(descriptor.getName())) { List<AttributeModel> attributeModels = constructAttributeModel(descriptor, model, model.getEntityClass(), nested, null); for (AttributeModel attributeModel : attributeModels) { // check if the main attribute has been found mainAttributeFound |= attributeModel.isMainAttribute(); // also keep track of the first string property... if (firstStringAttribute == null && String.class.equals(attributeModel.getType())) { firstStringAttribute = attributeModel; } // ... and the first searchable property if (firstSearchableAttribute == null && attributeModel.isSearchable()) { firstSearchableAttribute = attributeModel; } tempModelList.add(attributeModel); } } } // assign ordering and sort determineAttributeOrder(entityClass, reference, tempModelList); Collections.sort(tempModelList); // add the attributes to the model for (AttributeModel attributeModel : tempModelList) { // determine the attribute group name String group = attributeGroupMap.get(attributeModel.getName()); if (StringUtils.isEmpty(group)) { group = EntityModel.DEFAULT_GROUP; } model.addAttributeModel(group, attributeModel); } if (!mainAttributeFound && !nested) { if (firstStringAttribute != null) { firstStringAttribute.setMainAttribute(true); } else if (firstSearchableAttribute != null) { firstSearchableAttribute.setMainAttribute(true); } } String sortOrder = null; Model annot = entityClass.getAnnotation(Model.class); if (annot != null && !StringUtils.isEmpty(annot.sortOrder())) { sortOrder = annot.sortOrder(); } String sortOrderMsg = getEntityMessage(reference, EntityModel.SORT_ORDER); if (!StringUtils.isEmpty(sortOrderMsg)) { sortOrder = sortOrderMsg; } setSortOrder(model, sortOrder); cache.put(reference, model); result = model; } return result; }
From source file:org.walkmod.conf.entities.impl.ConfigurationImpl.java
private List<PropertyDefinition> getProperties(Object o) { List<PropertyDefinition> result = new LinkedList<PropertyDefinition>(); PropertyDescriptor[] properties = BeanUtils.getPropertyDescriptors(o.getClass()); if (properties != null) { for (PropertyDescriptor pd : properties) { if (pd.getWriteMethod() != null) { String name = pd.getDisplayName(); Class<?> clazz = pd.getPropertyType(); String type = clazz.getSimpleName(); String value = ""; if (String.class.isAssignableFrom(clazz) || Number.class.isAssignableFrom(clazz) || clazz.isPrimitive()) { if (pd.getReadMethod() != null) { try { value = pd.getReadMethod().invoke(o).toString(); } catch (Exception e) { }/* w w w . j a v a 2s .c om*/ } else { Field[] fields = o.getClass().getDeclaredFields(); boolean found = false; for (int i = 0; i < fields.length && !found; i++) { if (fields[i].getName().equals(name)) { found = true; fields[i].setAccessible(true); try { value = fields[i].get(o).toString(); } catch (Exception e) { } } } } } PropertyDefinition item = new PropertyDefinitionImpl(type, name, value); result.add(item); } } } return result; }
From source file:com.thesoftwarefactory.vertx.web.model.Form.java
/** * Build a new Form instance from the specified class * //from w w w . j a v a 2 s . c o m * @param cls * @param fieldPrefix: if not null, the prefix is prepended to each field name * @return */ public final static <T> Form<T> fromClass(Class<T> cls, String fieldPrefix) { Objects.requireNonNull(cls); Form<T> result = new Form<T>(); if (fieldPrefix != null) { result.fieldPrefix = fieldPrefix; } // discover properties for (PropertyDescriptor property : BeanUtils.getPropertyDescriptors(cls)) { if (property.getReadMethod() != null && property.getWriteMethod() != null) { // the property has a getter and setter String fieldName = fieldPrefix != null ? fieldPrefix + property.getName() : property.getName(); result.addField(result.new Field(fieldName, Form.fieldTypefromClass(property.getPropertyType()))); } } return result; }
From source file:org.paxml.util.ReflectUtils.java
/** * Get a specific type of property descriptors, except the "class" property. * /*from ww w.jav a2 s .co m*/ * @param clazz * the class * @param type * the type filter, null means no filtering * @return the list of property descriptors. */ public static List<PropertyDescriptor> getPropertyDescriptors(Class clazz, PropertyDescriptorType type) { List<PropertyDescriptor> list = new ArrayList<PropertyDescriptor>(); for (PropertyDescriptor pd : BeanUtils.getPropertyDescriptors(clazz)) { if ("class".equals(pd.getName())) { continue; } switch (type) { case GETTER: if (pd.getReadMethod() != null) { list.add(pd); } break; case SETTER: if (pd.getWriteMethod() != null) { list.add(pd); } break; default: list.add(pd); } } return list; }
From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractConnectorController.java
private String valid(String validationJson, String fieldName, String fieldValue) throws Exception { if (StringUtils.isNotBlank(validationJson)) { JsonBean jsonObject = JSONUtils.fromJSONString(validationJson, JsonBean.class); PropertyDescriptor pd[] = BeanUtils.getPropertyDescriptors(JsonBean.class); for (PropertyDescriptor propertyDescriptor : pd) { String propertyname = propertyDescriptor.getName(); if (!"class".equals(propertyname)) { Object propertyvalue = PropertyUtils.getProperty(jsonObject, propertyname); if (propertyvalue instanceof Boolean && (Boolean) propertyvalue || !(propertyvalue instanceof Boolean)) { String validationResult = jsonObject.validate(fieldName, fieldValue, messageSource); if (!validationResult.equals(CssdkConstants.SUCCESS)) { return validationResult; }//from w w w . j a va 2 s . c o m } } } } return CssdkConstants.SUCCESS; }