Java Code Examples for org.apache.commons.beanutils.BeanUtils

The following are top voted examples for showing how to use org.apache.commons.beanutils.BeanUtils. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: spring-boot   File: MyBeanUtils.java   View source code 10 votes vote down vote up
/**
 * map to bean
 * 转换过程中,由于属性的类型不同,需要分别转换。
 * java 反射机制,转换过程中属性的类型默认都是 String 类型,否则会抛出异常,而 BeanUtils 项目,做了大量转换工作,比 java 反射机制好用
 * BeanUtils 的 populate 方法,对 Date 属性转换,支持不好,需要自己编写转换器
 *
 * @param map  待转换的 map
 * @param bean 满足 bean 格式,且需要有无参的构造方法; bean 属性的名字应该和 map 的 key 相同
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 */
private static void mapToBean(Map<String, Object> map, Object bean) throws IllegalAccessException, InvocationTargetException {

    //注册几个转换器
    ConvertUtils.register(new SqlDateConverter(null), java.sql.Date.class);
    ConvertUtils.register(new SqlTimestampConverter(null), java.sql.Timestamp.class);
    //注册一个类型转换器  解决 common-beanutils 为 Date 类型赋值问题
    ConvertUtils.register(new Converter() {
        //  @Override
        public Object convert(Class type, Object value) { // type : 目前所遇到的数据类型。  value :目前参数的值。
            // System.out.println(String.format("value = %s", value));

            if (value == null || value.equals("") || value.equals("null"))
                return null;
            Date date = null;
            try {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                date = dateFormat.parse((String) value);
            } catch (Exception e) {

                e.printStackTrace();
            }

            return date;
        }

    }, Date.class);

    BeanUtils.populate(bean, map);
}
 
Example 2
Project: Android_Code_Arbiter   File: BeanInjection.java   View source code 8 votes vote down vote up
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{
    User user = new User();
    HashMap map = new HashMap();
    Enumeration names = request.getParameterNames();
    while (names.hasMoreElements()) {
        String name = (String) names.nextElement();
        map.put(name, request.getParameterValues(name));
    }
    try{
        BeanUtils.populate(user, map); //BAD

        BeanUtilsBean beanUtl = BeanUtilsBean.getInstance();
        beanUtl.populate(user, map); //BAD
    }catch(Exception e){
        e.printStackTrace();
    }
}
 
Example 3
Project: gluu   File: JsonConfigurationAction.java   View source code 7 votes vote down vote up
private String getProtectedOxTrustApplicationConfiguration(ApplicationConfiguration oxTrustApplicationConfiguration) {
	try {
		ApplicationConfiguration resultOxTrustApplicationConfiguration = (ApplicationConfiguration) BeanUtils.cloneBean(oxTrustApplicationConfiguration);

		resultOxTrustApplicationConfiguration.setSvnConfigurationStorePassword(HIDDEN_PASSWORD_TEXT);
		resultOxTrustApplicationConfiguration.setKeystorePassword(HIDDEN_PASSWORD_TEXT);
		resultOxTrustApplicationConfiguration.setIdpSecurityKeyPassword(HIDDEN_PASSWORD_TEXT);
		resultOxTrustApplicationConfiguration.setIdpBindPassword(HIDDEN_PASSWORD_TEXT);
		resultOxTrustApplicationConfiguration.setMysqlPassword(HIDDEN_PASSWORD_TEXT);
		resultOxTrustApplicationConfiguration.setCaCertsPassphrase(HIDDEN_PASSWORD_TEXT);
		resultOxTrustApplicationConfiguration.setOxAuthClientPassword(HIDDEN_PASSWORD_TEXT);

		return jsonService.objectToJson(resultOxTrustApplicationConfiguration);
	} catch (Exception ex) {
		log.error("Failed to prepare JSON from ApplicationConfiguration: '{0}'", ex, oxTrustApplicationConfiguration);
	}

	return null;
}
 
Example 4
Project: OMIPlatform   File: TzUserDetailsService.java   View source code 6 votes vote down vote up
@Override
public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {

    User user = this.userService.findByName(name);
    TzUserDetails userDetails = new TzUserDetails();

    if(user == null){
        throw new UsernameNotFoundException("用户不存在");
    }

    try {
        BeanUtils.copyProperties(userDetails,user);
    } catch (Exception e) {
        e.printStackTrace();
    }

    logger.info("---->身份验证:"+userDetails.getUsername()+":"+userDetails.getPassword());

   return userDetails;
}
 
Example 5
Project: OMIPlatform   File: ShopProductDto.java   View source code 6 votes vote down vote up
public static List<ShopProductDto> convert(List<ShopProduct> products,ObjectMapper objectMapper) throws InvocationTargetException, IllegalAccessException {
    if (products == null) {
        return null;
    }
    List<ShopProductDto> productDtos = new ArrayList();
    for (int i = 0; i < products.size(); i++) {
        ShopProductDto tmp = new ShopProductDto();
        BeanUtils.copyProperties(tmp, products.get(i));
        try {
            /*处理图片信息转换*/
           tmp.setImgs(tmp.parseImageList(objectMapper)) ;
            /*处理基础信息转换*/
            tmp.parseBaseProperty(objectMapper);
            /*其他转换操作*/
        } catch (IOException e) {
            e.printStackTrace();
        }
        productDtos.add(tmp);
    }
    return productDtos;
}
 
Example 6
Project: JRediClients   File: EntityProxyFactory.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
public <T extends IEntity> T createProxyEntity(T entity) throws Exception {
	EntityProxy entityProxy = createProxy(entity);
	if (entityProxy != null) {
		EntityProxyWrapper entityProxyWrapper = new EntityProxyWrapper(entityProxy);			
		AbstractEntity proxyEntity = createProxyEntity(entityProxy);
		if(proxyEntity!=null) {
			// 注入对象 数值
			BeanUtils.copyProperties(proxyEntity, entity);
			entityProxy.setCollectFlag(true);
			if(entityProxyWrapper != null) {
				proxyEntity.setEntityProxyWrapper(entityProxyWrapper);
				return (T) proxyEntity;
			}
		}
	}
	return null;
}
 
Example 7
Project: airtable.java   File: Table.java   View source code 6 votes vote down vote up
/**
 *
 * @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 8
Project: airtable.java   File: Table.java   View source code 6 votes vote down vote up
/**
 * Checks if the Property Values of the item are valid for the Request.
 *
 * @param item
 * @throws AirtableException
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 * @throws NoSuchMethodException
 */
private void checkProperties(T item) throws AirtableException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {

    if (propertyExists(item, FIELD_ID) || propertyExists(item, FIELD_CREATED_TIME)) {
        Field[] attributes = item.getClass().getDeclaredFields();
        for (Field attribute : attributes) {
            String attrName = attribute.getName();
            if (FIELD_ID.equals(attrName) || FIELD_CREATED_TIME.equals(attrName)) {
                if (BeanUtils.getProperty(item, attribute.getName()) != null) {
                    throw new AirtableException("Property " + attrName + " should be null!");
                }
            } else if ("photos".equals(attrName)) {
                List<Attachment> obj = (List<Attachment>) BeanUtilsBean.getInstance().getPropertyUtils().getProperty(item, "photos");
                checkPropertiesOfAttachement(obj);
            }
        }
    }

}
 
Example 9
Project: airtable.java   File: Table.java   View source code 6 votes vote down vote up
/**
 * Check properties of Attachement objects.
 * 
 * @param attachements
 * @throws AirtableException
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 * @throws NoSuchMethodException 
 */
private void checkPropertiesOfAttachement(List<Attachment> attachements) throws AirtableException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {

    if (attachements != null) {
        for (int i = 0; i < attachements.size(); i++) {
            if (propertyExists(attachements.get(i), FIELD_ID) || propertyExists(attachements.get(i), "size") 
                    || propertyExists(attachements.get(i), "type") || propertyExists(attachements.get(i), "filename")) {
                
                final Field[] attributesPhotos = attachements.getClass().getDeclaredFields();
                for (Field attributePhoto : attributesPhotos) {
                    final String namePhotoAttribute = attributePhoto.getName();
                    if (FIELD_ID.equals(namePhotoAttribute) || "size".equals(namePhotoAttribute) 
                            || "type".equals(namePhotoAttribute) || "filename".equals(namePhotoAttribute)) {
                        if (BeanUtils.getProperty(attachements.get(i), namePhotoAttribute) != null) {
                            throw new AirtableException("Property " + namePhotoAttribute + " should be null!");
                        }
                    }
                }
            }
        }
    }
}
 
Example 10
Project: tasfe-framework   File: MysqlTemplate.java   View source code 6 votes vote down vote up
/********************************** get *************************************/

    @Override
    public <T> T _get(Class<T> clazz, Long pv) throws Exception {
        Map<String, Object> param = new HashMap<>();

        String tableName = GeneralMapperReflectUtil.getTableName(clazz);
        String primaryKey = GeneralMapperReflectUtil.getPrimaryKey(clazz);
        List<String> queryColumn = GeneralMapperReflectUtil.getAllColumns(clazz, false);

        param.put("_table_", tableName);
        param.put("_pk_", primaryKey);
        param.put("_pv_", pv);
        param.put("_query_column_", queryColumn);
        Map map = sqlSession.selectOne(Crudable.GET, param);
        T t = clazz.newInstance();
        BeanUtils.populate(t, map);
        return t;
    }
 
Example 11
Project: jambo2   File: BaseVO.java   View source code 6 votes vote down vote up
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 12
Project: jambo2   File: SQLHelper.java   View source code 6 votes vote down vote up
protected Map getConditions(Object param) throws IllegalAccessException,
        InvocationTargetException, NoSuchMethodException {

    // 静态条件部分
    Map props = BeanUtils.describe(param);

    // new 动态条件部分 add by hekun
    if (param instanceof DBQueryParam) {
        DBQueryParam listVO = (DBQueryParam) param;
        Map queryConditions = listVO.getQueryConditions();

        if (queryConditions != null && queryConditions.size() > 0) {
            // 将静态条件加入动态条件中,重复的动态条件及其值将被覆盖。
            for (Iterator keys = props.keySet().iterator(); keys.hasNext(); ) {
                String key = (String) keys.next();
                Object value = props.get(key);
                if (key.startsWith("_") && value != null)
                    queryConditions.put(key, value);
            }
            props = queryConditions;
        }
    }
    return props;
}
 
Example 13
Project: jambo2   File: SQLHelper.java   View source code 6 votes vote down vote up
protected List getOrderedKeyset(Set keys, Object param) throws Exception {
    List orderedKeyset = new ArrayList();
    if (keys.size() > 0) {
        String firstitems = BeanUtils.getProperty(param,
                "_firstitems");
        String firstitemname = null;
        if (firstitems != null) {
            for (StringTokenizer st = new StringTokenizer(firstitems, ","); st
                    .hasMoreTokens(); ) {
                firstitemname = st.nextToken();
                if (keys.contains(firstitemname)) {
                    orderedKeyset.add(firstitemname);
                }
            }
        }
        for (Iterator it = keys.iterator(); it.hasNext(); ) {
            String key = (String) it.next();
            if (!orderedKeyset.contains(key))
                orderedKeyset.add(key);
        }
    }
    return orderedKeyset;
}
 
Example 14
Project: lams   File: LtiConsumerManagementAction.java   View source code 6 votes vote down vote up
/**
    * Edits specified LTI tool consumer
    */
   public ActionForward edit(ActionMapping mapping, ActionForm form, HttpServletRequest request,
    HttpServletResponse response) throws Exception {

initServices();

DynaActionForm ltiConsumerForm = (DynaActionForm) form;
Integer sid = WebUtil.readIntParam(request, "sid", true);

// editing a tool consumer
if (sid != null) {
    ExtServer ltiConsumer = integrationService.getExtServer(sid);
    BeanUtils.copyProperties(ltiConsumerForm, ltiConsumer);
    String lessonFinishUrl = ltiConsumer.getLessonFinishUrl() == null ? "-" : ltiConsumer.getLessonFinishUrl();
    request.setAttribute("lessonFinishUrl", lessonFinishUrl);

// create a tool consumer
} else { 
    //do nothing
}

return mapping.findForward("ltiConsumer");	
   }
 
Example 15
Project: domino   File: DesktopRequestAsyncSender.java   View source code 6 votes vote down vote up
private String formattedPath(Collection<String> pathParams, RequestBean arguments, String path) {
    final String[] processedPath = {path};
    pathParams.forEach(p -> {
        try {
            String value;
            if (isNested(p)) {
                value = getNestedValue(arguments, p);
            } else
                value = BeanUtils.getProperty(arguments, p);

            processedPath[0] = processedPath[0].replace("{" + p + "}", isNull(value) ? "" : value);
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            processedPath[0] = processedPath[0].replace("{" + p + "}", p);
        }
    });

    return processedPath[0];
}
 
Example 16
Project: qonduit   File: NotEmptyIfFieldSetValidator.java   View source code 6 votes vote down vote up
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
    if (value == null) {
        return true;
    }

    try {
        final String fieldValue = BeanUtils.getProperty(value, fieldName);
        final String notNullFieldValue = BeanUtils.getProperty(value, notNullFieldName);
        if (StringUtils.equals(fieldValue, fieldSetValue) && StringUtils.isEmpty(notNullFieldValue)) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate())
                    .addPropertyNode(notNullFieldName).addConstraintViolation();
            return false;
        }
    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
        throw new RuntimeException(e);
    }

    return true;
}
 
Example 17
Project: FCat   File: ObjectUtil.java   View source code 6 votes vote down vote up
/**
* 类实现 Maps --> Bean  
* @param objClass
* @param objMaps
*/
  public static  <T> List<T> map2BeanList(List<Map<String, Object>> objMaps, Class<T> objClass) {  
      if (objMaps == null || objClass == null) {  
          return Collections.emptyList();  
      }  
      List<T> objList = new ArrayList<T>();
      try { 
      	for(Map<String, Object> mapObj : objMaps) {
       	T obj = objClass.newInstance();
           BeanUtils.populate(obj, mapObj);
           objList.add(obj);
      	}
      } catch (Exception e) {  
      	logger.error(e.getMessage());
      } 
      return objList;
  }
 
Example 18
Project: OfficeAutomation   File: RowConvert.java   View source code 6 votes vote down vote up
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 19
Project: scoold   File: QuestionController.java   View source code 6 votes vote down vote up
@PostMapping("/{id}/edit")
public String edit(@PathVariable String id, @RequestParam(required = false) String title,
		@RequestParam(required = false) String body, @RequestParam(required = false) String tags,
		HttpServletRequest req) {

	Post showPost = pc.read(id);
	Profile authUser = utils.getAuthUser(req);
	if (!utils.canEdit(showPost, authUser) || showPost == null) {
		return "redirect:" + req.getRequestURI();
	}
	Post beforeUpdate = null;
	try {
		beforeUpdate = (Post) BeanUtils.cloneBean(showPost);
	} catch (Exception ex) {
		logger.error(null, ex);
	}

	if (!StringUtils.isBlank(title) && title.length() > 10) {
		showPost.setTitle(title);
	}
	if (!StringUtils.isBlank(body)) {
		showPost.setBody(body);
	}
	if (!StringUtils.isBlank(tags) && showPost.isQuestion()) {
		showPost.setTags(Arrays.asList(StringUtils.split(tags, ",")));
	}

	//note: update only happens if something has changed
	if (!showPost.equals(beforeUpdate)) {
		showPost.setLasteditby(authUser.getId());
		showPost.setLastedited(System.currentTimeMillis());
		showPost.update();
		utils.addBadgeOnceAndUpdate(authUser, Badge.EDITOR, true);
	}
	return "redirect:" + showPost.getPostLink(false, false);
}
 
Example 20
Project: UtilsMaven   File: DBUtils.java   View source code 6 votes vote down vote up
/**
 * 将所有记录包装成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 21
Project: bdf2   File: DbService.java   View source code 6 votes vote down vote up
/**
 * 插入表新列
 * 
 * @param dbInfoId
 * @param columnInfo
 * @throws Exception
 */
public void insertColumn(String dbInfoId, ColumnInfo columnInfo) throws Exception {
	com.bstek.bdf2.core.orm.jdbc.dialect.ColumnInfo dbColumnInfo = new com.bstek.bdf2.core.orm.jdbc.dialect.ColumnInfo();
	BeanUtils.copyProperties(dbColumnInfo, columnInfo);
	String tableName = columnInfo.getTableName();
	String columnName = columnInfo.getColumnName();
	boolean isprimaryKey = columnInfo.isIsprimaryKey();
	List<String> primaryKeys = findTablePrimaryKeys(dbInfoId, tableName);
	if (isprimaryKey) {
		primaryKeys.add(columnName);
		dbColumnInfo.setListPrimaryKey(primaryKeys);
		String pkName = this.findSqlServerPKIndex(dbInfoId, tableName);
		log.debug("pkName:" + pkName);
		if (StringUtils.hasText(pkName)) {
			dbColumnInfo.setPkName(pkName);
		}
	}
	IDialect dBDialect = getDBDialectByDbInfoId(dbInfoId);
	String sql = dBDialect.getNewColumnSql(dbColumnInfo);
	String[] sqls = sql.split(";");
	this.updateSql(dbInfoId, sqls);

}
 
Example 22
Project: validator-web   File: DefaultContainer.java   View source code 6 votes vote down vote up
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 23
Project: demo   File: ConverterApp.java   View source code 6 votes vote down vote up
private static void entity2Dto() {
	EUser u = new EUser();
	u.setId(1l);
	u.setUsername("yoking");
	u.setCreationDate(new Date(System.currentTimeMillis()));
	
	UserDTO user = new UserDTO();
	
	ConvertUtils.register(new DateStringConverter(), String.class);
	try {
		BeanUtils.copyProperties(user, u);
	} catch (IllegalAccessException | InvocationTargetException e) {
		e.printStackTrace();
	}
	
	System.out.println(user);
}
 
Example 24
Project: demo   File: ConverterApp.java   View source code 6 votes vote down vote up
private static void dto2Entity() {
	UserDTO user = new UserDTO();
	user.setId(1l);
	user.setUsername("joking");
	user.setCreationDate("2016-04-20");
	
	EUser u = new EUser();
	ConvertUtils.register(new DateStringConverter(), Date.class);
	try {
		BeanUtils.copyProperties(u, user);
	} catch (IllegalAccessException | InvocationTargetException e) {
		e.printStackTrace();
	}
	
	System.out.println(u);
}
 
Example 25
Project: sam-elle   File: BtyDataConverter.java   View source code 6 votes vote down vote up
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 26
Project: Shop   File: JSONUtils.java   View source code 6 votes vote down vote up
/***
 * 将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 27
Project: Shop   File: JSONUtils.java   View source code 6 votes vote down vote up
/***
 * 将JSON文本反序列化为主从关系的实体
 * @param 泛型T 代表主实体类型
 * @param 泛型D1 代表从实体类型
 * @param 泛型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 = JSONUtils.toBean(jsonObject, mainClass);
    List<D1> detailList1 = JSONUtils.toList(jsonArray1, detailClass1);
    List<D2> detailList2 = JSONUtils.toList(jsonArray2, detailClass2);

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

    return mainEntity;
}
 
Example 28
Project: Shop   File: JSONUtils.java   View source code 6 votes vote down vote up
/***
    * 将JSON文本反序列化为主从关系的实体
    * @param 主实体类型
    * @param jsonString JSON文本
    * @param mainClass 主实体类型
    * @param detailClass 存放了多个从实体在主实体中属性名称和类型
    * @return
    */
   @SuppressWarnings("rawtypes")
public static <T> T toBean(String jsonString, Class<T> mainClass,
           HashMap<String, Class> detailClass)
   {
       JSONObject jsonObject = JSONObject.fromObject(jsonString);
       T mainEntity = JSONUtils.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 29
Project: sistra   File: ResultadoRegistro.java   View source code 6 votes vote down vote up
public String toString()
{
	try
	{
		StringBuffer sb = new StringBuffer( "{" );
		Map properties = BeanUtils.describe( this );
		for ( Iterator it = properties.keySet().iterator(); it.hasNext(); )
		{
			Object key = it.next();
			Object value = properties.get( key );
			sb.append( key.toString() ).append( "=" ).append( value != null ? value.toString() : null ).append( it.hasNext() ? ", " : "") ; 
		}
		sb.append( "}" );
		return sb.toString();
	}
	catch( Exception exc )
	{
		exc.printStackTrace();
		return super.toString();
	}
}
 
Example 30
Project: sistra   File: SeleccionarCuadernoCargaAction.java   View source code 6 votes vote down vote up
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception 
{
    String idString = request.getParameter("codigo");
    idString = StringUtils.defaultString( idString, ( String ) request.getAttribute( "codigoCuaderno" ));
    if (idString == null || idString.length() == 0) {
        log.warn("El par�metre codigo �s null!!");
        return mapping.findForward("fail");
    }
    Long id = new Long(idString);
    
    CuadernoCargaForm cuadernoCargaForm = ( CuadernoCargaForm ) form;
    
    CuadernoCargaDelegate delegate = DelegateUtil.getCuadernoCargaDelegate();
    CuadernoCarga cuadernoCarga = delegate.obtenerCuadernoCarga( id );
    
    BeanUtils.copyProperties( cuadernoCargaForm, cuadernoCarga );
    
    cuadernoCargaForm.setRawFechaCarga( StringUtil.fechaACadena( cuadernoCarga.getFechaCarga() ) );
    
    request.setAttribute( "cuadernoCarga", cuadernoCarga );
    Util.setDevelopperMode( request );
		
    return mapping.findForward( "success" );
    
}
 
Example 31
Project: sistra   File: TramitePersistenteFacadeEJB.java   View source code 6 votes vote down vote up
/**
  * @ejb.interface-method
  * @ejb.permission role-name="${role.auto}"
  * @ejb.permission role-name="${role.todos}"
  * @param tramitePersistente
  * @return
  */
 public void backupTramitePersistente( TramitePersistente tramitePersistente )
 {
 	try
 	{
     	TramitePersistenteBackup result = new TramitePersistenteBackup();
  	BeanUtils.copyProperties( result, tramitePersistente );
Set setDocumentos = tramitePersistente.getDocumentos(); 
for ( Iterator it = setDocumentos.iterator(); it.hasNext(); )
{
	DocumentoPersistente documento = ( DocumentoPersistente ) it.next();
   	DocumentoPersistenteBackup backup = new DocumentoPersistenteBackup();
   	BeanUtils.copyProperties( backup, documento );
   	result.addDocumentoBackup( backup );
}
grabarBackupTramitePersistente ( result );
 	}
 	catch( Exception exc )
 	{
 		throw new EJBException( exc );
 	}
 }
 
Example 32
Project: sistra   File: NotificacionTelematicaFacadeEJB.java   View source code 6 votes vote down vote up
/**
    * Devuelve notificacion con informacion exclusiva de aviso
    * @param notificacionTelematica
    * @return
    */
   private NotificacionTelematica notificacionSinAbrir(NotificacionTelematica notificacionTelematica) throws Exception {
	
   	NotificacionTelematica not = new NotificacionTelematica();
   	BeanUtils.copyProperties(not,notificacionTelematica);

   	// Eliminamos referencia rds a oficio
   	not.setCodigoRdsOficio(0);
   	not.setClaveRdsOficio(null);
   	
   	// Eliminamos documentos
   	not.getDocumentos().clear();
   	
   	// Eliminamos tramite de subsanacion
   	not.setTramiteSubsanacionDescripcion(null);
   	not.setTramiteSubsanacionIdentificador(null);
   	not.setTramiteSubsanacionVersion(null);
   	not.setTramiteSubsanacionParametros(null);
   	
	return not;
}
 
Example 33
Project: wechat-core   File: BeanTest.java   View source code 6 votes vote down vote up
@Test
public void testMap2Bean() throws Exception {
    Map<String, Object> map = Maps.newHashMap();
    map.put("Username", "jonnyliu");
    map.put("Age", 39);
    User user = new User();
    Map map1 = Maps.newHashMap();
    map.forEach((x, y) -> {
        char[] charArray = x.toCharArray();
        charArray[0] = Character.toLowerCase(charArray[0]);
        map1.put(new String(charArray), y);
    });
    BeanUtils.populate(user, map1);

    System.out.println(user);
}
 
Example 34
Project: mycore   File: MCRRequestDebugFilter.java   View source code 6 votes vote down vote up
private String getValue(String key, Optional<Object> value) {

        return value.map(o -> {
            if (!hasSafeToString(o)) {
                try {
                    Map<String, String> beanDescription = BeanUtils.describe(value);
                    if (!beanDescription.isEmpty()) {
                        return beanDescription.toString();
                    }
                } catch (Exception e) {
                    LOGGER.error("BeanUtils Exception describing attribute {}", key, e);
                }
            }
            return o.toString();
        }).orElse("<null>");
    }
 
Example 35
Project: whatsmars   File: DbRouteInterceptor.java   View source code 6 votes vote down vote up
@Before("aopPoint()")
public Object doRoute(JoinPoint jp) throws Throwable {
    boolean result = true;
    Method method = this.getMethod(jp);
    DbRoute dbRoute = method.getAnnotation(DbRoute.class);
    String routeField = dbRoute.field();  // userId
    Object[] args = jp.getArgs();  
    if(args != null && args.length > 0) {  
        for(int i = 0; i < args.length; ++i) {  
            String routeFieldValue = BeanUtils.getProperty(args[i], routeField);
            if(StringUtils.isNotEmpty(routeFieldValue)) {
                if("userId".equals(routeField)) {  
                    this.dbRouter.route(routeField);
                }
                break;  
            }  
        }  
    }  
  
    return Boolean.valueOf(result);
}
 
Example 36
Project: leopard   File: BaseInfoBuilder.java   View source code 6 votes vote down vote up
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 37
Project: osframe   File: JSONHelper.java   View source code 6 votes vote down vote up
/***
 * 将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 38
Project: osframe   File: JSONHelper.java   View source code 6 votes vote down vote up
/***
 * 将JSON文本反序列化为主从关系的实体
 * 
 * @param <T>泛型T 代表主实体类型
 * @param <D1>泛型D1 代表从实体类型
 * @param <D2>泛型D2 代表从实体类型
 * @param jsonString
 *            JSON文本
 * @param mainClass
 *            主实体类型
 * @param detailName1
 *            从实体类在主实体类中的属性
 * @param detailClass1
 *            从实体类型
 * @param detailName2
 *            从实体类在主实体类中的属性
 * @param detailClass2
 *            从实体类型
 * @param detailName3
 *            从实体类在主实体类中的属性
 * @param detailClass3
 *            从实体类型
 * @return
 */
public static <T, D1, D2, D3> T toBean(String jsonString,
		Class<T> mainClass, String detailName1, Class<D1> detailClass1,
		String detailName2, Class<D2> detailClass2, String detailName3,
		Class<D3> detailClass3) {
	JSONObject jsonObject = JSONObject.fromObject(jsonString);
	JSONArray jsonArray1 = (JSONArray) jsonObject.get(detailName1);
	JSONArray jsonArray2 = (JSONArray) jsonObject.get(detailName2);
	JSONArray jsonArray3 = (JSONArray) jsonObject.get(detailName3);

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

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

	return mainEntity;
}
 
Example 39
Project: bigstreams   File: DateHourFileNameExtractor.java   View source code 6 votes vote down vote up
@Override
public String getFileName(FileStatus.FileTrackingStatus status) {

	StringBuilder buff = new StringBuilder();

	try {
		for (String key : keyProperties) {
			buff.append(BeanUtils.getSimpleProperty(status, key));
		}
	} catch (Throwable t) {
		RuntimeException rte = new RuntimeException(t.toString(), t);
		rte.setStackTrace(t.getStackTrace());
		throw rte;
	}

	buff.append(".");
	buff.append(extractDateTime(status.getFileName()));

	return buff.toString();
}
 
Example 40
Project: timely   File: NotEmptyIfFieldSetValidator.java   View source code 6 votes vote down vote up
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
    if (value == null) {
        return true;
    }

    try {
        final String fieldValue = BeanUtils.getProperty(value, fieldName);
        final String notNullFieldValue = BeanUtils.getProperty(value, notNullFieldName);
        if (StringUtils.equals(fieldValue, fieldSetValue) && StringUtils.isEmpty(notNullFieldValue)) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate())
                    .addPropertyNode(notNullFieldName).addConstraintViolation();
            return false;
        }
    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
        throw new RuntimeException(e);
    }

    return true;
}