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

The following examples show how to use org.apache.commons.beanutils.PropertyUtils#getSimpleProperty() . 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: ExcelWorkSheetHandler.java    From excelReader with MIT License 6 votes vote down vote up
private String getPropertyValue(Object targetObj, String propertyName) {
  String value = "";
  if (null == targetObj || StringUtils.isBlank(propertyName)) {
    LOG.error("targetObj or propertyName is null, both require to retrieve a value");
    return value;
  }

  try {
    if (PropertyUtils.isReadable(targetObj, propertyName)) {
      Object v = PropertyUtils.getSimpleProperty(targetObj, propertyName);
      if (null != v && StringUtils.isNotBlank(v.toString())) {
        value = v.toString();
      }
    } else {
      LOG.error("Given property (" + propertyName + ") is not readable!");
    }
  } catch (IllegalAccessException iae) {
    LOG.error(iae.getMessage());
  } catch (InvocationTargetException ite) {
    LOG.error(ite.getMessage());
  } catch (NoSuchMethodException nsme) {
    LOG.error(nsme.getMessage());
  }
  return value;
}
 
Example 2
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 3
Source File: FiscalYearMakersDaoOjb.java    From kfs with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Builds a String containing foreign key values for the given reference of the business object
 * 
 * @param businessObject business object instance with reference
 * @param referenceName name of reference
 * @return String of foreign key values or null if any of the foreign key values are null
 */
protected String getForeignKeyStringForReference( FiscalYearMaker fiscalYearMaker, FiscalYearBasedBusinessObject businessObject, String referenceName) throws Exception {
    Map<String, String> foreignKeyToPrimaryKeyMap = fiscalYearMaker.getForeignKeyMappings( referenceName );

    StringBuilder foreignKeyString = new StringBuilder(80);
    for (String fkFieldName : foreignKeyToPrimaryKeyMap.keySet()) {
        Object fkFieldValue = PropertyUtils.getSimpleProperty(businessObject, fkFieldName);
        if (fkFieldValue != null) {
            foreignKeyString.append( fkFieldValue.toString() ).append( KEY_STRING_DELIMITER );
        } else {
            foreignKeyString.setLength(0);
            break;
        }
    }

    return foreignKeyString.toString();
}
 
Example 4
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 5
Source File: FiscalYearMakersDaoOjb.java    From kfs with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Validates the parent record(s) exists for the child record by retrieving the OJB reference (if found and foreign keys have
 * value)
 * 
 * @param childRecord child record we are inserting
 * @param parentClass class for parent of child
 * @param parentKeys Set of parent key Strings that have been written
 * @param copyErrors Collection for adding error messages
 * @return true if the parent record(s) exist, false otherwise
 */
protected boolean validateChildParentReferencesExist(FiscalYearMaker objectFiscalYearMaker,FiscalYearBasedBusinessObject childRecord, Class<? extends FiscalYearBasedBusinessObject> parentClass, Set<String> parentKeys, List<String> copyErrors) throws Exception {
    boolean allChildParentReferencesExist = true;
    boolean foundParentReference = false;

    // get all references for child class
    @SuppressWarnings("rawtypes")
    Map<String, Class> referenceObjects = objectFiscalYearMaker.getReferenceObjectProperties();

    // iterate through to find references with the parent class
    for (String referenceName : referenceObjects.keySet()) {
        Class<? extends PersistableBusinessObject> referenceClass = referenceObjects.get(referenceName);

        if (parentClass.isAssignableFrom(referenceClass)) {
            foundParentReference = true;

            String foreignKeyString = getForeignKeyStringForReference(objectFiscalYearMaker, childRecord, referenceName);
            if (StringUtils.isNotBlank(foreignKeyString) 
                    && !parentKeys.contains(foreignKeyString)) {
                // attempt to retrieve the parent reference in case it already existed
                getPersistenceBroker(true).retrieveReference(childRecord, referenceName);
                PersistableBusinessObject reference = (PersistableBusinessObject) PropertyUtils.getSimpleProperty(childRecord, referenceName);
                if (ObjectUtils.isNull(reference)) {
                    allChildParentReferencesExist = false;
                    writeMissingParentCopyError(childRecord, parentClass, foreignKeyString, copyErrors);
                    LOG.warn( "Missing Parent Object: " + copyErrors.get(copyErrors.size()-1));
                } else {
                    parentKeys.add(foreignKeyString);
                }
            }
        }
    }

    if (!foundParentReference) {
        LOG.warn(String.format("\n!!! NO relationships between child %s and parent %s found in OJB descriptor\n", childRecord.getClass().getName(), parentClass.getName()));
    }

    return allChildParentReferencesExist;
}
 
Example 6
Source File: MyBeanUtils.java    From jeecg 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)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 7
Source File: HqlGenerateUtil.java    From jeecg with Apache License 2.0 5 votes vote down vote up
/**
 * 判断这个类是不是所以属性都为空
 * 
 * @param param
 * @return
 */
private static boolean itIsNotAllEmpty(Object param) {
	boolean isNotEmpty = false;
	try {
		PropertyDescriptor origDescriptors[] = PropertyUtils
				.getPropertyDescriptors(param);
		String name;
		for (int i = 0; i < origDescriptors.length; i++) {
			name = origDescriptors[i].getName();
			if ("class".equals(name)
					|| !PropertyUtils.isReadable(param, name)) {
				continue;
			}
			if (Map.class.isAssignableFrom(origDescriptors[i]
					.getPropertyType())) {
				Map<?, ?> map = (Map<?, ?>) PropertyUtils
						.getSimpleProperty(param, name);
				if (map != null && map.size() > 0) {
					isNotEmpty = true;
					break;
				}
			} else if (Collection.class.isAssignableFrom(origDescriptors[i]
					.getPropertyType())) {
				Collection<?> c = (Collection<?>) PropertyUtils
						.getSimpleProperty(param, name);
				if (c != null && c.size() > 0) {
					isNotEmpty = true;
					break;
				}
			} else if (StringUtil.isNotEmpty(PropertyUtils
					.getSimpleProperty(param, name))) {
				isNotEmpty = true;
				break;
			}
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
	return isNotEmpty;
}
 
Example 8
Source File: PostProcessorServiceImpl.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
  * Logs further details of OptimisticLockExceptions, using the given depth value to limit recursion Just In Case
  *
  * @param depth
  * @param t
  */
 private void logOptimisticDetails(int depth, Throwable t) {
     if ((depth > 0) && (t != null)) {
Object sourceObject = null;
boolean optLockException = false;
if ( t instanceof javax.persistence.OptimisticLockException ) {
    sourceObject = ((javax.persistence.OptimisticLockException)t).getEntity();
    optLockException = true;
} else if ( t instanceof OptimisticLockingFailureException ) {
    sourceObject = ((OptimisticLockingFailureException)t).getMessage();
    optLockException = true;
} else if ( t.getClass().getName().equals( "org.apache.ojb.broker.OptimisticLockException" ) ) {
       try {
                 sourceObject = PropertyUtils.getSimpleProperty(t, "sourceObject");
             } catch (Exception ex) {
                 LOG.warn( "Unable to retrieve source object from OJB OptimisticLockException", ex );
             }
             optLockException = true;
}
if ( optLockException ) {
             if (sourceObject != null) {
                 if ( sourceObject instanceof String ) {
                     LOG.error("source of OptimisticLockException Unknown.  Message: " + sourceObject);
                 } else {
                     LOG.error("source of OptimisticLockException = " + sourceObject.getClass().getName() + " ::= " + sourceObject);
                 }
             }
         } else {
             Throwable cause = t.getCause();
             if (cause != t) {
                 logOptimisticDetails(--depth, cause);
             }
         }
     }
 }
 
Example 9
Source File: BeanConfigurationAdapter.java    From knox with Apache License 2.0 5 votes vote down vote up
@Override
public Object getConfigurationValue( String name ) throws ConfigurationException {
  try {
    return PropertyUtils.getSimpleProperty( bean, name );
  } catch( Exception e ) {
    throw new ConfigurationException("", e );
  }
}
 
Example 10
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 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: 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)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){
                	    copyProperty(tobean, name, value);
                  }
              }
              catch (java.lang.IllegalArgumentException ie) {
                  ; // Should not happen
              }
              catch (Exception e) {
                  ; // Should not happen
              }

          }
      }
  }
 
Example 13
Source File: HqlGenerateUtil.java    From jeewx with Apache License 2.0 5 votes vote down vote up
/**
 * 判断这个类是不是所以属性都为空
 * 
 * @param param
 * @return
 */
private static boolean itIsNotAllEmpty(Object param) {
	boolean isNotEmpty = false;
	try {
		PropertyDescriptor origDescriptors[] = PropertyUtils
				.getPropertyDescriptors(param);
		String name;
		for (int i = 0; i < origDescriptors.length; i++) {
			name = origDescriptors[i].getName();
			if ("class".equals(name)
					|| !PropertyUtils.isReadable(param, name)) {
				continue;
			}
			if (Map.class.isAssignableFrom(origDescriptors[i]
					.getPropertyType())) {
				Map<?, ?> map = (Map<?, ?>) PropertyUtils
						.getSimpleProperty(param, name);
				if (map != null && map.size() > 0) {
					isNotEmpty = true;
					break;
				}
			} else if (Collection.class.isAssignableFrom(origDescriptors[i]
					.getPropertyType())) {
				Collection<?> c = (Collection<?>) PropertyUtils
						.getSimpleProperty(param, name);
				if (c != null && c.size() > 0) {
					isNotEmpty = true;
					break;
				}
			} else if (StringUtil.isNotEmpty(PropertyUtils
					.getSimpleProperty(param, name))) {
				isNotEmpty = true;
				break;
			}
		}
	} catch (Exception e) {
           e.printStackTrace();
	}
	return isNotEmpty;
}
 
Example 14
Source File: GroovyReflectionCompletion.java    From beakerx with Apache License 2.0 4 votes vote down vote up
List<String> autocompleteFromObject(List<String> parts) {
		
		List<String> lowPriorityCompletions = Arrays.asList("class","metaClass");

		List<String> filteredCompletions = Arrays.asList("empty");
		
		List<String> iterableOnlyCompletions = Arrays.asList("join(");

	
	
		ArrayList<String> result = new ArrayList<String>();
		
		try {

			String bindingReference = parts.get(0);
			Matcher m = indexedAccessPattern.matcher(bindingReference);
			
			Object value;
			if(m.matches()) {
				List collValue = (List)binding.getVariable(m.group(1));
				value = collValue.get(Integer.parseInt(m.group(2)));
			}
			else
				value = binding.getVariable(bindingReference);

			int i = 1;
			for(; i<parts.size()-1; ++i) {
				String partExpr = parts.get(i);
				
				
				Matcher m2 = indexedAccessPattern.matcher(partExpr);
				if(m2.matches()) {
					value = PropertyUtils.getIndexedProperty(value, partExpr);
				}
				else {
					value = PropertyUtils.getSimpleProperty(value, partExpr);
				}
			
				if(value == null) {
					// We can't complete anything on it
					// TODO: we could complete on the static type one day
					return result;
				}
			}
			
			String completionToken = parts.size() > 1 ? parts.get(parts.size()-1) : "";
			
			List<String> properties = getObjectPropertyNames(value); 
			
			List<String> lowPri = new ArrayList<String>();
		
			properties.forEach((String key) -> {
				if(key.startsWith(completionToken)) {
					if(lowPriorityCompletions.contains(key)) {
						lowPri.add(key);
					}
					else {
						result.add(key);
					}
				}
			});
			
			if(value instanceof Map) {
				Map<String,?> mapValue = (Map<String,?>)value;
				mapValue.keySet().stream()
								 .filter(k -> k.startsWith(completionToken))
								 .forEach(k -> result.add(k));
			}
			
			if(value instanceof Iterable || value instanceof Map) {
				result.addAll(SUPPLEMENTARY_COLLECTION_COMPLETIONS);
				result.addAll(iterableOnlyCompletions);
			}
			
			if(value instanceof String) {
				result.addAll(STRING_COMPLETIONS);
			}
			
//			result.addAll(lowPri);
			
			result.removeIf(v -> !v.startsWith(completionToken));
				
			result.removeAll(filteredCompletions);
			
			// Finally, add method names
			result.addAll(getObjectMethodCompletions(value, completionToken));
	
		} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
			e.printStackTrace();
		}
		return result;
	}
 
Example 15
Source File: SqlGenerateUtil.java    From jeecg with Apache License 2.0 4 votes vote down vote up
/**
 * 解析出where执行语句
 * @param searchObj
 * @param parameterMap
 * @return
 */
public static StringBuffer generateWhere(Object searchObj,Map<String,String[]> parameterMap){
	StringBuffer whereSql = new StringBuffer(" where 1=1 ");
	try {
		PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(searchObj.getClass());
		
		//拼接sql查询的条件
		for(PropertyDescriptor propertyDescriptor:propertyDescriptors){
			String propertyType = propertyDescriptor.getPropertyType().toString();//属性类型
			String propertyName = propertyDescriptor.getName();//属性名称
			Object propertyValue = PropertyUtils.getSimpleProperty(searchObj, propertyName);//属性值
			
			String dbColumnName = getDbNameByFieldName(propertyDescriptor);//对应的数据库中的列名
			// 添加 判断是否有区间值
			String beginValue = null;
			String endValue = null;
			
			if (parameterMap != null && (parameterMap.containsKey(propertyName + BEGIN)||parameterMap.containsKey(propertyName + END))){
				if (parameterMap != null && parameterMap.containsKey(propertyName + BEGIN)) {
					beginValue = parameterMap.get(propertyName + BEGIN)[0].trim();
					if(StringUtil.isNotEmpty(beginValue)){
						String beginValueReturn = getValueForType(propertyName + BEGIN,beginValue,propertyType);
						if(StringUtil.isNotEmpty(beginValueReturn)){
							whereSql.append("and "+dbColumnName+">="+beginValueReturn+" ");
						}
					}
				}
				if (parameterMap != null && parameterMap.containsKey(propertyName + END)) {
					endValue = parameterMap.get(propertyName + END)[0].trim();
					if(StringUtil.isNotEmpty(endValue)){
						String endValueReturn = getValueForType(propertyName + END,endValue,propertyType);
						if(StringUtil.isNotEmpty(endValueReturn)){
							whereSql.append("and "+dbColumnName+"<="+endValueReturn+" ");
						}
					}
				}
			}else{
				if(StringUtil.isNotEmpty(propertyValue)){
					String propertyValueReturn = getValueForType(propertyName,propertyValue,propertyType);
					if(StringUtil.isNotEmpty(propertyValueReturn)){
						whereSql.append("and "+dbColumnName+"="+propertyValueReturn+" ");
					}
				}
			}
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
	
	return whereSql;
}
 
Example 16
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 17
Source File: QueryGenerator.java    From jeecg-boot-with-activiti with MIT License 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,SysPermissionDataRule> 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);
	
}