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

The following examples show how to use org.apache.commons.beanutils.BeanUtils#populate() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BrooklynDslCommon.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
public static <T> T create(Class<T> type, List<?> constructorArgs, Map<String,?> fields, Map<String,?> config) {
    try {
        T bean = Reflections.invokeConstructorFromArgs(type, constructorArgs.toArray()).get();
        BeanUtils.populate(bean, fields);

        if (config.size() > 0) {
            if (bean instanceof Configurable) {
                ConfigBag configBag = ConfigBag.newInstance(config);
                FlagUtils.setFieldsFromFlags(bean, configBag);
                FlagUtils.setAllConfigKeys((Configurable) bean, configBag, true);
            } else {
                LOG.warn("While building object, type "+type+" is not 'Configurable'; cannot apply supplied config (continuing)");
            }
        }
        return bean;
    } catch (Exception e) {
        throw Exceptions.propagate(e);
    }
}
 
Example 2
Source File: AsksAction.java    From csustRepo with MIT License 6 votes vote down vote up
public String reply(){
	RepMessage message=messageService.get(id);
	
	if(getRequest().getMethod().equals("POST")){
		
           try {
			BeanUtils.populate(message, getParameters());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

   		message.setRepAdmin((RepAdmin) getSessionMap().get(RepAdmin.ADMIN));
           message.setReptime(replytime==null?new Date():replytime);
           messageService.updateNotNullField(message);
		return "listAction";
	}else{
		getRoot().push(message);
		return "reply";
	}
}
 
Example 3
Source File: ParamAction.java    From csustRepo with MIT License 6 votes vote down vote up
public String update() {
	
	RepParam param=new RepParam();
	
	try {
		BeanUtils.populate(param, getParameters());
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	param.setFormat(param.getFormat().trim().replace(" ", "").replace(",", ",").replace(":", ":"));
	paramService.update(param);
	paramService.updateStaticParams();

	getContextMap().put("message", "修改成功");
	getContextMap().put("returnUrl", "param_edit.do");
	
	return SUCCESS;
}
 
Example 4
Source File: MonitoringManager.java    From ankush with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Gets the object list.
 * 
 * @param <S>
 *            the generic type
 * @param targetClass
 *            the target class
 * @param infoList
 *            the info list
 * @return the object list
 * @throws InstantiationException
 *             the instantiation exception
 * @throws IllegalAccessException
 *             the illegal access exception
 * @throws InvocationTargetException
 *             the invocation target exception
 */
private <S> List<S> getObjectList(Class<S> targetClass,
		List<Map<String, Object>> infoList) throws InstantiationException,
		IllegalAccessException, InvocationTargetException {
	// Creating the resultant list object.
	List<S> result = new ArrayList<S>(infoList.size());

	// populating values in the list object from map.
	for (Map<String, Object> info : infoList) {
		// creating target class object.
		S status = targetClass.newInstance();
		// populating object with map values.
		BeanUtils.populate(status, info);
		// adding object in result list.
		result.add(status);
	}
	return result;
}
 
Example 5
Source File: SsoUserExtractor.java    From cola with MIT License 6 votes vote down vote up
@Override
public Object extractPrincipal(Map<String, Object> map) {
	Object authentication = map.get("userAuthentication");
	if (authentication == null) {
		throw new InvalidTokenException("userAuthentication is empty");
	}
	Object principal = ((Map<String, Object>) authentication).get("principal");
	AuthenticatedUser user = new AuthenticatedUser();
	if (principal == null) {
		throw new InvalidTokenException("principal is empty");
	}
	try {
		BeanUtils.populate(user, (Map<String, Object>) principal);
	} catch (Exception e) {
		throw new InvalidTokenException("populate user error: " + e.getMessage());
	}
	return user;
}
 
Example 6
Source File: FeignUtils.java    From parker with MIT License 6 votes vote down vote up
/**
 * 根据ID查询
 * @param client
 * @param id
 * @return
 */
public static User get(UserClient client, String id){
    User result = null;
    ResponseEntity<BaseResult> entity = client.get(id);
    Map<String, Object> map = (Map<String, Object>)entity.getBody().getData();
    if(HttpStatus.OK.value() == entity.getBody().getCode() && map != null){
        result = new User();
        try {
            // 转换时间
            // ConvertUtils.register(new DateConverter(null), java.util.Date.class);
            BeanUtils.populate(result, map);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return result;
}
 
Example 7
Source File: LogicalPlanConfiguration.java    From Bats with Apache License 2.0 5 votes vote down vote up
/**
 * Inject the configuration opProps into the operator instance.
 * @param operator
 * @param properties
 * @return Operator
 */
public static GenericOperator setOperatorProperties(GenericOperator operator, Map<String, String> properties)
{
  try {
    // populate custom opProps
    BeanUtils.populate(operator, properties);
    return operator;
  } catch (IllegalAccessException | InvocationTargetException e) {
    throw new IllegalArgumentException("Error setting operator properties", e);
  }
}
 
Example 8
Source File: CollectionUtils.java    From spring-boot with Apache License 2.0 5 votes vote down vote up
/**
 * map集合转对象
 */
public static Object map2Object(Map<String, Object> map, Class<?> beanClass)
        throws Exception {
    if (map == null)
        return null;
    Object obj = beanClass.newInstance();
    BeanUtils.populate(obj, map);
    return obj;
}
 
Example 9
Source File: CreateServiceInstanceRequest.java    From spring-boot-cf-service-broker with Apache License 2.0 5 votes vote down vote up
public <T> T getParameters(Class<T> cls) {
	try {
		T bean = cls.newInstance();
		BeanUtils.populate(bean, parameters);
		return bean;
	} catch (Exception e) {
		throw new IllegalArgumentException("Error mapping parameters to class of type " + cls.getName());
	}
}
 
Example 10
Source File: LogicalPlanConfiguration.java    From attic-apex-core with Apache License 2.0 5 votes vote down vote up
public static StreamingApplication setApplicationProperties(StreamingApplication application, Map<String, String> properties)
{
  try {
    BeanUtils.populate(application, properties);
    return application;
  } catch (IllegalAccessException | InvocationTargetException e) {
    throw new IllegalArgumentException("Error setting application properties", e);
  }
}
 
Example 11
Source File: DatabaseTableMeta.java    From canal-1.1.3 with Apache License 2.0 5 votes vote down vote up
private boolean applyHistoryToDB(EntryPosition position, String schema, String ddl, String extra) {
    Map<String, String> content = new HashMap<String, String>();
    content.put("destination", destination);
    content.put("binlogFile", position.getJournalName());
    content.put("binlogOffest", String.valueOf(position.getPosition()));
    content.put("binlogMasterId", String.valueOf(position.getServerId()));
    content.put("binlogTimestamp", String.valueOf(position.getTimestamp()));
    content.put("useSchema", schema);
    if (content.isEmpty()) {
        throw new RuntimeException("apply failed caused by content is empty in applyHistoryToDB");
    }
    // 待补充
    List<DdlResult> ddlResults = DruidDdlParser.parse(ddl, schema);
    if (ddlResults.size() > 0) {
        DdlResult ddlResult = ddlResults.get(0);
        content.put("sqlSchema", ddlResult.getSchemaName());
        content.put("sqlTable", ddlResult.getTableName());
        content.put("sqlType", ddlResult.getType().name());
        content.put("sqlText", ddl);
        content.put("extra", extra);
    }

    MetaHistoryDO metaDO = new MetaHistoryDO();
    try {
        BeanUtils.populate(metaDO, content);
        // 会建立唯一约束,解决:
        // 1. 重复的binlog file+offest
        // 2. 重复的masterId+timestamp
        metaHistoryDAO.insert(metaDO);
    } catch (Throwable e) {
        if (isUkDuplicateException(e)) {
            // 忽略掉重复的位点
            logger.warn("dup apply for sql : " + ddl);
        } else {
            throw new CanalParseException("apply history to db failed caused by : " + e.getMessage(), e);
        }

    }
    return true;
}
 
Example 12
Source File: AsksAction.java    From csustRepo with MIT License 5 votes vote down vote up
public String add(){
	if(getRequest().getMethod().equals("GET")){
		return "add";
	}
	Date now=new Date();
	
	RepMessage message=new RepMessage();
	message.setAddtime(releasetime==null?now:releasetime);
	message.setRepAdmin((RepAdmin) getSessionMap().get(RepAdmin.ADMIN));
	
	try {
		BeanUtils.populate(message, getParameters());
	} catch (Exception e) {
		e.printStackTrace();
	}
	
	message.setIsreplied(0);
       
	/*获取留言用户,这段不能用,但是可以用sessionMap来获取当前登录的admin,
	而且留言表和用户表/管理员表双向关联。
	按道理也不能为空,所以现在操作会报错。*/
	/*String us=getRequest().getParameter("userid");
	int userid=Integer.parseInt(us);
	RepAdmin admin=adminService.get(userid);
	message.setRepAdmin(admin);*/
	messageService.add(message);
	return "listAction";
}
 
Example 13
Source File: SQLMain.java    From primecloud-controller with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T, V> List<T> selectExecuteWithResult(String sql, Class<T> clazz) throws Exception {
    SQLExecuter sqlExecuter = new SQLExecuterFactory().createPCCSQLExecuter();
    List<Map<String, Object>> selectResults = sqlExecuter.showColumns(sql);
    List<T> results = new ArrayList<T>();
    Constructor<?>[] constructors = clazz.getConstructors();
    for (int i = 0; i < selectResults.size(); i++) {
        Map<String, Object> rowMap = selectResults.get(i);
        T newEntity = (T) constructors[0].newInstance();
        BeanUtils.populate(newEntity, rowMap);
        results.add(newEntity);
    }
    return results;
}
 
Example 14
Source File: StringCodec.java    From attic-apex-core with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings({"UseSpecificCatch", "BroadCatchBlock", "TooBroadCatch"})
public T fromString(String string)
{
  String[] parts = string.split(separator);

  try {
    @SuppressWarnings("unchecked")
    Class<? extends T> clazz = (Class<? extends T>)Thread.currentThread().getContextClassLoader().loadClass(parts[0]);
    if (parts.length == 1) {
      return clazz.newInstance();
    }

    //String[] properties = parts[1].split(separator, 2);
    if (parts.length == 2) {
      return clazz.getConstructor(String.class).newInstance(parts[1]);
    } else {
      T object = clazz.getConstructor(String.class).newInstance(parts[1]);
      HashMap<String, String> hashMap = new HashMap<>();
      for (int i = 2; i < parts.length; i++) {
        String[] keyValPair = parts[i].split(propertySeparator, 2);
        hashMap.put(keyValPair[0], keyValPair[1]);
      }
      BeanUtils.populate(object, hashMap);
      return object;
    }
  } catch (Throwable cause) {
    throw Throwables.propagate(cause);
  }
}
 
Example 15
Source File: SchemaToDataFetcher.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void addToResult( Schema schema, Map<String, Object> valuesMap, List<IdentifiableObject> resultsObjects )
{
    try
    {
        IdentifiableObject identifiableObject = (IdentifiableObject) schema.getKlass().newInstance();
        BeanUtils.populate( identifiableObject, valuesMap );
        resultsObjects.add( identifiableObject );
    }
    catch ( Exception e )
    {
        log.error( "Error during dynamic population of object type: " + schema.getKlass().getSimpleName(), e );
    }
}
 
Example 16
Source File: DatabaseTableMeta.java    From canal-1.1.3 with Apache License 2.0 4 votes vote down vote up
/**
 * 发布数据到console上
 */
private boolean applySnapshotToDB(EntryPosition position, boolean init) {
    // 获取一份快照
    Map<String, String> schemaDdls = null;
    lock.readLock().lock();
    try {
        if (!init && !hasNewDdl) {
            // 如果是持续构建,则识别一下是否有DDL变更过,如果没有就忽略了
            return false;
        }
        this.hasNewDdl = false;
        schemaDdls = memoryTableMeta.snapshot();
    } finally {
        lock.readLock().unlock();
    }

    MemoryTableMeta tmpMemoryTableMeta = new MemoryTableMeta();
    for (Map.Entry<String, String> entry : schemaDdls.entrySet()) {
        tmpMemoryTableMeta.apply(position, entry.getKey(), entry.getValue(), null);
    }

    // 基于临时内存对象进行对比
    boolean compareAll = true;
    for (Schema schema : tmpMemoryTableMeta.getRepository().getSchemas()) {
        for (String table : schema.showTables()) {
            String fullName = schema + "." + table;
            if (blackFilter == null || !blackFilter.filter(fullName)) {
                if (filter == null || filter.filter(fullName)) {
                    // issue : https://github.com/alibaba/canal/issues/1168
                    // 在生成snapshot时重新过滤一遍
                    if (!compareTableMetaDbAndMemory(connection, tmpMemoryTableMeta, schema.getName(), table)) {
                        compareAll = false;
                    }
                }
            }
        }
    }

    if (compareAll) {
        Map<String, String> content = new HashMap<String, String>();
        content.put("destination", destination);
        content.put("binlogFile", position.getJournalName());
        content.put("binlogOffest", String.valueOf(position.getPosition()));
        content.put("binlogMasterId", String.valueOf(position.getServerId()));
        content.put("binlogTimestamp", String.valueOf(position.getTimestamp()));
        content.put("data", JSON.toJSONString(schemaDdls));
        if (content.isEmpty()) {
            throw new RuntimeException("apply failed caused by content is empty in applySnapshotToDB");
        }

        MetaSnapshotDO snapshotDO = new MetaSnapshotDO();
        try {
            BeanUtils.populate(snapshotDO, content);
            metaSnapshotDAO.insert(snapshotDO);
        } catch (Throwable e) {
            if (isUkDuplicateException(e)) {
                // 忽略掉重复的位点
                logger.info("dup apply snapshot use position : " + position + " , just ignore");
            } else {
                throw new CanalParseException("apply failed caused by : " + e.getMessage(), e);
            }
        }
        return true;
    } else {
        logger.error("compare failed , check log");
    }
    return false;
}
 
Example 17
Source File: RoleAction.java    From csustRepo with MIT License 4 votes vote down vote up
public String add() {
	//查询可选的权限
	List<RepPermission> permissions=LogInterceptor.list;
	getContextMap().put("permissionlist", permissions);
	
	//根据参数对角色bean赋值
	RepRole role=new RepRole();
	try {
		BeanUtils.populate(role, getParameters());
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	role.setName(role.getName().trim());
	String[] permissionIdStrs=(String[])getParameters().get("permissionids");
	//判断是否存在同名角色
	RepRole r=roleService.findRoleByName(getRequest().getParameter("name").trim());
	if(r!=null){
		//将取出的权限id数组转换成list
		List<String> permissionids=Arrays.asList(permissionIdStrs);
		getContextMap().put("message", "已经存在同名用户,请换个用户名!");
		getContextMap().put("selectpermissionlist", permissionids);
		getRoot().push(role);
		return "add";
	}
	//对角色bean的权限set赋值
	if(permissionIdStrs!=null&&permissionIdStrs.length>0){
		for (String id : permissionIdStrs) {
			RepPermission p=new RepPermission();
			p.setId(Integer.parseInt(id));
			role.getRepPermissions().add(p);
		}
	}else {
		getContextMap().put("permissionsmessage", "请至少选择一个权限!");
		getRoot().push(role);
		return "add";
	}
	
	roleService.add(role);
	getContextMap().put("message", "新增成功");
	getContextMap().put("returnUrl", "role_list.do");
	
	return SUCCESS;
}
 
Example 18
Source File: ConfigsTest.java    From haven-platform with Apache License 2.0 4 votes vote down vote up
@Test
public void testMap() throws InvocationTargetException, IllegalAccessException {
    ContainerSource createContainerArg = new ContainerSource();

    BeanUtils.populate(createContainerArg, Collections.singletonMap("cpuShares", "23"));

    createContainerArg.getCpuShares();
    Assert.assertNotNull(createContainerArg.getCpuShares());

    ContainerSource createContainerArg2 = new ContainerSource();
    BeanUtils.populate(createContainerArg2, Collections.singletonMap("blkioWeight", "15"));

    BeanUtils.copyProperties(createContainerArg, createContainerArg2);

    Assert.assertNotNull(createContainerArg.getBlkioWeight());

}
 
Example 19
Source File: ProxyInvocation.java    From redant with Apache License 2.0 4 votes vote down vote up
/**
 * 获得方法调用的参数
 * @param method 方法
 * @param parameterTypes 方法参数类型
 * @return 参数
 * @throws Exception 参数异常
 */
private Object[] getParameters(Method method,Class<?>[] parameterTypes) throws Exception {
	//用于存放调用参数的对象数组
	Object[] parameters = new Object[parameterTypes.length];

	//获得所调用方法的参数的Annotation数组
	Annotation[][] annotationArray = method.getParameterAnnotations();

	//获取参数列表
	Map<String, List<String>> paramMap = HttpRequestUtil.getParameterMap(RedantContext.currentContext().getRequest());

	//构造调用所需要的参数数组
	for (int i = 0; i < parameterTypes.length; i++) {
		Object parameter;
		Class<?> type = parameterTypes[i];
		Annotation[] annotation = annotationArray[i];
		// 如果该参数没有 Param 注解
		if (annotation == null || annotation.length == 0) {
			// 如果该参数类型是基础类型,则需要加 Param 注解
			if(PrimitiveTypeUtil.isPriType(type)){
				logger.warn("Must specify a @Param annotation for primitive type parameter in method={}", method.getName());
				continue;
			}
			// 封装对象类型的parameter
			parameter = type.newInstance();
			BeanUtils.populate(parameter,paramMap);
			parameters[i] = parameter;
		}else{
			Param param = (Param) annotation[0];
			try{
				// 生成当前的调用参数
				parameter = parseParameter(paramMap, type, param, method, i);
				if(param.notNull()){
					GenericsUtil.checkNull(param.key(), parameter);
				}
				if(param.notBlank()){
					GenericsUtil.checkBlank(param.key(), parameter);
				}
				parameters[i] = parameter;
			}catch(Exception e){
			    logger.error("param ["+param.key()+"] is invalid,cause:"+e.getMessage());
				throw new IllegalArgumentException("参数 "+param.key()+" 不合法:"+e.getMessage());
			}
		}
	}
	return parameters;
}
 
Example 20
Source File: XmlMapper.java    From sakai with Educational Community License v2.0 3 votes vote down vote up
/**
 * Maps each element node to a bean property.
 * Supports only simple types such as String, int and long, plus Lists.
 *
 * If node is a document it processes it as if it were the root node.
 *
 * If there are multiple nodes with the same element name they will be stored
 * in a List.
 *
 * NOTE:
 * This is DESIGNED to ignore elements at more depth so that simple
 * String key value pairs are used.  This WILL NOT recurse to more depth,
 * by design.  If it did so, you would have to use maps of maps.
 *
 * @param bean Serializable object which has the appropriate setters/getters
 * @param doc the document
 */
static public void populateBeanFromDoc(Serializable bean, Document doc)
{
  try
  {
    Map m = map(doc);
    BeanUtils.populate(bean, m);
  }
  catch(Exception e)
  {
    log.error(e.getMessage(), e);
    throw new RuntimeException(e);
  }
}