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

The following examples show how to use org.apache.commons.beanutils.PropertyUtils#getPropertyDescriptors() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MailingServiceImpl.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
private <T> T cloneBean(T dest, T orig) throws IllegalAccessException, InvocationTargetException {
	PropertyDescriptor[] origDescriptors = PropertyUtils.getPropertyDescriptors(orig);
	for (PropertyDescriptor descriptor : origDescriptors) {
		String name = descriptor.getName();
		if (PropertyUtils.isReadable(orig, name) && PropertyUtils.isWriteable(dest, name)) {
			try {
				Object value = PropertyUtils.getSimpleProperty(orig, name);
				if (!(value instanceof Collection<?>) && !(value instanceof Map<?, ?>)) {
					PropertyUtils.setSimpleProperty(dest, name, value);
				}
			} catch (NoSuchMethodException e) {
				logger.debug("Error writing to '" + name + "' on class '" + dest.getClass() + "'", e);
			}
		}
	}
	return dest;
}
 
Example 2
Source File: AssetPaymentServiceImpl.java    From kfs with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * @see org.kuali.kfs.module.cam.document.service.AssetPaymentService#adjustPaymentAmounts(org.kuali.kfs.module.cam.businessobject.AssetPayment,
 *      boolean, boolean)
 */
public void adjustPaymentAmounts(AssetPayment assetPayment, boolean reverseAmount, boolean nullPeriodDepreciation) throws IllegalAccessException, InvocationTargetException {
    LOG.debug("Starting - adjustAmounts() ");
    PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(AssetPayment.class);
    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        Method readMethod = propertyDescriptor.getReadMethod();
        if (readMethod != null && propertyDescriptor.getPropertyType() != null && KualiDecimal.class.isAssignableFrom(propertyDescriptor.getPropertyType())) {
            KualiDecimal amount = (KualiDecimal) readMethod.invoke(assetPayment);
            Method writeMethod = propertyDescriptor.getWriteMethod();
            if (writeMethod != null && amount != null) {
                // Reset periodic depreciation expenses
                if (nullPeriodDepreciation && Pattern.matches(CamsConstants.SET_PERIOD_DEPRECIATION_AMOUNT_REGEX, writeMethod.getName().toLowerCase())) {
                    Object[] nullVal = new Object[] { null };
                    writeMethod.invoke(assetPayment, nullVal);
                }
                else if (reverseAmount) {
                    // reverse the amounts
                    writeMethod.invoke(assetPayment, (amount.negated()));
                }
            }

        }
    }
    LOG.debug("Finished - adjustAmounts()");
}
 
Example 3
Source File: ModelItemProperties.java    From MogwaiERDesignerNG with GNU General Public License v3.0 6 votes vote down vote up
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
Source File: BaseResourceTest.java    From minnal with Apache License 2.0 6 votes vote down vote up
public <T> boolean compare(T model1, T model2, int depth) {
    if (model1 == null || model2 == null) {
        return false;
    }
    for (PropertyDescriptor descriptor : PropertyUtils.getPropertyDescriptors(model1)) {
        if (PropertyUtil.isSimpleProperty(descriptor.getPropertyType())) {
            try {
                Object property1 = PropertyUtils.getProperty(model1, descriptor.getName());
                Object property2 = PropertyUtils.getProperty(model2, descriptor.getName());
                if (property1 != null && property2 != null && !property1.equals(property2)) {
                    return false;
                }
            } catch (Exception e) {
                logger.info(e.getMessage(), e);
            }
        }
    }
    return true;
}
 
Example 5
Source File: KualiTestAssertionUtils.java    From kfs with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Asserts that the non-null non-BO properties of the expected bean are equal to those of the actual bean. Any null or
 * BusinessObject expected properties are ignored. Attributes are reflected bean-style via any public no-argument methods
 * starting with "get" (or "is" for booleans), including inherited methods. The expected and actual beans do not need to be of
 * the same class.
 * <p>
 * Reflection wraps primitives, so differences in primitiveness are ignored. Properties that are BusinessObjects (generally
 * relations based on foreign key properties) are also ignored, because this method is not testing OJB foreign key resolution
 * (e.g., via the <code>refresh</code> method), we do not want to have to put all the related BOs into the test fixture
 * (redundant with the foreign keys), and many (all?) of our BOs implement the <code>equals</code> method in terms of identity
 * so would fail this assertion anyway. This is a data-oriented assertion, for our data-oriented tests and persistence layer.
 * 
 * @param message a description of this test assertion
 * @param expectedBean a java bean containing expected properties
 * @param actualBean a java bean containing actual properties
 * @throws InvocationTargetException if a getter method throws an exception (the cause)
 * @throws NoSuchMethodException if an expected property does not exist in the actualBean
 */
public static void assertSparselyEqualBean(String message, Object expectedBean, Object actualBean) throws InvocationTargetException, NoSuchMethodException {
    if (message == null) {
        message = "";
    }
    else {
        message = message + " ";
    }
    assertNotNull(message + "actual bean is null", actualBean);
    PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(expectedBean);
    for (int i = 0; i < descriptors.length; i++) {
        PropertyDescriptor descriptor = descriptors[i];
        if (PropertyUtils.getReadMethod(descriptor) != null) {
            try {
                Object expectedValue = PropertyUtils.getSimpleProperty(expectedBean, descriptor.getName());
                if (expectedValue != null && !(expectedValue instanceof BusinessObject)) {
                    assertEquals(message + descriptor.getName(), expectedValue, PropertyUtils.getSimpleProperty(actualBean, descriptor.getName()));
                }
            }
            catch (IllegalAccessException e) {
                throw new AssertionError(e); // can't happen because getReadMethod() returns only public methods
            }
        }
    }
}
 
Example 6
Source File: SqlGenerateUtil.java    From jeecg with Apache License 2.0 6 votes vote down vote up
/**
 * 将Obj对应的属性转为DB中的属性
 * @param searchObj
 * @param fields
 * @param dealfields
 * @return
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public static StringBuffer generateDBFields(Object searchObj,String fields,List dealfields){
	StringBuffer dbFields = new StringBuffer();
	PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(searchObj.getClass());
	String[] fileNames = fields.split(",");
	for(int i=0;i<fileNames.length;i++){
		for(PropertyDescriptor propertyDescriptor:propertyDescriptors){
			String propertyName = propertyDescriptor.getName();
			if(fileNames[i].equals(propertyName)){
				dbFields.append(getDbNameByFieldName(propertyDescriptor)+((i==fileNames.length-1)?"":","));
				dealfields.add(fileNames[i]);
				break;
			}
		}
	}
	
	return dbFields;
}
 
Example 7
Source File: SmartSubQueryParser.java    From bdf3 with Apache License 2.0 6 votes vote down vote up
public SmartSubQueryParser(Linq linq, Class<?> entityClass, List<CollectInfo> collectInfos) {
	PropertyDescriptor[] pds = PropertyUtils.getPropertyDescriptors(entityClass);
	for (PropertyDescriptor pd : pds) {
		if (JpaUtil.isEntityClass(pd.getPropertyType())) {
			boolean found = false;
			for (CollectInfo collectInfo : collectInfos) {
				Class<?> cls = collectInfo.getEntityClass();
				if (cls != null && pd.getPropertyType().isAssignableFrom(cls)) {
					parsers.add(new SubQueryParser(linq, cls, collectInfo.getProperties()));
					found = true;
					break;
				}
			}
			if (!found) {
				parsers.add(new SubQueryParser(linq, pd.getPropertyType()));
			}
		}
	}
}
 
Example 8
Source File: BeanUtil.java    From boubei-tss with Apache License 2.0 6 votes vote down vote up
/**
 * 对象属性复制工具
 * 
 * @param to
 *            目标拷贝对象
 * @param from
 *            拷贝源
 * @param ignore
 *            需要忽略的属性
 */
public static void copy(Object to, Object from, String[] ignore) {
    List<String> list = Arrays.asList(ignore);
    PropertyDescriptor[] descr = PropertyUtils.getPropertyDescriptors(to);
    for (int i = 0; i < descr.length; i++) {
        PropertyDescriptor d = descr[i];
        
        if (d.getWriteMethod() == null)  continue;
        
        if (list.contains(d.getName())) continue;
        
        try {
            Object value = PropertyUtils.getProperty(from, d.getName());
            PropertyUtils.setProperty(to, d.getName(), value);
        } catch (Exception e) {
            throw new RuntimeException("属性名:" + d.getName() + " 在实体间拷贝时出错", e);
        }
    }
}
 
Example 9
Source File: ModelItemProperties.java    From MogwaiERDesignerNG with GNU General Public License v3.0 5 votes vote down vote up
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 10
Source File: QueryGenerator.java    From jeecg-boot-with-activiti with MIT License 5 votes vote down vote up
/**
 *   根据权限相关配置生成相关的SQL 语句
 * @param searchObj
 * @param parameterMap
 * @return
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public static String installAuthJdbc(Class<?> clazz) {
	StringBuffer sb = new StringBuffer();
	//权限查询
	Map<String,SysPermissionDataRule> ruleMap = getRuleMap();
	PropertyDescriptor origDescriptors[] = PropertyUtils.getPropertyDescriptors(clazz);
	String sql_and = " and ";
	for (String c : ruleMap.keySet()) {
		if(oConvertUtils.isNotEmpty(c) && c.startsWith(SQL_RULES_COLUMN)){
			sb.append(sql_and+getSqlRuleValue(ruleMap.get(c).getRuleValue()));
		}
	}
	String name;
	for (int i = 0; i < origDescriptors.length; i++) {
		name = origDescriptors[i].getName();
		if (judgedIsUselessField(name)) {
			continue;
		}
		if(ruleMap.containsKey(name)) {
			SysPermissionDataRule dataRule = ruleMap.get(name);
			QueryRuleEnum rule = QueryRuleEnum.getByValue(dataRule.getRuleConditions());
			Class propType = origDescriptors[i].getPropertyType();
			boolean isString = propType.equals(String.class);
			Object value;
			if(isString) {
				value = converRuleValue(dataRule.getRuleValue());
			}else {
				value = NumberUtils.parseNumber(dataRule.getRuleValue(),propType);
			}
			String filedSql = getSingleSqlByRule(rule, oConvertUtils.camelToUnderline(name), value,isString);
			sb.append(sql_and+filedSql);
		}
	}
	log.info("query auth sql is:"+sb.toString());
	return sb.toString();
}
 
Example 11
Source File: MyBeanUtils.java    From jeewx with Apache License 2.0 5 votes vote down vote up
/**
	 * 对象拷贝
	 * 数据对象空值不拷贝到目标对象
	 * 
	 * @param dataObject
	 * @param toObject
	 * @throws NoSuchMethodException
	 * copy
	 */
  public static void copyBeanNotNull2Bean(Object databean,Object tobean)
  {
	  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){
                	    copyProperty(tobean, name, value);
                  }
              }
              catch (java.lang.IllegalArgumentException ie) {
                  ; // Should not happen
              }
              catch (Exception e) {
                  ; // Should not happen
              }

          }
      }
  }
 
Example 12
Source File: CheckUtil.java    From eclipse-cs with GNU Lesser General Public License v2.1 5 votes vote down vote up
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 13
Source File: JavaFileUtils.java    From xDoc with MIT License 4 votes vote down vote up
public static List<FieldInfo> analysisFields(Class classz, Map<String, String> commentMap) {
    PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(classz);


    List<FieldInfo> fields = new ArrayList<>();

    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        //排除掉class属性
        if ("class".equals(propertyDescriptor.getName())) {
            continue;
        }

        FieldInfo field = new FieldInfo();
        field.setType(propertyDescriptor.getPropertyType());
        field.setSimpleTypeName(propertyDescriptor.getPropertyType().getSimpleName());
        field.setName(propertyDescriptor.getName());
        String comment = commentMap.get(propertyDescriptor.getName());
        if (StringUtils.isBlank(comment)) {
            field.setComment("");
            field.setRequire(false);
            fields.add(field);
        } else {
            boolean require = false;
            if (comment.contains("|")) {
                int endIndex = comment.lastIndexOf("|" + Constant.YES_ZH);
                if (endIndex < 0) {
                    endIndex = comment.lastIndexOf("|" + Constant.YES_EN);
                }
                require = endIndex > 0;

                if (require) {
                    comment = comment.substring(0, endIndex);
                }
            }

            field.setComment(comment);
            field.setRequire(require);
            fields.add(field);
        }
    }
    return fields;
}
 
Example 14
Source File: KRADLegacyDataAdapterImpl.java    From rice with Educational Community License v2.0 4 votes vote down vote up
@Override
public void setObjectPropertyDeep(Object bo, String propertyName, Class type,
        Object propertyValue) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    DataObjectWrapper<Object> dataObjectWrapper = dataObjectService.wrap(bo);
    // Base return cases to avoid null pointers & infinite loops
    if (KRADUtils.isNull(bo) || !PropertyUtils.isReadable(bo, propertyName) || (propertyValue != null
            && propertyValue.equals(dataObjectWrapper.getPropertyValueNullSafe(propertyName))) || (type != null
            && !type.equals(KRADUtils.easyGetPropertyType(bo, propertyName)))) {
        return;
    }
    // Set the property in the BO
    KRADUtils.setObjectProperty(bo, propertyName, type, propertyValue);

    // Now drill down and check nested BOs and BO lists
    PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(bo.getClass());
    for (int i = 0; i < propertyDescriptors.length; i++) {

        PropertyDescriptor propertyDescriptor = propertyDescriptors[i];

        // Business Objects
        if (propertyDescriptor.getPropertyType() != null && (BusinessObject.class).isAssignableFrom(
                propertyDescriptor.getPropertyType()) && PropertyUtils.isReadable(bo,
                propertyDescriptor.getName())) {
            Object nestedBo = dataObjectWrapper.getPropertyValueNullSafe(propertyDescriptor.getName());
            if (nestedBo instanceof BusinessObject) {
                setObjectPropertyDeep(nestedBo, propertyName, type, propertyValue);
            }
        }

        // Lists
        else if (propertyDescriptor.getPropertyType() != null && (List.class).isAssignableFrom(
                propertyDescriptor.getPropertyType()) && dataObjectWrapper.getPropertyValueNullSafe(
                propertyDescriptor.getName()) != null) {

            List propertyList = (List) dataObjectWrapper.getPropertyValueNullSafe(propertyDescriptor.getName());
            for (Object listedBo : propertyList) {
                if (listedBo != null && listedBo instanceof BusinessObject) {
                    setObjectPropertyDeep(listedBo, propertyName, type, propertyValue);
                }
            } // end for
        }
    } // end for
}
 
Example 15
Source File: Schema.java    From usergrid with Apache License 2.0 4 votes vote down vote up
public synchronized void registerEntity( Class<? extends Entity> entityClass ) {
    logger.info( "Registering {}", entityClass );
    EntityInfo e = registeredEntityClasses.get( entityClass );
    if ( e != null ) {
        return;
    }

    Map<String, PropertyDescriptor> propertyDescriptors = entityClassPropertyToDescriptor.get( entityClass );
    if ( propertyDescriptors == null ) {
        EntityInfo entity = new EntityInfo();

        String type = getEntityType( entityClass );

        propertyDescriptors = new LinkedHashMap<String, PropertyDescriptor>();
        Map<String, PropertyInfo> properties = new TreeMap<String, PropertyInfo>( String.CASE_INSENSITIVE_ORDER );
        Map<String, CollectionInfo> collections =
                new TreeMap<String, CollectionInfo>( String.CASE_INSENSITIVE_ORDER );
        Map<String, DictionaryInfo> sets = new TreeMap<String, DictionaryInfo>( String.CASE_INSENSITIVE_ORDER );

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

        for ( PropertyDescriptor descriptor : descriptors ) {
            String name = descriptor.getName();

            EntityProperty propertyAnnotation = getAnnotation( entityClass, descriptor, EntityProperty.class );
            if ( propertyAnnotation != null ) {
                if ( isNotBlank( propertyAnnotation.name() ) ) {
                    name = propertyAnnotation.name();
                }
                propertyDescriptors.put( name, descriptor );

                PropertyInfo propertyInfo = new PropertyInfo( propertyAnnotation );
                propertyInfo.setName( name );
                propertyInfo.setType( descriptor.getPropertyType() );

                properties.put( name, propertyInfo );
                // logger.info(propertyInfo);
            }

            EntityCollection collectionAnnotation =
                    getAnnotation( entityClass, descriptor, EntityCollection.class );
            if ( collectionAnnotation != null ) {
                CollectionInfo collectionInfo = new CollectionInfo( collectionAnnotation );
                collectionInfo.setName( name );
                collectionInfo.setContainer( entity );

                collections.put( name, collectionInfo );
                // logger.info(collectionInfo);
            }

            EntityDictionary setAnnotation = getAnnotation( entityClass, descriptor, EntityDictionary.class );
            if ( setAnnotation != null ) {
                DictionaryInfo setInfo = new DictionaryInfo( setAnnotation );
                setInfo.setName( name );
                // setInfo.setType(descriptor.getPropertyType());
                sets.put( name, setInfo );
                // logger.info(setInfo);
            }
        }

        if ( !DynamicEntity.class.isAssignableFrom( entityClass ) ) {
            entity.setProperties( properties );
            entity.setCollections( collections );
            entity.setDictionaries( sets );
            entity.mapCollectors( this, type );

            entityMap.put( type, entity );

            allProperties.putAll( entity.getProperties() );

            Set<String> propertyNames = entity.getIndexedProperties();
            for ( String propertyName : propertyNames ) {
                PropertyInfo property = entity.getProperty( propertyName );
                if ( ( property != null ) && !allIndexedProperties.containsKey( propertyName ) ) {
                    allIndexedProperties.put( propertyName, property );
                }
            }
        }

        entityClassPropertyToDescriptor.put( entityClass, propertyDescriptors );

        registeredEntityClasses.put( entityClass, entity );
    }
}
 
Example 16
Source File: DataDictionary.java    From kfs with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * @param propertyClass
 * @param propertyName
 * @return PropertyDescriptor for the getter for the named property of the given class, if one exists.
 */
public static PropertyDescriptor buildSimpleReadDescriptor(Class propertyClass, String propertyName) {
    if (propertyClass == null) {
        throw new IllegalArgumentException("invalid (null) propertyClass");
    }
    if (StringUtils.isBlank(propertyName)) {
        throw new IllegalArgumentException("invalid (blank) propertyName");
    }

    PropertyDescriptor p = null;

    // check to see if we've cached this descriptor already. if yes, return true.
    String propertyClassName = propertyClass.getName();
    Map<String, PropertyDescriptor> m = cache.get(propertyClassName);
    if (null != m) {
        p = m.get(propertyName);
        if (null != p) {
            return p;
        }
    }

    // Use PropertyUtils.getPropertyDescriptors instead of manually constructing PropertyDescriptor because of
    // issues with introspection and generic/co-variant return types
    // See https://issues.apache.org/jira/browse/BEANUTILS-340 for more details

    PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(propertyClass);
    if (ArrayUtils.isNotEmpty(descriptors)) {
        for (PropertyDescriptor descriptor : descriptors) {
            if (descriptor.getName().equals(propertyName)) {
                p = descriptor;
            }
        }
    }

    // cache the property descriptor if we found it.
    if (p != null) {
        if (m == null) {
            m = new TreeMap<String, PropertyDescriptor>();
            cache.put(propertyClassName, m);
        }
        m.put(propertyName, p);
    }

    return p;
}
 
Example 17
Source File: ObjectUtils.java    From rice with Educational Community License v2.0 4 votes vote down vote up
public static void setObjectPropertyDeep(Object bo, String propertyName, Class type, Object propertyValue,
            int depth) throws FormatException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
        // Base return cases to avoid null pointers & infinite loops
        if (depth == 0 || isNull(bo) || !PropertyUtils.isReadable(bo, propertyName)) {
            return;
        }

        // Removed this as the two remaining locations which call this are now performing the refresh themselves
        
        // need to materialize the updateable collections before resetting the property, because it may be used in the retrieval
//        try {
//            materializeUpdateableCollections(bo);
//        } catch(ClassNotPersistableException ex){
//            //Not all classes will be persistable in a collection. For e.g. externalizable business objects.
//            LOG.info("Not persistable dataObjectClass: "+bo.getClass().getName()+", field: "+propertyName);
//        }

    // Set the property in the BO
        setObjectProperty(bo, propertyName, type, propertyValue);

        // Now drill down and check nested BOs and BO lists
        PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(bo.getClass());
        for (int i = 0; i < propertyDescriptors.length; i++) {
            PropertyDescriptor propertyDescriptor = propertyDescriptors[i];

            // Business Objects
            if (propertyDescriptor.getPropertyType() != null && (BusinessObject.class).isAssignableFrom(
                    propertyDescriptor.getPropertyType()) && PropertyUtils.isReadable(bo,
                    propertyDescriptor.getName())) {
                Object nestedBo = getPropertyValue(bo, propertyDescriptor.getName());
                if (nestedBo instanceof BusinessObject) {
                    setObjectPropertyDeep(nestedBo, propertyName, type, propertyValue, depth - 1);
                }
            }

            // Lists
            else if (propertyDescriptor.getPropertyType() != null && (List.class).isAssignableFrom(
                    propertyDescriptor.getPropertyType()) && getPropertyValue(bo, propertyDescriptor.getName())
                    != null) {

                List propertyList = (List) getPropertyValue(bo, propertyDescriptor.getName());

                // Complete Hibernate Hack - fetches the proxied List into the PersistenceContext and sets it on the BO Copy.
//                if (propertyList instanceof PersistentBag) {
//                    try {
//                        PersistentBag bag = (PersistentBag) propertyList;
//                        PersistableBusinessObject pbo =
//                                (PersistableBusinessObject) KRADServiceLocator.getEntityManagerFactory()
//                                        .createEntityManager().find(bo.getClass(), bag.getKey());
//                        Field field1 = pbo.getClass().getDeclaredField(propertyDescriptor.getName());
//                        Field field2 = bo.getClass().getDeclaredField(propertyDescriptor.getName());
//                        field1.setAccessible(true);
//                        field2.setAccessible(true);
//                        field2.set(bo, field1.get(pbo));
//                        propertyList = (List) getPropertyValue(bo, propertyDescriptor.getName());
//                        ;
//                    } catch (Exception e) {
//                        LOG.error(e.getMessage(), e);
//                    }
//                }
                // End Complete Hibernate Hack

                for (Object listedBo : propertyList) {
                    if (listedBo != null && listedBo instanceof BusinessObject) {
                        setObjectPropertyDeep(listedBo, propertyName, type, propertyValue, depth - 1);
                    }
                } // end for
            }
        } // end for
    }
 
Example 18
Source File: QueryGenerator.java    From teaching with Apache License 2.0 4 votes vote down vote up
/**
 * 组装Mybatis Plus 查询条件
 * <p>使用此方法 需要有如下几点注意:   
 * <br>1.使用QueryWrapper 而非LambdaQueryWrapper;
 * <br>2.实例化QueryWrapper时不可将实体传入参数   
 * <br>错误示例:如QueryWrapper<JeecgDemo> queryWrapper = new QueryWrapper<JeecgDemo>(jeecgDemo);
 * <br>正确示例:QueryWrapper<JeecgDemo> queryWrapper = new QueryWrapper<JeecgDemo>();
 * <br>3.也可以不使用这个方法直接调用 {@link #initQueryWrapper}直接获取实例
 */
public static void installMplus(QueryWrapper<?> queryWrapper,Object searchObj,Map<String, String[]> parameterMap) {
	
	/*
	 * 注意:权限查询由前端配置数据规则 当一个人有多个所属部门时候 可以在规则配置包含条件 orgCode 包含 #{sys_org_code}
	但是不支持在自定义SQL中写orgCode in #{sys_org_code} 
	当一个人只有一个部门 就直接配置等于条件: orgCode 等于 #{sys_org_code} 或者配置自定义SQL: orgCode = '#{sys_org_code}'
	*/
	
	//区间条件组装 模糊查询 高级查询组装 简单排序 权限查询
	PropertyDescriptor origDescriptors[] = PropertyUtils.getPropertyDescriptors(searchObj);
	Map<String,SysPermissionDataRuleModel> ruleMap = getRuleMap();
	
	//权限规则自定义SQL表达式
	for (String c : ruleMap.keySet()) {
		if(oConvertUtils.isNotEmpty(c) && c.startsWith(SQL_RULES_COLUMN)){
			queryWrapper.and(i ->i.apply(getSqlRuleValue(ruleMap.get(c).getRuleValue())));
		}
	}
	
	String name, type;
	for (int i = 0; i < origDescriptors.length; i++) {
		//aliasName = origDescriptors[i].getName();  mybatis  不存在实体属性 不用处理别名的情况
		name = origDescriptors[i].getName();
		type = origDescriptors[i].getPropertyType().toString();
		try {
			if (judgedIsUselessField(name)|| !PropertyUtils.isReadable(searchObj, name)) {
				continue;
			}
			
			//数据权限查询
			if(ruleMap.containsKey(name)) {
				addRuleToQueryWrapper(ruleMap.get(name), name, origDescriptors[i].getPropertyType(), queryWrapper);
			}
			
			// 添加 判断是否有区间值
			String endValue = null,beginValue = null;
			if (parameterMap != null && parameterMap.containsKey(name + BEGIN)) {
				beginValue = parameterMap.get(name + BEGIN)[0].trim();
				addQueryByRule(queryWrapper, name, type, beginValue, QueryRuleEnum.GE);
				
			}
			if (parameterMap != null && parameterMap.containsKey(name + END)) {
				endValue = parameterMap.get(name + END)[0].trim();
				addQueryByRule(queryWrapper, name, type, endValue, QueryRuleEnum.LE);
			}
			
			//判断单值  参数带不同标识字符串 走不同的查询
			//TODO 这种前后带逗号的支持分割后模糊查询需要否 使多选字段的查询生效
			Object value = PropertyUtils.getSimpleProperty(searchObj, name);
			if (null != value && value.toString().startsWith(COMMA) && value.toString().endsWith(COMMA)) {
				String multiLikeval = value.toString().replace(",,", COMMA);
				String[] vals = multiLikeval.substring(1, multiLikeval.length()).split(COMMA);
				final String field = oConvertUtils.camelToUnderline(name);
				if(vals.length>1) {
					queryWrapper.and(j -> {
						j = j.like(field,vals[0]);
						for (int k=1;k<vals.length;k++) {
							j = j.or().like(field,vals[k]);
						}
						return j;
					});
				}else {
					queryWrapper.and(j -> j.like(field,vals[0]));
				}
			}else {
				//根据参数值带什么关键字符串判断走什么类型的查询
				QueryRuleEnum rule = convert2Rule(value);
				value = replaceValue(rule,value);
				// add -begin 添加判断为字符串时设为全模糊查询
				//if( (rule==null || QueryRuleEnum.EQ.equals(rule)) && "class java.lang.String".equals(type)) {
					// 可以设置左右模糊或全模糊,因人而异
					//rule = QueryRuleEnum.LIKE;
				//}
				// add -end 添加判断为字符串时设为全模糊查询
				addEasyQuery(queryWrapper, name, rule, value);
			}
			
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
	}
	// 排序逻辑 处理 
	doMultiFieldsOrder(queryWrapper, parameterMap);
			
	//高级查询
	doSuperQuery(queryWrapper, parameterMap);
	
}
 
Example 19
Source File: DataDictionary.java    From rice with Educational Community License v2.0 4 votes vote down vote up
/**
 * @param propertyClass
 * @param propertyName
 * @return PropertyDescriptor for the getter for the named property of the given class, if one exists.
 */
public static PropertyDescriptor buildSimpleReadDescriptor(Class propertyClass, String propertyName) {
    if (propertyClass == null) {
        throw new IllegalArgumentException("invalid (null) propertyClass");
    }
    if (StringUtils.isBlank(propertyName)) {
        throw new IllegalArgumentException("invalid (blank) propertyName");
    }

    PropertyDescriptor p = null;

    // check to see if we've cached this descriptor already. if yes, return true.
    String propertyClassName = propertyClass.getName();
    Map<String, PropertyDescriptor> m = cache.get(propertyClassName);
    if (null != m) {
        p = m.get(propertyName);
        if (null != p) {
            return p;
        }
    }

    // Use PropertyUtils.getPropertyDescriptors instead of manually constructing PropertyDescriptor because of
    // issues with introspection and generic/co-variant return types
    // See https://issues.apache.org/jira/browse/BEANUTILS-340 for more details

    PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(propertyClass);
    if (ArrayUtils.isNotEmpty(descriptors)) {
        for (PropertyDescriptor descriptor : descriptors) {
            if (descriptor.getName().equals(propertyName)) {
                p = descriptor;
            }
        }
    }

    // cache the property descriptor if we found it.
    if (p != null) {
        if (m == null) {
            m = new TreeMap<String, PropertyDescriptor>();
            cache.put(propertyClassName, m);
        }
        m.put(propertyName, p);
    }

    return p;
}
 
Example 20
Source File: JPAPlugin.java    From restcommander with Apache License 2.0 4 votes vote down vote up
private Object makeCompositeKey(Model model) throws Exception {
    initProperties();
    Class<?> idClass = getCompositeKeyClass();
    Object id = idClass.newInstance();
    PropertyDescriptor[] idProperties = PropertyUtils.getPropertyDescriptors(idClass);
    if(idProperties == null || idProperties.length == 0)
        throw new UnexpectedException("Composite id has no properties: "+idClass.getName());
    for (PropertyDescriptor idProperty : idProperties) {
        // do we have a field for this?
        String idPropertyName = idProperty.getName();
        // skip the "class" property...
        if(idPropertyName.equals("class"))
            continue;
        Model.Property modelProperty = this.properties.get(idPropertyName);
        if(modelProperty == null)
            throw new UnexpectedException("Composite id property missing: "+clazz.getName()+"."+idPropertyName
                    +" (defined in IdClass "+idClass.getName()+")");
        // sanity check
        Object value = modelProperty.field.get(model);

        if(modelProperty.isMultiple)
            throw new UnexpectedException("Composite id property cannot be multiple: "+clazz.getName()+"."+idPropertyName);
        // now is this property a relation? if yes then we must use its ID in the key (as per specs)
            if(modelProperty.isRelation){
            // get its id
            if(!Model.class.isAssignableFrom(modelProperty.type))
                throw new UnexpectedException("Composite id property entity has to be a subclass of Model: "
                        +clazz.getName()+"."+idPropertyName);
            // we already checked that cast above
            @SuppressWarnings("unchecked")
            Model.Factory factory = Model.Manager.factoryFor((Class<? extends Model>) modelProperty.type);
            if(factory == null)
                throw new UnexpectedException("Failed to find factory for Composite id property entity: "
                        +clazz.getName()+"."+idPropertyName);
            // we already checked that cast above
            if(value != null)
                value = factory.keyValue((Model) value);
        }
        // now affect the composite id with this id
        PropertyUtils.setSimpleProperty(id, idPropertyName, value);
    }
    return id;
}