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

The following are Jave code examples for showing how to use setProperty() 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: iBase4J-Common   File: InstanceUtil.java   View Source Code Vote up 6 votes
/**
 * 封装实体
 * 
 * @param cls
 *            实体类
 * @param list
 *            数据查询结果集
 * @return
 */
public static final <E> List<E> getInstanceList(Class<E> cls, ResultSet rs) {
    List<E> resultList = newArrayList();
    try {
        E object = cls.newInstance();
        Field[] fields = cls.getDeclaredFields();
        while (rs.next()) {
            object = cls.newInstance();
            for (int i = 0; i < fields.length; i++) {
                String fieldName = fields[i].getName();
                PropertyUtils.setProperty(object, fieldName, rs.getObject(fieldName));
            }
            resultList.add(object);
        }
    } catch (Exception e) {
        throw new InstanceException(e);
    }
    return resultList;
}
 
Example 2
Project: YiDu-Novel   File: ReviewListAction.java   View Source Code Vote up 6 votes
@Override
protected void loadData() {

    initCollections(new String[] { "collectionProperties.review.searchkey" });
    ReviewSearchBean searchBean = new ReviewSearchBean();
    BeanUtils.copyProperties(this, searchBean, new String[] { "articleno" });

    try {
        PropertyUtils.setProperty(searchBean, option, key);
    } catch (Exception e) {
        logger.warn(e.getMessage());
    }

    if (StringUtils.isEmpty(pagination.getSortColumn())) {
        pagination.setSortColumn(TReview.PROP_POSTDATE);
        pagination.setSortOrder("DESC");
    }

    // 总件数设置
    pagination.setPreperties(reviewService.getCount(searchBean));
    searchBean.setPagination(pagination);
    reviewList = reviewService.find(searchBean);
    // Setting number of records in the particular page
    pagination.setPageRecords(reviewList.size());
}
 
Example 3
Project: automat   File: InstanceUtil.java   View Source Code Vote up 6 votes
/**
 * 封装实体
 * 
 * @param cls
 *            实体类
 * @param list
 *            数据查询结果集
 * @return
 */
public static final <E> List<E> getInstanceList(Class<E> cls, ResultSet rs) {
    List<E> resultList = newArrayList();
    try {
        E object = cls.newInstance();
        Field[] fields = cls.getDeclaredFields();
        while (rs.next()) {
            object = cls.newInstance();
            for (int i = 0; i < fields.length; i++) {
                String fieldName = fields[i].getName();
                PropertyUtils.setProperty(object, fieldName, rs.getObject(fieldName));
            }
            resultList.add(object);
        }
    } catch (Exception e) {
        throw new InstanceException(e);
    }
    return resultList;
}
 
Example 4
Project: nixmash-blog   File: SiteOptions.java   View Source Code Vote up 6 votes
public void setSiteOptionProperty(String property, Object value)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    if (PropertyUtils.isWriteable(this, property)) {

        switch (PropertyUtils
                .getPropertyDescriptor(this, property).getPropertyType().getSimpleName()) {
            case OPTION_VALUE_TYPE_BOOLEAN:
                value = Boolean.valueOf(value.toString());
                break;
            case OPTION_VALUE_TYPE_INTEGER:
                value = Integer.parseInt(value.toString());
                break;
            case OPTION_VALUE_TYPE_USERREGISTRATION:
                value = UserRegistration.valueOf(value.toString());
                break;
            default:
                break;
        }
        PropertyUtils.setProperty(this, property, value);
    }
}
 
Example 5
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 6
Project: mumu   File: InstanceUtil.java   View Source Code Vote up 6 votes
/**
 * 封装实体
 * 
 * @param cls 实体类
 * @param list 数据查询结果集
 * @return
 */
public static final <E> List<E> getInstanceList(Class<E> cls, ResultSet rs) {
	List<E> resultList = newArrayList();
	try {
		E object = cls.newInstance();
		Field[] fields = cls.getDeclaredFields();
		while (rs.next()) {
			object = cls.newInstance();
			for (int i = 0; i < fields.length; i++) {
				String fieldName = fields[i].getName();
				PropertyUtils.setProperty(object, fieldName, rs.getObject(fieldName));
			}
			resultList.add(object);
		}
	} catch (Exception e) {
		throw new InstanceException(e);
	}
	return resultList;
}
 
Example 7
Project: iBase4J   File: InstanceUtil.java   View Source Code Vote up 6 votes
/**
 * 封装实体
 * 
 * @param cls
 *            实体类
 * @param list
 *            数据查询结果集
 * @return
 */
public static final <E> List<E> getInstanceList(Class<E> cls, ResultSet rs) {
	List<E> resultList = newArrayList();
	try {
		E object = cls.newInstance();
		Field[] fields = cls.getDeclaredFields();
		while (rs.next()) {
			object = cls.newInstance();
			for (int i = 0; i < fields.length; i++) {
				String fieldName = fields[i].getName();
				PropertyUtils.setProperty(object, fieldName, rs.getObject(fieldName));
			}
			resultList.add(object);
		}
	} catch (Exception e) {
		throw new InstanceException(e);
	}
	return resultList;
}
 
Example 8
Project: Yidu   File: ReviewListAction.java   View Source Code Vote up 6 votes
@Override
protected void loadData() {

    initCollections(new String[] { "collectionProperties.review.searchkey" });
    ReviewSearchBean searchBean = new ReviewSearchBean();
    BeanUtils.copyProperties(this, searchBean, new String[] { "articleno" });

    try {
        PropertyUtils.setProperty(searchBean, option, key);
    } catch (Exception e) {
        logger.warn(e.getMessage());
    }

    if (StringUtils.isEmpty(pagination.getSortColumn())) {
        pagination.setSortColumn(TReview.PROP_POSTDATE);
        pagination.setSortOrder("DESC");
    }

    // 总件数设置
    pagination.setPreperties(reviewService.getCount(searchBean));
    searchBean.setPagination(pagination);
    reviewList = reviewService.find(searchBean);
    // Setting number of records in the particular page
    pagination.setPageRecords(reviewList.size());
}
 
Example 9
Project: bird-java   File: InstanceHelper.java   View Source Code Vote up 6 votes
/**
 * 封装实体
 *
 * @param cls
 *            实体类
 * @param rs
 *            数据查询结果集
 * @return
 */
public static final <E> List<E> getInstanceList(Class<E> cls, ResultSet rs) {
    List<E> resultList = newArrayList();
    try {
        E object = cls.newInstance();
        Field[] fields = cls.getDeclaredFields();
        while (rs.next()) {
            object = cls.newInstance();
            for (int i = 0; i < fields.length; i++) {
                String fieldName = fields[i].getName();
                PropertyUtils.setProperty(object, fieldName, rs.getObject(fieldName));
            }
            resultList.add(object);
        }
    } catch (Exception e) {
        throw new InstanceException(e);
    }
    return resultList;
}
 
Example 10
Project: uckefu   File: UKResultMapper.java   View Source Code Vote up 6 votes
public <T> T mapEntity(String source , SearchHit hit , Class<T> clazz) {
	T t = mapEntity(source , clazz) ;
	
	Map<String, HighlightField> highlightFields = hit.getHighlightFields();
	HighlightField highlightNameField = highlightFields.get("title");
	HighlightField contentHightlightField = highlightFields.get("content");
	try {
		if(highlightNameField!=null&&highlightNameField.fragments()!=null){
			PropertyUtils.setProperty(t, "title" , highlightNameField.fragments()[0].string());
		}
		if(contentHightlightField!=null){
			PropertyUtils.setProperty(t, "content" , contentHightlightField.fragments()[0].string());
		}
		PropertyUtils.setProperty(t, "id" , hit.getId());
	} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
		e.printStackTrace();
	} 
	return t;
}
 
Example 11
Project: JAVA-   File: InstanceUtil.java   View Source Code Vote up 6 votes
/**
 * 封装实体
 * 
 * @param cls
 *            实体类
 * @param list
 *            数据查询结果集
 * @return
 */
public static final <E> List<E> getInstanceList(Class<E> cls, ResultSet rs) {
    List<E> resultList = newArrayList();
    try {
        E object = cls.newInstance();
        Field[] fields = cls.getDeclaredFields();
        while (rs.next()) {
            object = cls.newInstance();
            for (int i = 0; i < fields.length; i++) {
                String fieldName = fields[i].getName();
                PropertyUtils.setProperty(object, fieldName, rs.getObject(fieldName));
            }
            resultList.add(object);
        }
    } catch (Exception e) {
        throw new InstanceException(e);
    }
    return resultList;
}
 
Example 12
Project: validator-web   File: BeanReader.java   View Source Code Vote up 6 votes
@SuppressWarnings({ "unchecked", "rawtypes" })
public void setProperty(String name, Object value) {
    if (bean instanceof Map) {
        if (bean instanceof MultiValueMap) {
            MultiValueMap valueMap = (MultiValueMap) bean;
            valueMap.set(name, value);
            return;
        }
        Map map = (Map) bean;
        map.put(name, value);
        return;
    }
    try {
        PropertyUtils.setProperty(bean, name, value);
    } catch (Exception e) {
        if (log.isWarnEnabled()) {
            log.warn("Property '" + name + "' can't setter for object of " +
                    "type " + bean.getClass().getName() + ".");
        }
    }
}
 
Example 13
Project: melon   File: InstanceUtil.java   View Source Code Vote up 6 votes
/**
 * 封装实体
 *
 * @param cls  实体类
 * @param list 数据查询结果集
 * @return
 */
public static final <E> List<E> getInstanceList(Class<E> cls, ResultSet rs) {
    List<E> resultList = newArrayList();
    try {
        E object = cls.newInstance();
        Field[] fields = cls.getDeclaredFields();
        while (rs.next()) {
            object = cls.newInstance();
            for (int i = 0; i < fields.length; i++) {
                String fieldName = fields[i].getName();
                PropertyUtils.setProperty(object, fieldName, rs.getObject(fieldName));
            }
            resultList.add(object);
        }
    } catch (Exception e) {
        throw new InstanceException(e);
    }
    return resultList;
}
 
Example 14
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 15
Project: linkbinder   File: BaseDao.java   View Source Code Vote up 6 votes
/**
 * 前方一致検索用の文字列をエスケープする.
 * @throws NoSuchMethodException
 * @throws InvocationTargetException
 * @throws IllegalAccessException
 */
private void escape(Object clone, List<String> fields)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    String escapeChar = (String) PropertyUtils.getProperty(clone, "escapeChar");
    String escapeEscapeChar = escapeChar + escapeChar;
    String escapePercent = escapeChar + PERCENT;
    String escapeUnderBar = escapeChar + UNDER_BAR;
    for (String field : fields) {
        Object object = PropertyUtils.getProperty(clone, field);
        if (object != null) {
            String value = String.valueOf(object);
            // エスケープ文字自体を変換
            value = value.replaceAll(escapeChar, escapeEscapeChar);
            // %を変換
            value = value.replaceAll(PERCENT, escapePercent);
            // _を変換
            value = value.replaceAll(UNDER_BAR, escapeUnderBar);

            PropertyUtils.setProperty(clone, field, value);
        }
    }
}
 
Example 16
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 17
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 18
Project: crnk-framework   File: TaskToProjectRepository.java   View Source Code Vote up 5 votes
@Override
public void setRelation(Task task, ObjectId projectId, String fieldName) {
	Project project = projectRepository.findOne(projectId, null);
	try {
		PropertyUtils.setProperty(task, fieldName, project);
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
	taskRepository.save(task);
}
 
Example 19
Project: crnk-framework   File: TaskToProjectRepository.java   View Source Code Vote up 5 votes
@Override
public void setRelations(Task task, Iterable<ObjectId> projectIds, String fieldName) {
	Iterable<Project> projects = projectRepository.findAll(projectIds, null);
	try {
		PropertyUtils.setProperty(task, fieldName, projects);
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
	taskRepository.save(task);
}
 
Example 20
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 21
Project: QLExpress   File: ExpressUtil.java   View Source Code Vote up 5 votes
public static void setProperty(Object bean, Object name, Object value) {
	try {
		if (bean instanceof Class) {
			Field f = ((Class<?>) bean).getDeclaredField(name.toString());
			f.set(null, value);
		}else if(bean instanceof Map ){
			((Map<Object,Object>)bean).put(name, value);
	    } else {
	    	Class<?> filedClass = PropertyUtils.getPropertyType(bean, name.toString());
			PropertyUtils.setProperty(bean, name.toString(),ExpressUtil.castObject(value, filedClass, false));
		}
	} catch (Exception e) {
		throw new RuntimeException("不能访问" + bean + "的property:" + name,e);
	}
}
 
Example 22
Project: stallion-core   File: MappedModel.java   View Source Code Vote up 5 votes
public default Object put(String key, Object value) {
    try {
        if (key.equals("id") || key.equals("lastModifiedMillis") && !(value instanceof Long)) {
            if (value instanceof Double) {
                value = ((Double) value).longValue();
            } else if (value instanceof Integer) {
                value = ((Integer) value).longValue();
            } else if (value instanceof Float) {
                value = ((Float) value).longValue();
            } else if (value instanceof BigInteger) {
                value = ((BigInteger) value).longValue();
            }

        }
        if (PropertyUtils.isWriteable(this, key)) {
            Class cls = null;
            if (value != null) {
                cls = value.getClass();
            }
            PropertyUtils.setProperty(this, key, value);
            return null;
        } else {
            return getAttributes().put(key, value);
        }
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}
 
Example 23
Project: tkhoon   File: ObjectUtil.java   View Source Code Vote up 5 votes
public static void setField(Object obj, String fieldName, Object fieldValue) {
    try {
        if (PropertyUtils.isWriteable(obj, fieldName)) {
            PropertyUtils.setProperty(obj, fieldName, fieldValue);
        }
    } catch (Exception e) {
        logger.error("设置成员变量出错!", e);
        throw new RuntimeException(e);
    }
}
 
Example 24
Project: sistra   File: ConectorConfigurator.java   View Source Code Vote up 5 votes
public static void setConectorProperties(Conector conector, Map properties) {
    for (Iterator iterator = properties.keySet().iterator(); iterator.hasNext();) {
        String propertyName = (String) iterator.next();
        try {
            PropertyUtils.setProperty(conector, propertyName, properties.get(propertyName));
        } catch (Throwable t) {
            log.error("Error fijando propiedad " + propertyName, t);
        }
    }
}
 
Example 25
Project: simbest-cores   File: EnumsDecorator.java   View Source Code Vote up 5 votes
@Override
public void decorate(Object bean, String property, Object strategy) {
	try {
		GenericEnum someEnum = (GenericEnum) PropertyUtils.getProperty(bean, property);
		if (someEnum != null) {
			PropertyUtils.setProperty(bean, (String)strategy, someEnum.getValue());
		}
	} catch (Exception e) {
		log.error(Exceptions.getStackTraceAsString(e));
	}
}
 
Example 26
Project: OpenCyclos   File: MapBean.java   View Source Code Vote up 5 votes
public void set(final String name, final String key, final Object value) {
    final Object bean = this.get(name);
    if (bean != null) {
        if (bean instanceof DynaBean) {
            ((DynaBean) bean).set(key, value);
        } else {
            try {
                PropertyUtils.setProperty(bean, key, value);
            } catch (final Exception e) {
                // Keep on
            }
        }
    }
}
 
Example 27
Project: MMServerEngine   File: ObjectUtil.java   View Source Code Vote up 5 votes
/**
 * 设置成员变量
 */
public static void setField(Object obj, String fieldName, Object fieldValue) {
    try {
        if (PropertyUtils.isWriteable(obj, fieldName)) {
            PropertyUtils.setProperty(obj, fieldName, fieldValue);
        }
    } catch (Exception e) {
        logger.error("设置成员变量出错!", e);
        throw new RuntimeException(e);
    }
}
 
Example 28
Project: katharsis-framework   File: TaskToProjectRepository.java   View Source Code Vote up 5 votes
@Override
public void setRelation(Task task, ObjectId projectId, String fieldName) {
    Project project = projectRepository.findOne(projectId, null);
    try {
        PropertyUtils.setProperty(task, fieldName, project);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    taskRepository.save(task);
}
 
Example 29
Project: katharsis-framework   File: TaskToProjectRepository.java   View Source Code Vote up 5 votes
@Override
public void setRelations(Task task, Iterable<ObjectId> projectIds, String fieldName) {
    Iterable<Project> projects = projectRepository.findAll(projectIds, null);
    try {
        PropertyUtils.setProperty(task, fieldName, projects);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    taskRepository.save(task);
}
 
Example 30
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 31
Project: ERDesignerNG   File: ModelItemProperties.java   View Source Code Vote up 5 votes
public void initializeFrom(T aObject) {
	ModelProperties theProperties = aObject.getProperties();

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

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

}
 
Example 32
Project: alfresco-repository   File: ComplexContentTransformer.java   View Source Code Vote up 4 votes
/**
 * Sets any transformation option overrides it can.
 */
private void overrideTransformationOptions(TransformationOptions options)
{
    // Set any transformation options overrides if we can
    if(options != null && transformationOptionOverrides != null)
    {
       for(String key : transformationOptionOverrides.keySet())
       {
          if(PropertyUtils.isWriteable(options, key))
          {
             try 
             {
                PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(options, key);
                Class<?> propertyClass = pd.getPropertyType();
                
                Object value = transformationOptionOverrides.get(key);
                if(value != null)
                {
                    if(propertyClass.isInstance(value))
                    {
                        // Nothing to do
                    }
                    else if(value instanceof String && propertyClass.isInstance(Boolean.TRUE))
                    {
                        // Use relaxed converter
                        value = TransformationOptions.relaxedBooleanTypeConverter.convert((String)value);
                    }
                    else
                    {
                        value = DefaultTypeConverter.INSTANCE.convert(propertyClass, value);
                    }
                }
                PropertyUtils.setProperty(options, key, value);
             } 
             catch(MethodNotFoundException mnfe) {}
             catch(NoSuchMethodException nsme) {}
             catch(InvocationTargetException ite) {}
             catch(IllegalAccessException iae) {}
          }
          else
          {
             logger.warn("Unable to set override Transformation Option " + key + " on " + options);
          }
       }
    }
}
 
Example 33
Project: audible   File: DomainMapper.java   View Source Code Vote up 4 votes
private void handleCollections(Object to, Class toClass, Class toPropertyType, Function fromFunction, Object finalFrom, String toPropertyName, boolean beenMappedWithOrika) throws Exception {
    Field field = toClass.getDeclaredField(toPropertyName);

    Type type = field.getGenericType();

    if (type instanceof ParameterizedType) {
        ParameterizedType pt = (ParameterizedType) type;
        Class typeForCollection = (Class) pt.getActualTypeArguments()[0];

        Object object = eval(toPropertyType, fromFunction, finalFrom, beenMappedWithOrika, to, toPropertyName);

        List fromList = null;

        MappingType overrideMappingTypeNested = null;

        if (object != null) {
            if (object instanceof CustomMappingWrapper) {
                CustomMappingWrapper cmo = (CustomMappingWrapper) object;
                overrideMappingTypeNested = cmo.getMappingType();
                fromList = new ArrayList((Collection) cmo.getObject());
            } else {

                fromList = new ArrayList((Collection) object);
            }
        }

        //Check to see if they are already providing toClass in the closure
        boolean isOverride = fromList != null && !fromList.isEmpty() && !typeForCollection.isAssignableFrom(fromList.iterator().next().getClass());


        if (fromList == null || fromList.isEmpty()) { //Set null if empty
            PropertyUtils.setProperty(to, toPropertyName, null);
        } else if (isOverride && mappingService.hasMappingForClass(typeForCollection)) { //Recursively call

            Object toValue;
            if (parallelProcessEmbeddedList) {
                toValue = mapListParallel(typeForCollection, fromList, overrideMappingTypeNested != null ? overrideMappingTypeNested : defaultEmbeddedMapping);
            } else {
                toValue = mapList(typeForCollection, fromList, overrideMappingTypeNested != null ? overrideMappingTypeNested : defaultEmbeddedMapping);
            }

            PropertyUtils.setProperty(to, toPropertyName, toValue);


        } else { //Already provided by the fromList
            if (toPropertyType.isAssignableFrom(fromList.getClass())) { //Collection type is assignable

                PropertyUtils.setProperty(to, toPropertyName, fromList);

            } else { //Explicit collection type
                if (List.class.isAssignableFrom(toPropertyType)) {
                    List list = new ArrayList();
                    list.addAll(fromList);
                    PropertyUtils.setProperty(to, toPropertyName, list);

                } else if (Set.class.isAssignableFrom(toPropertyType)) {
                    Set set = new HashSet();
                    set.addAll(fromList);
                    PropertyUtils.setProperty(to, toPropertyName, set);
                } else {
                    throw new Exception("Unable to find find property collection type on " + toPropertyType);
                }


            }


        }


    }
}
 
Example 34
Project: OpenMobster   File: TestBeanSyntax.java   View Source Code Vote up 4 votes
private Object initializeIndexedProperty(Object parentObject, String property, 
PropertyDescriptor propertyMetaData) throws Exception
{
	Object element = null;
	
	//Find the Class of the elementType
	Class elementType = null;
	
	if(!propertyMetaData.getPropertyType().isArray())
	{
		ParameterizedType returnType = (ParameterizedType)propertyMetaData.
		getReadMethod().getGenericReturnType();
		Type[] actualTypes = returnType.getActualTypeArguments();		
		for(Type actualType: actualTypes)
		{
			elementType = (Class)actualType;
		}
	}
	else
	{
		elementType = propertyMetaData.getPropertyType().getComponentType();
	}
			
	//An IndexedProperty
	Object indexedProperty = PropertyUtils.getProperty(parentObject, propertyMetaData.getName());
	
	//Initialize the IndexedProperty (An Array or Collection)
	if(indexedProperty == null)
	{						
		if(propertyMetaData.getPropertyType().isArray())
		{
			//TODO: Remove hardcoded array size							
			PropertyUtils.setProperty(parentObject, propertyMetaData.getName(),
			Array.newInstance(elementType, 1));
		}
		else
		{
			//Handle Collection Construction
			PropertyUtils.setProperty(parentObject, propertyMetaData.getName(), new ArrayList());
		}
		indexedProperty = PropertyUtils.getProperty(parentObject, propertyMetaData.getName());
	}
	
	//Check to see if the index specified by the field requires creation of new
	//element
	try
	{
		element = PropertyUtils.getIndexedProperty(parentObject, property);
	}
	catch(IndexOutOfBoundsException iae)
	{
		Object newlyInitialized = elementType.newInstance();
					
		if(!propertyMetaData.getPropertyType().isArray())
		{
			((Collection)indexedProperty).add(newlyInitialized);
		}
		else
		{
			//TODO: Remove hardcoded array index
			Array.set(indexedProperty, 0, newlyInitialized);
		}
								
		element = newlyInitialized;
	}
	
			
	return element;
}
 
Example 35
Project: dot4command-core   File: BeanUtils.java   View Source Code Vote up 4 votes
public static void setPropertyValue(Object data, String name, Object value) {
	try {
		PropertyUtils.setProperty(data, name, value);
	}catch (Exception ex) {}
}
 
Example 36
Project: jk-util   File: JKObjectUtil.java   View Source Code Vote up 3 votes
/**
 * Sets the peoperty value.
 *
 * @param source
 *            the source
 * @param fieldName
 *            the field name
 * @param value
 *            the value
 */
public static void setPeopertyValue(final Object source, final String fieldName, final Object value) {
	try {
		PropertyUtils.setProperty(source, fieldName, value);
	} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
		throw new RuntimeException(e);
	}
}
 
Example 37
Project: flatworm   File: ParseUtils.java   View Source Code Vote up 3 votes
/**
 * Invoke a setter for a the given {@code propertyName}.
 *
 * @param target       The {@code Object} that contains the setter property to be invoked.
 * @param propertyName The name of the property.
 * @param toAdd        The value to pass to the property.
 * @throws FlatwormParserException should invoking the setter method fail for any reason.
 */
public static void setProperty(Object target, String propertyName, Object toAdd) throws FlatwormParserException {
    try {
        PropertyUtils.setProperty(target, propertyName, toAdd);
    } catch (Exception e) {
        throw new FlatwormParserException(e.getMessage(), e);
    }
}