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

The following are Jave code examples for showing how to use getProperty() 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: urule   File: PackageServletHandler.java   View Source Code Vote up 6 votes
private void instanceChildObject(Object obj,String propertyName){
	int pointIndex=propertyName.indexOf(".");
	if(pointIndex==-1){
		return;
	}
	String name=propertyName.substring(0,pointIndex);
	propertyName=propertyName.substring(pointIndex+1);
	try {
		Object instance=PropertyUtils.getProperty(obj, name);
		if(instance!=null){
			instanceChildObject(instance,propertyName);
			return;
		}
		Object targetEntity=new GeneralEntity(name);
		PropertyUtils.setProperty(obj, name, targetEntity);
		instanceChildObject(targetEntity,propertyName);
	} catch (Exception e) {
		throw new RuleException(e);
	}
}
 
Example 2
Project: FastDFS_Client   File: FieldMateData.java   View Source Code Vote up 6 votes
/**
 * 获取动态属性长度
 * 
 * @param bean
 * @param charset
 * @return
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 * @throws NoSuchMethodException
 */
@SuppressWarnings("unchecked")
public int getDynamicFieldByteSize(Object bean, Charset charset)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    Object value = PropertyUtils.getProperty(bean, field.getName());
    if (null == value) {
        return 0;
    }
    switch (dynamicFieldType) {
    // 如果是打包剩余的所有Byte
    case allRestByte:
        return ((String) value).getBytes(charset).length;
    // 如果是文件matedata
    case matedata:
        return MetadataMapper.toByte((Set<MateData>) value, charset).length;
    default:
        return getFieldSize(field);
    }
}
 
Example 3
Project: delivery-sdk-java   File: ThymeleafTemplateEngine.java   View Source Code Vote up 6 votes
private String getContentTypeFromModel(Object model) {
    if (model instanceof ContentItem) {
        ContentItem contentItem = (ContentItem) model;
        return contentItem.getSystem().getType();
    }
    ContentItemMapping contentItemMapping = model.getClass().getAnnotation(ContentItemMapping.class);
    if (contentItemMapping != null) {
        return contentItemMapping.value();
    }
    try {
        Object system = PropertyUtils.getProperty(model, "system");
        if (system instanceof System) {
            return ((System) system).getType();
        }
    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
        logger.debug("Unable to find System property on model", e);
    }
    return null;
}
 
Example 4
Project: Biliomi   File: XmlElementPathBeanComparator.java   View Source Code Vote up 6 votes
@Override
public int compare(T o1, T o2) {
  Comparable obj1 = null;
  Comparable obj2 = null;

  try {
    obj1 = (Comparable) PropertyUtils.getProperty(o1, this.propertyPath);
    obj2 = (Comparable) PropertyUtils.getProperty(o2, this.propertyPath);
  } catch (NestedNullException ignored) {
    // Ignored, als het property NULL is, dan vergelijken met NULL
  } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
    throw new IllegalArgumentException("Could not retrieve property " + this.propertyPath, e);
  }

  Comparator<Comparable<Object>> objectComparator = null;
  if ((obj1 != null && obj2 != null) && obj1 instanceof String) {
    obj1 = ((String) obj1).toLowerCase().trim();
    obj2 = ((String) obj2).toLowerCase().trim();

    if (!StringUtils.isEmpty((String) obj1) && !StringUtils.isEmpty((String) obj2)) {
      if (StringUtils.isNumeric((String) obj1) && StringUtils.isNumeric((String) obj2)) {
        objectComparator = Comparator.comparingDouble(o -> new Double(String.valueOf(o)));
      }
    }
  }

  if (objectComparator == null) {
    objectComparator = Comparator.naturalOrder();
  }

  //noinspection unchecked
  return Comparator.nullsLast(objectComparator).compare(obj1, obj2);
}
 
Example 5
Project: Biliomi   File: UserSettingsProducer.java   View Source Code Vote up 6 votes
@Produces
@CoreSetting("PRODUCER")
public String getUserSetting(InjectionPoint injectionPoint) {
  Annotated annotated = injectionPoint.getAnnotated();

  if (annotated.isAnnotationPresent(CoreSetting.class)) {
    String settingPath = annotated.getAnnotation(CoreSetting.class).value();
    Object object = yamlCoreSettings;
    String[] split = settingPath.split("\\.");
    int c = 0;

    while (c < split.length) {
      try {
        object = PropertyUtils.getProperty(object, split[c]);
        c++;
      } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
        LogManager.getLogger(getClass()).error("Failed retrieving setting " + settingPath, e);
        return null;
      }
    }

    return String.valueOf(object);
  }

  return null;
}
 
Example 6
Project: QLExpress   File: ExpressUtil.java   View Source Code Vote up 6 votes
public static Object getProperty(Object bean, Object name) {
	try {
		if(bean.getClass().isArray() && name.equals("length")){
		   return Array.getLength(bean);
		}else if (bean instanceof Class) {
			if(name.equals("class")){
				return bean;
			}else{
				Field f = ((Class<?>) bean).getDeclaredField(name.toString());
				return f.get(null);
			}
		}else if(bean instanceof Map ){
			return ((Map<?,?>)bean).get(name);
	    }else {
			Object obj = PropertyUtils.getProperty(bean, name.toString());
			return obj;
		}
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example 7
Project: spring-data-mapdb   File: PropertyComparator.java   View Source Code Vote up 6 votes
/**
 *
 * @param o1
 *            An entry in a map
 * @param o2
 *            Another entry in the map
 * @return Comparison result
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public int compare(Object o1, Object o2) {

	try {
		Object o1Field = PropertyUtils.getProperty(o1, this.attributeName);
		Object o2Field = PropertyUtils.getProperty(o2, this.attributeName);

		if (o1Field == null) {
			return this.direction;
		}
		if (o2Field == null) {
			return -1 * this.direction;
		}
		if (o1Field instanceof Comparable && o2Field instanceof Comparable) {
			return this.direction * ((Comparable) o1Field).compareTo((Comparable) o2Field);
		}

	} catch (Exception ignore) {
		return 0;
	}

	return 0;
}
 
Example 8
Project: microservice   File: WorkflowTraceService.java   View Source Code Vote up 6 votes
/**
 * 获取当前节点信息
 *
 * @param processInstance
 * @return
 */
private Task getCurrentTaskInfo(ProcessInstance processInstance) {
    Task currentTask = null;
    try {
        String activitiId = (String) PropertyUtils.getProperty(processInstance, "activityId");
        logger.debug("current activity id: {}", activitiId);

        currentTask = taskService.createTaskQuery().processInstanceId(processInstance.getId()).taskDefinitionKey(activitiId)
                .singleResult();
        logger.debug("current task for processInstance: {}", ToStringBuilder.reflectionToString(currentTask));

    } catch (Exception e) {
        logger.error("can not get property activityId from processInstance: {}", processInstance);
    }
    return currentTask;
}
 
Example 9
Project: validator-web   File: BeanReader.java   View Source Code Vote up 6 votes
@SuppressWarnings({ "unchecked" })
public Object getProperty(String name) {
    if (bean instanceof Map) {
        if (bean instanceof MultiValueMap) {
            MultiValueMap<String, ?> valueMap = (MultiValueMap<String, ?>) bean;
            List<?> values = valueMap.get(name);
            if (values == null || values.isEmpty()) {
                return null;
            } else if (values.size() == 1) {
                return values.get(0);
            }
            return values;
        }
        return ((Map<String, ?>)bean).get(name);
    }
    try {
        return PropertyUtils.getProperty(bean, name);
    } catch (Exception e) {
        if (log.isWarnEnabled()) {
            log.warn("Property '" + name + "' does not exist for object of " +
                    "type " + bean.getClass().getName() + ".");
        }
    }
    return null;
}
 
Example 10
Project: flatworm   File: PropertyUtilsMappingStrategy.java   View Source Code Vote up 6 votes
@Override
public void mapBean(Object bean, String beanName, String property, Object value,
                    Map<String, ConversionOptionBO> conversionOption) throws FlatwormParserException {
    try {
        ConversionOptionBO option = conversionOption.get("append");
        if (option != null && "true".equalsIgnoreCase(option.getValue())) {
            Object currentValue = PropertyUtils.getProperty(bean, property);
            if (currentValue != null)
                value = currentValue.toString() + value;
        }
        PropertyUtils.setProperty(bean, property, value);
    } catch (Exception e) {
        log.error("While running set property method for " + beanName + "." + property
                + " with value '" + value + "'", e);
        throw new FlatwormParserException("Setting field " + beanName + "." + property);
    }
}
 
Example 11
Project: OpenMobster   File: TestBeanSyntax.java   View Source Code Vote up 6 votes
private Object initializeSimpleProperty(Object parentObject, String property, PropertyDescriptor propertyMetaData)
throws Exception
{
	Object propertyValue = null;
	
	//A Regular Property
	propertyValue = PropertyUtils.getProperty(parentObject, property); 
	if(propertyValue == null)
	{
		Object newlyInitialized = propertyMetaData.getPropertyType().newInstance();
		PropertyUtils.setProperty(parentObject, property, newlyInitialized);
		propertyValue = newlyInitialized;
	}		
	
	return propertyValue;
}
 
Example 12
Project: simbest-cores   File: SysUserDecorator.java   View Source Code Vote up 6 votes
@Override
public void decorate(Object bean, String property, Object strategy) {		
	try {
		Object key = PropertyUtils.getProperty(bean, property);		
		if(key != null){
			SysUser sysUser = null;
			if(key instanceof Integer)
				sysUser = sysUserAdvanceService.loadByKey((Integer)key);	
			if(key instanceof String)
				sysUser = sysUserAdvanceService.loadByUnique((String)key);	
			if(sysUser != null)
				PropertyUtils.setProperty(bean, (String)strategy, sysUser.getUsername());				
		}
	} catch (NullPointerException | IllegalAccessException | InvocationTargetException
			| NoSuchMethodException e) {			
		log.error(Exceptions.getStackTraceAsString(e));
	}
}
 
Example 13
Project: easycode   File: SqlUtils.java   View Source Code Vote up 6 votes
public static String getInsertSql(Object entity,Table table, boolean includePk) 
		throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
	StringBuilder sql = new StringBuilder(),
				columnsStr = new StringBuilder(Symbol.L_PARENTHESIS),
				valuesStr = new StringBuilder(Symbol.L_PARENTHESIS);
	sql.append(" INSERT INTO ").append(Configuration.dialect
			.wrapQuote(table.getName()) + Symbol.SPACE);
	
	Collection<Column> columns = table.getColumns().values();
	for(Iterator<Column> ite = columns.iterator();ite.hasNext();) {
		Column column = ite.next();
		if(column.isPrimaryKey() && !includePk) 
			continue;
		columnsStr.append(Symbol.SPACE + Configuration.dialect
				.wrapQuote(column.getSqlName()) + (ite.hasNext() ? Symbol.COMMA : Symbol.EMPTY));
		
		Object data = PropertyUtils.getProperty(entity, column.getName());
		valuesStr.append(Symbol.SPACE + value2Sql(data) + (ite.hasNext() ? Symbol.COMMA : Symbol.EMPTY));
	}
	
	columnsStr.append(Symbol.R_PARENTHESIS);
	valuesStr.append(Symbol.R_PARENTHESIS);
	
	return sql.append(columnsStr).append(" VALUES").append(valuesStr).toString();
}
 
Example 14
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 15
Project: neoscada   File: DefaultExecutableFactory.java   View Source Code Vote up 5 votes
private static Object getReference ( final Map<String, Object> map, final String expression )
{
    try
    {
        return PropertyUtils.getProperty ( map, expression );
    }
    catch ( IllegalAccessException | InvocationTargetException | NoSuchMethodException e )
    {
        throw new RuntimeException ( e );
    }
}
 
Example 16
Project: crnk-framework   File: TaskToProjectRepository.java   View Source Code Vote up 5 votes
/**
 * A simple implementation of the removeRelations method which presents the general concept of the method.
 * It SHOULD NOT be used in production because of possible race condition - production ready code should perform an
 * atomic operation.
 *
 * @param task
 * @param projectIds
 * @param fieldName
 */
@Override
public void removeRelations(Task task, Iterable<ObjectId> projectIds, String fieldName) {
	try {
		if (PropertyUtils.getProperty(task, fieldName) != null) {
			Iterable<Project> projects = (Iterable<Project>) PropertyUtils.getProperty(task, fieldName);
			Iterator<Project> iterator = projects.iterator();
			while (iterator.hasNext()) {
				for (ObjectId projectIdToRemove : projectIds) {
					if (iterator.next().getId().equals(projectIdToRemove)) {
						iterator.remove();
						break;
					}
				}
			}
			List<Project> newProjectList = new ArrayList<>();
			for (Project project : projects) {
				newProjectList.add(project);
			}

			PropertyUtils.setProperty(task, fieldName, newProjectList);
			taskRepository.save(task);
		}
	} catch (Exception e) {
		throw new RuntimeException(e);
	}

}
 
Example 17
Project: crnk-framework   File: TaskToProjectRepository.java   View Source Code Vote up 5 votes
@Override
public Project findOneTarget(ObjectId objectId, String fieldName, QuerySpec requestParams) {
	Task task = taskRepository.findOne(objectId, requestParams);
	try {
		return (Project) PropertyUtils.getProperty(task, fieldName);
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example 18
Project: Biliomi   File: ModelRestService.java   View Source Code Vote up 5 votes
/**
 * Create a new entity, saving it to the database
 *
 * @param e The entity to create
 * @return An OK response with the new entity or NOT_MODIFIED on creation failure
 * @throws Exception When an internal error occurs
 */
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response restCreateEntity(T e) throws Exception {
  if (e == null || checkNotNullProperties(e)) {
    return Responses.badRequest();
  }

  Object id = PropertyUtils.getProperty(e, "id");
  if (id != null) {
    if (Long.class.isAssignableFrom(id.getClass()) && (long) id > 0) {
      return Responses.badRequest();
    }
  }

  try {
    T entity = createEntity(e);

    if (entity == null) {
      return Responses.notModified();
    }

    return Responses.ok(entity);
  } catch (ConstraintViolationException err) {
    return Responses.alreadyExists();
  }
}
 
Example 19
Project: obevo   File: BeanDataExtractor.java   View Source Code Vote up 5 votes
@Override
public Object extractValue(Object obj, String fieldName) {
    try {
        return PropertyUtils.getProperty(obj, fieldName);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 20
Project: microservice   File: WorkflowTraceService.java   View Source Code Vote up 5 votes
/**
 * 流程跟踪图
 *
 * @param processInstanceId 流程实例ID
 * @return 封装了各种节点信息
 */
public List<Map<String, Object>> traceProcess(String processInstanceId) throws Exception {
    Execution execution = runtimeService.createExecutionQuery().executionId(processInstanceId).singleResult();//执行实例
    Object property = PropertyUtils.getProperty(execution, "activityId");
    String activityId = "";
    if (property != null) {
        activityId = property.toString();
    }
    ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId)
            .singleResult();
    ProcessDefinitionEntity processDefinition = (ProcessDefinitionEntity) ((RepositoryServiceImpl) repositoryService)
            .getDeployedProcessDefinition(processInstance.getProcessDefinitionId());
    List<ActivityImpl> activitiList = processDefinition.getActivities();//获得当前任务的所有节点

    List<Map<String, Object>> activityInfos = new ArrayList<Map<String, Object>>();
    for (ActivityImpl activity : activitiList) {

        boolean currentActiviti = false;
        String id = activity.getId();

        // 当前节点
        if (id.equals(activityId)) {
            currentActiviti = true;
        }

        Map<String, Object> activityImageInfo = packageSingleActivitiInfo(activity, processInstance, currentActiviti);

        activityInfos.add(activityImageInfo);
    }

    return activityInfos;
}
 
Example 21
Project: stallion-core   File: MappedModel.java   View Source Code Vote up 5 votes
public default Object get(Object key) {
    try {
        if (PropertyUtils.isReadable(this, key.toString())) {

            return PropertyUtils.getProperty(this, key.toString());
        }

        return getAttributes().get(key);
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}
 
Example 22
Project: TranskribusCore   File: BeanComparator.java   View Source Code Vote up 5 votes
public int compare(Object o1, Object o2) {
//		if ((o1 instanceof Comparable) && (o2 instanceof Comparable)) {
//			// Compare simple type like String, Integer etc
//			Comparable c1 = ((Comparable) o1);
//			Comparable c2 = ((Comparable) o2);
//			return compare(c1, c2);
//		}

		try {
			o1 = PropertyUtils.getProperty(o1, sortPropertyName);
			o2 = PropertyUtils.getProperty(o2, sortPropertyName);
			
			if (o1 == null && o2 == null) {
				return 0;
			}
			else if (o1 == null && o2 != null) {
				return -1;
			} else if (o1 != null && o2 == null) {
				return 1;
			}
			
			if ((o1 instanceof Comparable) && (o2 instanceof Comparable)) {
				// Compare simple type like String, Integer etc
				Comparable c1 = ((Comparable) o1);
				Comparable c2 = ((Comparable) o2);
				return compare(c1, c2);
			}			
		} 
		catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
			return 0;
		}

		return 0;
	}
 
Example 23
Project: Shop-for-JavaWeb   File: ActTaskService.java   View Source Code Vote up 5 votes
/**
 * 流程跟踪图信息
 * @param processInstanceId		流程实例ID
 * @return	封装了各种节点信息
 */
public List<Map<String, Object>> traceProcess(String processInstanceId) throws Exception {
	Execution execution = runtimeService.createExecutionQuery().executionId(processInstanceId).singleResult();//执行实例
	Object property = PropertyUtils.getProperty(execution, "activityId");
	String activityId = "";
	if (property != null) {
		activityId = property.toString();
	}
	ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId)
			.singleResult();
	ProcessDefinitionEntity processDefinition = (ProcessDefinitionEntity) ((RepositoryServiceImpl) repositoryService)
			.getDeployedProcessDefinition(processInstance.getProcessDefinitionId());
	List<ActivityImpl> activitiList = processDefinition.getActivities();//获得当前任务的所有节点

	List<Map<String, Object>> activityInfos = new ArrayList<Map<String, Object>>();
	for (ActivityImpl activity : activitiList) {

		boolean currentActiviti = false;
		String id = activity.getId();

		// 当前节点
		if (id.equals(activityId)) {
			currentActiviti = true;
		}

		Map<String, Object> activityImageInfo = packageSingleActivitiInfo(activity, processInstance, currentActiviti);

		activityInfos.add(activityImageInfo);
	}

	return activityInfos;
}
 
Example 24
Project: katharsis-framework   File: TaskToProjectRepository.java   View Source Code Vote up 5 votes
/**
 * A simple implementation of the removeRelations method which presents the general concept of the method.
 * It SHOULD NOT be used in production because of possible race condition - production ready code should perform an
 * atomic operation.
 *
 * @param task
 * @param projectIds
 * @param fieldName
 */
@Override
public void removeRelations(Task task, Iterable<ObjectId> projectIds, String fieldName) {
    try {
        if (PropertyUtils.getProperty(task, fieldName) != null) {
            Iterable<Project> projects = (Iterable<Project>) PropertyUtils.getProperty(task, fieldName);
            Iterator<Project> iterator = projects.iterator();
            while (iterator.hasNext()) {
                for (ObjectId projectIdToRemove : projectIds) {
                    if (iterator.next().getId().equals(projectIdToRemove)) {
                        iterator.remove();
                        break;
                    }
                }
            }
            List<Project> newProjectList = new ArrayList<>();
            for (Project project: projects) {
                newProjectList.add(project);
            }

            PropertyUtils.setProperty(task, fieldName, newProjectList);
            taskRepository.save(task);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

}
 
Example 25
Project: helium   File: DatatablesHelper.java   View Source Code Vote up 5 votes
private static Object getPropietatValor(
		Object registre,
		String propietatNom,
		List<PropertyDescriptor> descriptors) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
	Object valor = null;
	try {
		int index = Integer.parseInt(propietatNom);
		valor = PropertyUtils.getProperty(registre, descriptors.get(index).getName());
	} catch (NumberFormatException ex) {
		if (propietatNom != null && !propietatNom.isEmpty() && !"<null>".equals(propietatNom)) {
			valor = PropertyUtils.getProperty(registre, propietatNom);
		}
	}
	return valor;
}
 
Example 26
Project: osframe   File: EntityUtil.java   View Source Code Vote up 5 votes
/**
 *获取实体中的指定字段值
 * @param obj 对象
 * @param field 字段
 * @return
 */
public static Object getEntityFieldValue(Object obj,String field){
    Object val=null;
    if(obj==null || StringUtil.isNull(field)){
        return val;
    }
    try{
        val=PropertyUtils.getProperty(obj, field);
    }catch (Exception e){
        e.printStackTrace();
    }
    return val;
}
 
Example 27
Project: katharsis-framework   File: TaskToProjectRepository.java   View Source Code Vote up 5 votes
@Override
public Iterable<Project> findManyTargets(ObjectId objectId, String fieldName, QueryParams requestParams) {
    Task task = taskRepository.findOne(objectId, requestParams);
    try {
        return (Iterable<Project>) PropertyUtils.getProperty(task, fieldName);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 28
Project: pho   File: PhoenixHBaseQueryTranslator.java   View Source Code Vote up 5 votes
private <T> List<EntityPropertyValueBinding> buildParameterBindings(T entity, List<String> selectedFields)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {

    try {

        Map<String, EntityPropertyBinding> entityPropertyBindings = entityPropertiesResolver
                .getEntityPropertyNamePropertyBindingMap(entity.getClass());
        if (MapUtils.isEmpty(entityPropertyBindings)) {
            throw new DataStoreException("Invalid Entity class " + entity.getClass().getSimpleName());
        }
        List<EntityPropertyValueBinding> entityPropertyValueBindings = new LinkedList<EntityPropertyValueBinding>();
        int position = 1;
        Set<String> entityFields = entityPropertyBindings.keySet();
        if (CollectionUtils.isEmpty(selectedFields)) {
            selectedFields = new ArrayList<String>(entityFields);
        }
        for (String beanPropertyName : selectedFields) {
            EntityPropertyBinding entityPropertyBinding = entityPropertyBindings.get(beanPropertyName);
            if (entityPropertyBinding == null) {
                String errorMessage = "Invalid bean property " + beanPropertyName + " for bean "
                        + entity.getClass().getSimpleName();
                throw new DataStoreException(errorMessage);
            }
            Object value = PropertyUtils.getProperty(entity, entityPropertyBinding.getNameFullPath());
            EntityPropertyValueBinding entityPropertyValueBinding = new EntityPropertyValueBinding(
                    entityPropertyBinding);
            entityPropertyValueBinding.setValue(value);
            entityPropertyValueBinding.setPosition(position++);
            entityPropertyValueBindings.add(entityPropertyValueBinding);
        }
        return entityPropertyValueBindings;
    } catch (Exception ex) {
        logger.warn("Exceotion while building parameter bindings for entity {}", entity.getClass(), ex);
        throw new DataStoreException(ex);
    }

}
 
Example 29
Project: MMServerEngine   File: ObjectUtil.java   View Source Code Vote up 5 votes
/**
 * 获取成员变量
 */
public static Object getFieldValue(Object obj, String fieldName) {
    Object propertyValue = null;
    try {
        if (PropertyUtils.isReadable(obj, fieldName)) {
            propertyValue = PropertyUtils.getProperty(obj, fieldName);
        }
    } catch (Exception e) {
        logger.error("获取成员变量出错!", e);
        throw new RuntimeException(e);
    }
    return propertyValue;
}
 
Example 30
Project: TranskribusSwtGui   File: ATableWidgetPagination.java   View Source Code Vote up 5 votes
private static <T> T findItem(List<T> items, String propertyName, Object value) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
	if (items == null)
		return null;
	
	for (T i : items) {
		Object v = PropertyUtils.getProperty(i, propertyName);
		
		logger.trace("prop value: "+v+" values classes: "+(value.getClass())+" / "+(v.getClass())+" values: "+value+" / "+v);
		if (value.equals(v)) {
			return i;
		}
	}
	return null;
}
 
Example 31
Project: flatworm   File: ParseUtils.java   View Source Code Vote up 5 votes
/**
 * Attempt to find the collection property on {@code target} indicated by the {@code propertyName} and then see if the "collection"
 * returned has an {@code add(Object)} method and if it does - invoke it with the {@code toAdd} instance. If any of the parameters are
 * {@code null} then no action is taken.
 *
 * @param target                 The object that has the collection property for which the {@code toAdd} instance will be added.
 * @param collectionPropertyName The name of the Java BeanBO property that will return a collection (may not be a {@link
 *                               java.util.Collection} so long as there is an {@code add(Object)} method). Note that if this returns a
 *                               null value a {@link FlatwormConfigurationException} will be thrown.
 * @param toAdd                  The instance to add to the collection indicated.
 * @throws FlatwormParserException Should the underlying collection referenced by {@code propertyName} be {@code null} or non-existent,
 *                                 should no {@code add(Object)} method exist on the collection and should any error occur while
 *                                 invoking the {@code add(Object)} method if it is found (reflection style errors).
 */
public static void addValueToCollection(Object target, String collectionPropertyName, Object toAdd) throws FlatwormParserException {
    if (target == null || StringUtils.isBlank(collectionPropertyName) || toAdd == null) return;
    try {
        PropertyDescriptor propertyDescriptor = PropertyUtils.getPropertyDescriptor(target, collectionPropertyName);
        if (propertyDescriptor != null) {
            Object collectionInstance = PropertyUtils.getProperty(target, collectionPropertyName);
            if (collectionInstance != null) {
                // Once compiled, generics lose their converterName reference and it defaults to a simple java.lang.Object.class
                // so that's the method parameter we'll search by.
                Method addMethod = propertyDescriptor.getPropertyType().getMethod("add", Object.class);
                if (addMethod != null) {
                    addMethod.invoke(collectionInstance, toAdd);
                } else {
                    throw new FlatwormParserException(String.format(
                            "The collection instance %s for property %s in class %s does not have an add method.",
                            collectionInstance.getClass().getName(), propertyDescriptor.getName(), target.getClass().getName()));
                }
            } else {
                throw new FlatwormParserException(String.format(
                        "Unable to invoke the add method on collection %s as it is currently null for instance %s.",
                        propertyDescriptor.getName(), target.getClass().getName()));
            }
        } else {
            throw new FlatwormParserException(String.format(
                    "%s does not have a getter for property %s - the %s instance could therefore not be added to the collection.",
                    target.getClass().getName(), collectionPropertyName, toAdd.getClass().getName()));
        }
    } catch (Exception e) {
        throw new FlatwormParserException(String.format(
                "Unable to invoke the add method on the collection for property %s in bean %s with object of converterName %s",
                collectionPropertyName, target.getClass().getName(), toAdd.getClass().getName()),
                e);
    }
}
 
Example 32
Project: TranskribusCore   File: CustomTag.java   View Source Code Vote up 5 votes
public Object getAttributeValue(String name) {
	if (isPredefinedAttribute(name)) {
		try {
			return PropertyUtils.getProperty(this, name);
		} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
			logger.error("Error getting property '" + name + "': " + e.getMessage(), e);
			return null;
		}
	} else {
		return attributes.get(new CustomTagAttribute(name, true, null, null));
	}

}
 
Example 33
Project: weixin_api   File: XmlUtil.java   View Source Code Vote up 4 votes
/**
 * 对象属性转换为xml标签
 * 
 * @param pd
 * @param xml
 * @throws NoSuchMethodException
 * @throws InvocationTargetException
 * @throws IllegalAccessException
 * @throws XMLStreamException
 */
private static void objectPropToNode(Object bean, XMLStreamWriter xml)
		throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, XMLStreamException {
	if (bean == null) {
		return;
	}

	LinkedHashMap<String, Field> fields = new LinkedHashMap<String, Field>();
	getFields(bean.getClass(), fields);
	if (fields == null || fields.isEmpty()) {
		return;
	}
	for (Entry<String, Field> fieldEntry : fields.entrySet()) {
		String name = fieldEntry.getKey();
		Object value = null;
		try {
			value = PropertyUtils.getProperty(bean, name);
		} catch (Exception ex) {
		}
		if (value == null) {// 忽略空值
			continue;
		}

		String tag = fieldEntry.getValue().isAnnotationPresent(SerializedName.class) ? name
				: StringUtils.capitalize(name);// 首字母大写做为XML标签名,注解为SerializedName的不做处理

		Class<?> type = value.getClass();
		boolean isPrimitive = type.isPrimitive() || type.isEnum() || value instanceof String
				|| value instanceof Number;// 是否基本类型boolean、byte、char、short、int、long、float
		// 和 double 或 Enum
		boolean isArray = type.isArray();// 是否数组

		if (!isArray) {// 非数组型属性
			xml.writeStartElement(tag);// 写开始标签
			if (isPrimitive) {// 基本类型直接写内容
				xml.writeCData(String.valueOf(value));
			} else {
				objectPropToNode(value, xml);// 复合类型,递归解析
			}
			xml.writeEndElement();// 写结束标签
		} else {// 数组型属性
			int length = Array.getLength(value);
			for (int i = 0; i < length; i++) {
				Object val = Array.get(value, i);
				if (val == null) {
					continue;
				}
				xml.writeStartElement(tag);// 写开始标签
				if (isPrimitive) {// 基本类型
					xml.writeCData(String.valueOf(val));
				} else {// 复合类型
					objectPropToNode(val, xml);
				}
				xml.writeEndElement();// 写结束标签
			}
		}

	}
}
 
Example 34
Project: alfresco-repository   File: DbProperty.java   View Source Code Vote up 4 votes
/**
 * Full constructor allowing control over whether the property name should be indexed (e.g. colours[3]),
 * whether the current value of the property should be retrieved automatically or whether to use the
 * supplied value (useful when performing comparisons - construct one with a particular/expected value and
 * construct another with the current value by reflection).
 * <p>
 * The public constructors provide a more usable API with select sets of arguments.
 * 
 * @param dbObject DbObject
 * @param propertyName String
 * @param index int
 * @param useSuppliedValue boolean
 * @param propertyValue Object
 */
protected DbProperty(DbObject dbObject, String propertyName, int index, boolean useSuppliedValue, Object propertyValue)
{
    if (dbObject == null)
    {
        throw new IllegalArgumentException("dbObject cannot be null.");
    }
    this.dbObject = dbObject;
    
    if (propertyName == null)
    {
        if (index > -1 || useSuppliedValue)
        {
            throw new IllegalArgumentException("propertyName cannot be null.");
        }
    }
    if (index > -1)
    {
        this.propertyName = propertyName+"["+index+"]";
    }
    else
    {
        this.propertyName = propertyName;
    }

    // Unfortunetely, this boolean is required, since we may want to set the property value to null.
    if (useSuppliedValue)
    {
        this.propertyValue = propertyValue;
    }
    else if (propertyName != null)
    {
        try
        {
            this.propertyValue = PropertyUtils.getProperty(dbObject, this.propertyName);
        }
        catch (Throwable error)
        {
            throw new IllegalArgumentException("Cannot get value for property named \"" + propertyName + "\"", error);
        }
    }
    else
    {
        // No property is being referred to by this object.
        this.propertyValue = null;
    }
}
 
Example 35
Project: Biliomi   File: XmlElementPathBeanPredicate.java   View Source Code Vote up 4 votes
@Override
public boolean test(T t) {
  // If t is null it will not match
  if (t == null) {
    return false;
  }

  Object tValue;
  try {
    tValue = PropertyUtils.getProperty(t, propertyPath);
  } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
    throw new IllegalArgumentException("Failed retrieving test value " + propertyPath, e);
  }

  // NULL values
  if (value == null) {
    return (tValue == null);
  } else if (tValue == null) {
    return false;
  }

  // Test DateTime
  if (DateTime.class.isAssignableFrom(tValue.getClass())
      && String.class.isAssignableFrom(valueClass)) {
    return testDateTime((DateTime) tValue, (String) value, operator);
  }

  // Test enums
  if (Enum.class.isAssignableFrom(tValue.getClass()) && String.class.isAssignableFrom(valueClass)) {
    // noinspection unchecked
    return testEnum((Enum) tValue, (String) value, operator);
  }

  // Test numbers
  if (Number.class.isAssignableFrom(tValue.getClass()) && Number.class.isAssignableFrom(valueClass)) {
    return testNumber((Number) tValue, (Number) value, operator);
  }

  // Test collections against string
  if (Collection.class.isAssignableFrom(tValue.getClass()) && String.class.isAssignableFrom(valueClass)) {
    return testCollectionAgainsString((Collection<?>) tValue, (String) value, operator);
  }

  // Test Class equality
  if (!tValue.getClass().isAssignableFrom(valueClass)) {
    return false;
  }

  // Test booleans
  if (Boolean.class.isAssignableFrom(valueClass)) {
    return testBoolean((Boolean) tValue, (Boolean) value, operator);
  }

  // Test strings
  if (String.class.isAssignableFrom(valueClass)) {
    return testString((String) tValue, (String) value, operator);
  }

  // Test collections
  if (Collection.class.isAssignableFrom(valueClass)) {
    return testCollection((Collection<?>) tValue, (Collection<?>) value, operator);
  }

  // Default to object equals
  return value.equals(tValue);
}
 
Example 36
Project: xroad-catalog   File: JaxbCatalogServiceTest.java   View Source Code Vote up 4 votes
private String getStringProperty(String propertyName, Object item) throws IllegalAccessException,
        InvocationTargetException, NoSuchMethodException {
    return (String) PropertyUtils.getProperty(item, propertyName);
}
 
Example 37
Project: venus   File: ValidatorSupport.java   View Source Code Vote up 4 votes
public String getMessage(Object value) {
    if (message == null) {
        return "";
    }
    String result = null;
    if (messageParameters == null || messageParameters.length == 0) {
        result = message;
    } else {
        Object[] parsedParameters = new Object[messageParameters.length];
        for (int i = 0; i < this.messageParameters.length; i++) {
            if (STAND_FOR_NAME.equals(messageParameters[i])) {
                parsedParameters[i] = this.describeValidateName();
            } else if (STAND_FOR_VALUE.equals(messageParameters[i])) {
                if (value != null) {
                    parsedParameters[i] = value.toString();
                } else {
                    parsedParameters[i] = "null";

                }
            } else {
                parsedParameters[i] = holder.findString(messageParameters[i]);
            }
        }
        result = String.format(message, parsedParameters);
    }
    Matcher matcher = validatorPattern.matcher(result);
    StringBuffer sb = new StringBuffer();
    Object obj = null;
    while (matcher.find()) {
        try {
            obj = PropertyUtils.getProperty(this, matcher.group(1));
        } catch (Exception e) {
            obj = "null";
        }
        if (obj == null) {
            obj = "null";
        }
        matcher.appendReplacement(sb, obj.toString());
    }
    matcher.appendTail(sb);
    return sb.toString();
}
 
Example 38
Project: lams   File: TagUtils.java   View Source Code Vote up 3 votes
/**
    * Return the value of the specified property of the specified bean,
    * no matter which property reference format is used, with no
    * type conversions.
    *
    * @param bean Bean whose property is to be extracted.
    * @param name Possibly indexed and/or nested name of the property
    *  to be extracted.
    *
    * @exception IllegalAccessException if the caller does not have
    *  access to the property accessor method
    * @exception InvocationTargetException if the property accessor method
    *  throws an exception
    * @exception NoSuchMethodException if an accessor method for this
    *  propety cannot be found.
    * @deprecated Use PropertyUtils.getProperty() directly.  This will be removed
    * after Struts 1.2.
    */
public static Object getProperty(Object bean, String name)
	throws
		IllegalAccessException,
		InvocationTargetException,
		NoSuchMethodException {

	return PropertyUtils.getProperty(bean, name);
}
 
Example 39
Project: jk-util   File: JKObjectUtil.java   View Source Code Vote up 3 votes
/**
 * Gets the property value.
 *
 * @param <T>
 *            the generic type
 * @param instance
 *            the instance
 * @param fieldName
 *            the field name
 * @return the property value
 */
public static <T> T getPropertyValue(final Object instance, final String fieldName) {
	try {
		return (T) PropertyUtils.getProperty(instance, fieldName);
	} catch (final Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example 40
Project: FastDFS_Client   File: FieldMateData.java   View Source Code Vote up 2 votes
/**
 * 获取单元对应值
 * 
 * @param bean
 * @return
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 * @throws NoSuchMethodException
 */
private Object getFieldValue(Object bean)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    return PropertyUtils.getProperty(bean, field.getName());
}