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

The following are Jave code examples for showing how to use setProperty() of the org.apache.commons.beanutils.BeanUtils 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: airtable.java   File: Table.java   View Source Code Vote up 6 votes
/**
 *
 * @param retval
 * @param key
 * @param value
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 */
private void setProperty(T retval, String key, Object value) throws IllegalAccessException, InvocationTargetException {
    String property = key2property(key);

    for (final Field f : this.type.getDeclaredFields()) {
        final SerializedName annotation = f.getAnnotation(SerializedName.class);

        if (annotation != null && property.equalsIgnoreCase(annotation.value())) {
            property = f.getName();
            break;
        }
    }

    if (propertyExists(retval, property)) {
        BeanUtils.setProperty(retval, property, value);
    } else {
        LOG.warn(retval.getClass() + " does not support public setter for existing property [" + property + "]");
    }
}
 
Example 2
Project: jambo2   File: BaseVO.java   View Source Code Vote up 6 votes
public static void setProperties(Object obj, Map map){
	Field[] fields = obj.getClass().getDeclaredFields();
	for(Field field : fields) {
		Column column = field.getAnnotation(Column.class);
		String dbColumnname = null;
		if ("".equals(column.name()))
			dbColumnname = field.getName();
		else dbColumnname = column.name();

		try {
			Object value = map.get(dbColumnname);
			if (value != null) {
				BeanUtils.setProperty(obj, field.getName(), value);
			}
		} catch (Exception e) {
			log.catching(e);
		}
	}
}
 
Example 3
Project: OfficeAutomation   File: RowConvert.java   View Source Code Vote up 6 votes
private static <T> T convertWithMethod(Row row, Class<T> clazz) throws IllegalAccessException, InstantiationException, ParseException, InvocationTargetException {
    Field[] fields = new Field[]{};
    Class temp = clazz;
    while(temp != null){
        fields = ArrayUtils.addAll(temp.getDeclaredFields(),fields);
        temp = temp.getSuperclass();
    }
    Object object = clazz.newInstance();
    for (Field field : fields) {
        ExcelCellField filedExcelAnnotation = getAnnotationCellFiled(field.getAnnotations());
        if (filedExcelAnnotation == null) {
            continue;
        }
        Class<?> fieldType = field.getType();
        Integer index = filedExcelAnnotation.index();
        String propertyName = field.getName();
        Object value = getValue(fieldType, row.getCell(index), filedExcelAnnotation);
        if (value != null) {
            BeanUtils.setProperty(object, propertyName, value);
        }
    }
    return (T) object;
}
 
Example 4
Project: UtilsMaven   File: DBUtils.java   View Source Code Vote up 6 votes
/**
 * 将所有记录包装成T类对象,并将所有T类对象放入一个数组中并返回,传入的T类的定义必须符合JavaBean规范,
 * 因为本函数是调用T类对象的setter器来给对象赋值的
 *
 * @param clazz          T类的类对象
 * @param listProperties 所有记录
 * @return 返回所有被实例化的对象的数组,若没有对象,返回一个空数组
 * @throws InstantiationException
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 */
private static <T> List<T> transformMapListToBeanList(Class<T> clazz, List<Map<String, Object>> listProperties)
        throws InstantiationException, IllegalAccessException, InvocationTargetException {
    // 存放被实例化的T类对象
    T bean = null;
    // 存放所有被实例化的对象
    List<T> list = new ArrayList<T>();
    // 将实例化的对象放入List数组中
    if (listProperties.size() != 0) {

        Iterator<Map<String, Object>> iter = listProperties.iterator();
        while (iter.hasNext()) {
            // 实例化T类对象
            bean = clazz.newInstance();
            // 遍历每条记录的字段,并给T类实例化对象属性赋值
            for (Map.Entry<String, Object> entry : iter.next().entrySet()) {
                BeanUtils.setProperty(bean, entry.getKey(), entry.getValue());
            }
            // 将赋过值的T类对象放入数组中
            list.add(bean);
        }
    }
    return list;
}
 
Example 5
Project: validator-web   File: DefaultContainer.java   View Source Code Vote up 6 votes
protected void injectValue(Object bean, PropertyDescriptor pd) {
    Method writeMethod = pd.getWriteMethod();
    Value valueAnnotate = writeMethod.getAnnotation(Value.class);
    if (valueAnnotate == null) {
        return;
    }
    String value = valueAnnotate.value();
    if (value.startsWith("${") && value.endsWith("}")) {
        value = value.substring(2, value.length() - 1);
        value = getProperty(value);
    }
    try {
        BeanUtils.setProperty(bean, pd.getName(), value);
    } catch (Exception e) {
        throw new InjectBeanException("Could not inject value: " + writeMethod + "; nested exception is " + e, e);
    }
}
 
Example 6
Project: navi   File: HttpRequestUtil.java   View Source Code Vote up 6 votes
public static <T> T createBeanFromRequest(NaviHttpRequest request, Class<? extends T> clazz) throws NaviSystemException {
    try {
        T bean = clazz.newInstance();
        Field[] fields = bean.getClass().getDeclaredFields();

        for (Field field : fields) {
            if (request.getParameter(field.getName()) != null) {
                String val = request.getParameter(field.getName());
                if (val == null) {
                    continue;
                }

                Object obj = val;
                if (field.getType().equals(JSONArray.class) || field.getType().equals(JSONObject.class)) {
                    obj = JSON.parse(val);
                }

                BeanUtils.setProperty(bean, field.getName(), obj);
            }
        }

        return bean;
    } catch (Exception e) {
        throw new NaviSystemException("system, error, " + e.getMessage(), NaviError.SYSERROR);
    }
}
 
Example 7
Project: sam-elle   File: BtyDataConverter.java   View Source Code Vote up 6 votes
public static BatteryInfoReq convert(String str) {
    if (StringUtils.isBlank(str)) {
        return null;
    }
    BatteryInfoReq req = new BatteryInfoReq();
    String[] arr = StringUtils.split(str, "&");
    for (int i = 0; i < arr.length; i++) {
        String[] pair = StringUtils.split(arr[i], "=");
        try {
            BeanUtils.setProperty(req, pair[0], pair[1]);
        } catch (Exception e) {
            logger.error(ExceptionUtils.getStackTrace(e));
        }
    }

    return req;

}
 
Example 8
Project: Shop   File: JSONUtils.java   View Source Code Vote up 6 votes
/***
 * 将JSON文本反序列化为主从关系的实体
 * @param 泛型T 代表主实体类型
 * @param 泛型D 代表从实体类型
 * @param jsonString JSON文本
 * @param mainClass 主实体类型
 * @param detailName 从实体类在主实体类中的属性名称
 * @param detailClass 从实体类型
 * @return
 */
public static <T, D> T toBean(String jsonString, Class<T> mainClass,
        String detailName, Class<D> detailClass)
{
    JSONObject jsonObject = JSONObject.fromObject(jsonString);
    JSONArray jsonArray = (JSONArray) jsonObject.get(detailName);

    T mainEntity = JSONUtils.toBean(jsonObject, mainClass);
    List<D> detailList = JSONUtils.toList(jsonArray, detailClass);

    try
    {
        BeanUtils.setProperty(mainEntity, detailName, detailList);
    }
    catch (Exception ex)
    {
        throw new RuntimeException("主从关系JSON反序列化实体失败!");
    }

    return mainEntity;
}
 
Example 9
Project: coordinated-entry   File: BaseRepositoryImpl.java   View Source Code Vote up 6 votes
@Override
@Transactional
public void delete(T entity)  {
		try {
			BeanUtils.setProperty(entity, "deleted", true);
			BeanUtils.setProperty(entity, "dateUpdated", LocalDateTime.now());
			Account account = SecurityContextUtil.getUserAccount();
			if(account!=null)
					BeanUtils.setProperty(entity, "userId", account.getAccountId());

			entityManager.merge(entity);
		} catch (Exception e) {
			entityManager.detach(entity);
			entityManager.flush();
		} 
}
 
Example 10
Project: leopard   File: BaseInfoBuilder.java   View Source Code Vote up 6 votes
public void setField(NamedNodeMap namedNodeMap, String fieldName) {
	Attr attr = (Attr) namedNodeMap.getNamedItem(fieldName);
	if (attr != null) {
		boolean isDefaultValue = !attr.getSpecified();
		boolean success = setDefaultFlag(fieldName, isDefaultValue);
		if (success) {

			// Json.print(baseInfo, "baseInfo");
			Object value = this.toBaseInfoValue(fieldName, attr.getNodeValue());
			try {
				BeanUtils.setProperty(baseInfo, fieldName, value);
			}
			catch (Exception e) {
				throw new RuntimeException(e.getMessage(), e);
			}
		}
	}
}
 
Example 11
Project: osframe   File: JSONHelper.java   View Source Code Vote up 6 votes
/***
 * 将JSON文本反序列化为主从关系的实体
 * 
 * @param <T>泛型T 代表主实体类型
 * @param <D1>泛型D1 代表从实体类型
 * @param <D2>泛型D2 代表从实体类型
 * @param jsonString
 *            JSON文本
 * @param mainClass
 *            主实体类型
 * @param detailName1
 *            从实体类在主实体类中的属性
 * @param detailClass1
 *            从实体类型
 * @param detailName2
 *            从实体类在主实体类中的属性
 * @param detailClass2
 *            从实体类型
 * @return
 */
public static <T, D1, D2> T toBean(String jsonString, Class<T> mainClass,
		String detailName1, Class<D1> detailClass1, String detailName2,
		Class<D2> detailClass2) {
	JSONObject jsonObject = JSONObject.fromObject(jsonString);
	JSONArray jsonArray1 = (JSONArray) jsonObject.get(detailName1);
	JSONArray jsonArray2 = (JSONArray) jsonObject.get(detailName2);

	T mainEntity = JSONHelper.toBean(jsonObject, mainClass);
	List<D1> detailList1 = JSONHelper.toList(jsonArray1, detailClass1);
	List<D2> detailList2 = JSONHelper.toList(jsonArray2, detailClass2);

	try {
		BeanUtils.setProperty(mainEntity, detailName1, detailList1);
		BeanUtils.setProperty(mainEntity, detailName2, detailList2);
	} catch (Exception ex) {
		throw new RuntimeException("主从关系JSON反序列化实体失败!");
	}

	return mainEntity;
}
 
Example 12
Project: dingding-app-server   File: WebUtil.java   View Source Code Vote up 6 votes
/**
 * 转换请求中的header中的参数为简单对象(只有对象中的简单类型会被赋值),参数值为数组的只取第一个
 *
 * @param request 请求对象
 * @param claz    目标对象类型类
 * @param <T>     目标对象类型
 * @return 目标对象
 * @throws IllegalAccessException
 * @throws InstantiationException
 */
public static <T> T HeaderToSimpleBean(HttpServletRequest request, Class<T> claz) throws IllegalAccessException, InstantiationException {
    Enumeration it = request.getHeaderNames();
    T object = claz.newInstance();
    while (it.hasMoreElements()) {
        String hKey = (String) it.nextElement();
        String hValue = request.getHeader(hKey);
        if (StringUtils.isNotBlank(hKey) && StringUtils.isNotBlank(hValue)) {
            try {
                BeanUtils.setProperty(object, hKey, hValue);
            } catch (Exception e) {
            }
        }
    }
    return object;
}
 
Example 13
Project: rabbitframework   File: ReflectionBuilder.java   View Source Code Vote up 6 votes
private void setProperty(Object object, String propertyPath, Object value) {
    try {
        if (log.isTraceEnabled()) {
            log.trace("Applying property [{}] value [{}] on object of type [{}]",
                    new Object[]{propertyPath, value, object.getClass().getName()});
        }
        BeanUtils.setProperty(object, propertyPath, value);
    } catch (Exception e) {
        String msg = "Unable to set property '" + propertyPath + "' with value [" + value + "] on object " +
                "of type " + (object != null ? object.getClass().getName() : null) + ".  If " +
                "'" + value + "' is a reference to another (previously defined) object, prefix it with " +
                "'" + OBJECT_REFERENCE_BEGIN_TOKEN + "' to indicate that the referenced " +
                "object should be used as the actual value.  " +
                "For example, " + OBJECT_REFERENCE_BEGIN_TOKEN + value;
        throw new ConfigurationException(msg, e);
    }
}
 
Example 14
Project: anyline   File: BeanUtil.java   View Source Code Vote up 6 votes
public static boolean setFieldValue(Object obj, Field field, Object value){
	if(null == obj || null == field){
		return false;
	}
	try{
		if(field.isAccessible()){
			//可访问属性
			field.set(obj, value);
			BeanUtils.setProperty(obj, field.getName(), value);
		}else{
			//不可访问属性
			field.setAccessible(true);
			field.set(obj, value);
			BeanUtils.setProperty(obj, field.getName(), value);
			field.setAccessible(false);
		}
	}catch(Exception e){
		e.printStackTrace();
		return false;
	}
	return true;
}
 
Example 15
Project: airtable.java   File: MapConverter.java   View Source Code Vote up 5 votes
/**
 * Converts the input object into a <code>Map</code> object.
 *  
 * @param <T> Target type of the conversion.
 * @param type Data type to which this value should be converted.
 * @param value TThe input value to be converted.
 * @return The converted <code>Map</code>
 * @throws Throwable if an error occurs converting to the specified type 
 */
@Override
protected <T> T convertToType(Class<T> type, Object value) throws Throwable {

    if(mapClass == null) {
        throw new IllegalAccessException("mapClass is not initialized by setListClass().");
    }
    
    final Class<T> sourceType = (Class<T>) value.getClass();
    Map<String, Object> returnMap = new HashMap<>();
        
    if(value instanceof LinkedTreeMap){
        for (String key : ((LinkedTreeMap<String, Object>) value).keySet()) {
            Object instanz = this.mapClass.newInstance();
            Object val = ((LinkedTreeMap) value).get(key);   
            BeanUtils.setProperty(instanz,"name",key); 
            for (String key2 : ((LinkedTreeMap<String, Object>) val).keySet()) {
                Object val2 = ((LinkedTreeMap) val).get(key2);            
                BeanUtils.setProperty(instanz,key2,val2);                                
            }           
            returnMap = toClassMap(sourceType,instanz,returnMap);
        }         
        return (T) returnMap;
    }
    
    if(value instanceof String){
        return (T) toStringMap(sourceType,value.toString(),returnMap);
    }
    
    final String stringValue = value.toString().trim();
    if (stringValue.length() == 0) {
        return handleMissing(type);
    }
        
    return (T) toStringMap(sourceType,stringValue,returnMap);
}
 
Example 16
Project: airtable.java   File: ListConverter.java   View Source Code Vote up 5 votes
/**
 *
 * Convert the Input Object into a List of Attachements
 *
 * This Method handles the conversion from a List of LinkedHashMaps to a
 * List of Attachement Objects.
 *
 * <p>
 * If the Input Object is no List or the List Item is no LinkedHashMap
 * everything will be converted into a (List?) String.</p>
 *
 * @param type The type of the Input Object
 * @param value The value of the Input Object
 * @return A List
 * @throws java.lang.InstantiationException If no Instance of the listClass
 * can be instantiated
 * @throws java.lang.IllegalAccessException If the Object can't be accest
 * @throws java.lang.reflect.InvocationTargetException If th Target can't be
 * accessed
 */
@Override
protected <T> T convertToType(final Class<T> type, Object value) throws InstantiationException, IllegalAccessException, InvocationTargetException {

    if (listClass == null) {
        throw new IllegalAccessException("listClass is not initialized by setListClass().");
    }

    List<T> returnList = new ArrayList<>();

    if (value instanceof List) {
        for (T item : ((List<T>) value)) {
            if (item instanceof LinkedTreeMap) {
                Object instanz = listClass.newInstance();
                for (String key : ((LinkedTreeMap<String, Object>) item).keySet()) {
                    Object val = ((LinkedTreeMap) item).get(key);
                    BeanUtils.setProperty(instanz, key, val);
                }
                returnList = toClassList(item.getClass(), instanz, returnList);
            }
            if (item instanceof String) {
                returnList = toStringList(item.getClass(), item.toString(), returnList);
            }

        }
        return (T) returnList;
    }

    //TODO überarbeiten
    if (value instanceof String) {
        return (T) toStringList(value.getClass(), value.toString(), returnList);
    }

    final String stringValue = value.toString().trim();
    if (stringValue.length() == 0) {
        return handleMissing(type);
    }

    return (T) toStringList(value.getClass(), stringValue, returnList);
}
 
Example 17
Project: atlas   File: AtlasConfigHelper.java   View Source Code Vote up 5 votes
public static void setProperty(Object object,
                               String fieldName,
                               String value)
    throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchFieldException {

    String[] fieldNames = fieldName.split("\\.");

    Object last = object;
    for (int i = 0; i < fieldNames.length - 1; i++) {

        String field = fieldNames[i];

        if (last instanceof NamedDomainObjectContainer) {
            last = ((NamedDomainObjectContainer)last).maybeCreate(field);
        } else {
            Field declaredField = last.getClass().getField(field);
            declaredField.setAccessible(true);

            if (null == declaredField.get(last)) {
                Object newInstance = declaredField.getType()
                    .getConstructors()
                    .getClass()
                    .newInstance();
                declaredField.set(last, newInstance);
            }

            last = declaredField.get(last);
        }
    }

    BeanUtils.setProperty(last, fieldNames[fieldNames.length - 1], value);
}
 
Example 18
Project: urule   File: Utils.java   View Source Code Vote up 5 votes
public static void setObjectProperty(Object object,String property,Object value){
	try {
		BeanUtils.setProperty(object, property, value);
	} catch (Exception e) {
		throw new RuleException(e);
	}
}
 
Example 19
Project: delivery-sdk-java   File: StronglyTypedContentItemConverter.java   View Source Code Vote up 5 votes
<T> T convert(ContentItem item, Map<String, ContentItem> modularContent, Class<T> tClass) {
    if (tClass == Object.class) {
        Class<?> mappingClass = contentTypeToClassMapping.get(item.getSystem().getType());
        if (mappingClass == null) {
            return (T) item;
        }
        return (T) convert(item, modularContent, mappingClass);
    }
    if (tClass == ContentItem.class) {
        return (T) item;
    }
    T bean = null;
    try {
        //Invoke the default constructor
        bean = ConstructorUtils.invokeConstructor(tClass, null);

        //Get the bean properties
        Field[] fields = tClass.getDeclaredFields();

        //Inject mappings
        for (Field field : fields) {
            Object value = getValueForField(item, modularContent, bean, field);
            if (value != null) {
                BeanUtils.setProperty(bean, field.getName(), value);
            }
        }
    } catch (NoSuchMethodException |
            IllegalAccessException |
            InvocationTargetException |
            InstantiationException e) {
        handleReflectionException(e);
    }
    //Return bean
    return bean;
}
 
Example 20
Project: FastDFS_Client   File: FdfsParamMapper.java   View Source Code Vote up 5 votes
/**
 * 按列顺序映射
 * 
 * @param content
 * @param genericType
 * @param objectMap
 * @return
 * @throws InstantiationException
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 */
private static <T> T mapByIndex(byte[] content, Class<T> genericType, ObjectMateData objectMap, Charset charset)
        throws InstantiationException, IllegalAccessException, InvocationTargetException {

    List<FieldMateData> mappingFields = objectMap.getFieldList();
    T obj = genericType.newInstance();
    for (int i = 0; i < mappingFields.size(); i++) {
        FieldMateData field = mappingFields.get(i);
        // 设置属性值
        LOGGER.debug("设置值是 " + field + field.getValue(content, charset));
        BeanUtils.setProperty(obj, field.getFieldName(), field.getValue(content, charset));
    }

    return obj;
}
 
Example 21
Project: TranskribusSwtGui   File: BindColorToButtonListener.java   View Source Code Vote up 5 votes
private void updatePropertyFromWidget() {
	ColorDialog cd = new ColorDialog(Display.getCurrent().getActiveShell());
	cd.setText("Choose color");
	cd.setRGB(getValueOfProperty().getRGB());
	RGB newColor = cd.open();
	if (newColor == null)
		return;
			
	try {
		BeanUtils.setProperty(bean, property, Colors.createColor(newColor));
	} catch (IllegalAccessException | InvocationTargetException e) {
		throw new RuntimeException(e);
	}	
}
 
Example 22
Project: TranskribusSwtGui   File: Utils.java   View Source Code Vote up 5 votes
public static void setBeanProperties(Object bean, Configuration config) /*throw IllegalAccessException, InvocationTargetException, NoSuchMethodException*/ {
	BeanMap beanmap = new BeanMap(bean);
	
	Iterator<String> it = config.getKeys();
	
	while (it.hasNext()) {
		String key = it.next();
		String value = config.getProperty(key).toString().trim();
		Class<?> type = beanmap.getType(key);
		if (type == null) {
			// no such property!
			logger.debug("Could not find property: " + key);
			continue;
		}
			
		
		logger.debug("setting property '"+key+"' of bean '"+bean.getClass().getSimpleName()+"' to '"+value+"'"+ " type = "+type);
		
		try {
			Object valueObject = getValue(beanmap.getType(key), value);
			BeanUtils.setProperty(bean, key, valueObject);
		}
		catch (Exception ex) {
			logger.warn("Could not set value of config attribute "+key+" to "+value+", error: "+ex.getMessage());
		}
		
	}
}
 
Example 23
Project: OSCAR-ConCert   File: BORNWbXmlGenerator.java   View Source Code Vote up 5 votes
private void setNDDSAnswer(String formName, String formKey, String xmlName, Object ndds) {
	NDDSResponseCodes.Enum resp = null;
	if ((resp = getNDDSAnswer(formName, formKey)) != null) {
		try {
			BeanUtils.setProperty(ndds, xmlName, resp);
		} catch (Exception e) {
			MiscUtils.getLogger().warn("error setting XML value from NDDS", e);
		}
	}
}
 
Example 24
Project: OSCAR-ConCert   File: BORNWbXmlGenerator.java   View Source Code Vote up 5 votes
private void setNDDSCompletionDateTime(String formName, Object ndds) {
	EFormValue date = this.eformValuesMap.get(formName).get("today");
	if (date != null && date.getVarValue() != null && !date.getVarValue().isEmpty()) {
		try {
			Date x = visitDateFormatter.parse(date.getVarValue());
			Calendar c = Calendar.getInstance();
			c.setTime(x);

			BeanUtils.setProperty(ndds, "NDDSCompletionDateTime", c);
		} catch (Exception e) {
			MiscUtils.getLogger().warn("invalid date " + date.getVarValue());
		}
	}
}
 
Example 25
Project: gluu   File: JsonConfigurationAction.java   View Source Code Vote up 5 votes
private void processPasswordProperty(ApplicationConfiguration source, ApplicationConfiguration current, String property) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, EncryptionException {
	String currentValue = BeanUtils.getProperty(current, property);
	if (StringHelper.equals(currentValue, HIDDEN_PASSWORD_TEXT)) {
		String sourceValue = BeanUtils.getSimpleProperty(source, property);
		BeanUtils.setProperty(current, property, sourceValue);
	} else {
		String currentValueEncrypted = StringEncrypter.defaultInstance().encrypt(currentValue, cryptoConfigurationSalt);
		BeanUtils.setProperty(current, property, currentValueEncrypted);
	}
}
 
Example 26
Project: osframe   File: JSONHelper.java   View Source Code Vote up 5 votes
/***
 * 将JSON文本反序列化为主从关系的实体
 * 
 * @param <T>
 *            主实体类型
 * @param jsonString
 *            JSON文本
 * @param mainClass
 *            主实体类型
 * @param detailClass
 *            存放了多个从实体在主实体中属性名称和类型
 * @return
 */
public static <T> T toBean(String jsonString, Class<T> mainClass,
		HashMap<String, Class> detailClass) {
	JSONObject jsonObject = JSONObject.fromObject(jsonString);
	T mainEntity = JSONHelper.toBean(jsonObject, mainClass);
	for (Object key : detailClass.keySet()) {
		try {
			Class value = (Class) detailClass.get(key);
			BeanUtils.setProperty(mainEntity, key.toString(), value);
		} catch (Exception ex) {
			throw new RuntimeException("主从关系JSON反序列化实体失败!");
		}
	}
	return mainEntity;
}
 
Example 27
Project: gemfirexd-oss   File: TestAgainstLiveDatabaseBase.java   View Source Code Vote up 5 votes
/**
 * Initializes the test datasource and the platform.
 * 
 * @param props The properties to initialize from
 * @return The data source object
 */
private static DataSource initDataSourceFromProperties(Properties props)
{
    if (props == null)
    {
        return null;
    }

    try
    {
        String     dataSourceClass = props.getProperty(DATASOURCE_PROPERTY_PREFIX + "class", BasicDataSource.class.getName());
        DataSource dataSource      = (DataSource)Class.forName(dataSourceClass).newInstance();

        for (Iterator it = props.entrySet().iterator(); it.hasNext();)
        {
            Map.Entry entry    = (Map.Entry)it.next();
            String    propName = (String)entry.getKey();

            if (propName.startsWith(DATASOURCE_PROPERTY_PREFIX) && !propName.equals(DATASOURCE_PROPERTY_PREFIX +"class"))
            {
                BeanUtils.setProperty(dataSource,
                                      propName.substring(DATASOURCE_PROPERTY_PREFIX.length()),
                                      entry.getValue());
            }
        }
        return dataSource;
    }
    catch (Exception ex)
    {
        throw new DatabaseOperationException(ex);
    }
}
 
Example 28
Project: dingding-app-server   File: WebUtil.java   View Source Code Vote up 5 votes
/**
 * 转换请求中的参数为简单对象(只有对象中的简单类型会被赋值),参数值为数组的只取第一个
 *
 * @param request 请求对象
 * @param claz    目标对象类型类
 * @param <T>     目标对象类型
 * @return 目标对象
 * @throws IllegalAccessException
 * @throws InstantiationException
 */
public static <T> T paramsToSimpleBean(HttpServletRequest request, Class<T> claz) throws IllegalAccessException, InstantiationException {
    Map<String, String[]> paramMap = request.getParameterMap();
    T object = claz.newInstance();
    for (Map.Entry<String, String[]> ent : paramMap.entrySet()) {
        if (StringUtils.isNotBlank(ent.getKey()) && ent.getValue() != null && ent.getValue().length > 0 && StringUtils.isNotBlank(ent.getValue()[0])) {
            try {
                BeanUtils.setProperty(object, ent.getKey(), ent.getValue()[0]);
            } catch (Exception e) {
            }
        }
    }
    return object;
}
 
Example 29
Project: coordinated-entry   File: QueryExecutorImpl.java   View Source Code Vote up 5 votes
public Object update(Object entity) {
	try {
		BeanUtils.setProperty(entity, "updatedAt", LocalDateTime.now());
		BeanUtils.copyProperty(entity, "user", SecurityContextUtil.getUserAccount().getUsername());
		getCurrentSession().update(entity);
	} catch (Exception e) {
		e.printStackTrace();
		return null;
	}
	return null;
}
 
Example 30
Project: potato-webmvc   File: BeanHelper.java   View Source Code Vote up 4 votes
public static void setProperty(Object bean, String name, Object value) throws IllegalAccessException, InvocationTargetException{
BeanUtils.setProperty(bean, name, value);
}
 
Example 31
Project: osframe   File: JSONHelper.java   View Source Code Vote up 4 votes
/***
 * 将JSON文本反序列化为主从关系的实体
 * 
 * @param <T>
 *            泛型T 代表主实体类型
 * @param <D>
 *            泛型D 代表从实体类型
 * @param jsonString
 *            JSON文本
 * @param mainClass
 *            主实体类型
 * @param detailName
 *            从实体类在主实体类中的属性名称
 * @param detailClass
 *            从实体类型
 * @return
 */
public static <T, D> T toBean(String jsonString, Class<T> mainClass,
		String detailName, Class<D> detailClass) {
	JSONObject jsonObject = JSONObject.fromObject(jsonString);
	JSONArray jsonArray = (JSONArray) jsonObject.get(detailName);

	T mainEntity = JSONHelper.toBean(jsonObject, mainClass);
	List<D> detailList = JSONHelper.toList(jsonArray, detailClass);

	try {
		BeanUtils.setProperty(mainEntity, detailName, detailList);
	} catch (Exception ex) {
		throw new RuntimeException("主从关系JSON反序列化实体失败!");
	}

	return mainEntity;
}