cn.hutool.core.bean.BeanUtil Java Examples

The following examples show how to use cn.hutool.core.bean.BeanUtil. 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: DictService.java    From Guns with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 查询字典列表,通过字典类型code
 *
 * @author fengshuonan
 * @Date 2019-06-20 15:14
 */
public List<Map<String, Object>> getDictsByCodes(List<String> dictCodes) {

    QueryWrapper<Dict> wrapper = new QueryWrapper<>();
    wrapper.in("code", dictCodes).orderByAsc("sort");

    ArrayList<Map<String, Object>> results = new ArrayList<>();

    //转成map
    List<Dict> list = this.list(wrapper);
    for (Dict dict : list) {
        Map<String, Object> map = BeanUtil.beanToMap(dict);
        results.add(map);
    }

    return results;
}
 
Example #2
Source File: RestDictService.java    From Guns with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 查询字典列表,通过字典类型code
 *
 * @author fengshuonan
 * @Date 2019-06-20 15:14
 */
public List<Map<String, Object>> getDictsByCodes(List<String> dictCodes) {

    QueryWrapper<RestDict> wrapper = new QueryWrapper<>();
    wrapper.in("code", dictCodes).orderByAsc("sort");

    ArrayList<Map<String, Object>> results = new ArrayList<>();

    //转成map
    List<RestDict> list = this.list(wrapper);
    for (RestDict dict : list) {
        Map<String, Object> map = BeanUtil.beanToMap(dict);
        results.add(map);
    }

    return results;
}
 
Example #3
Source File: CollUtil.java    From albedo with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 提取集合中的对象的一个属性(通过Getter函数), 组合成List.
 *
 * @param collection   来源集合.
 * @param propertyName 要提取的属性名.
 */
@SuppressWarnings("unchecked")
public static List extractToList(final Collection collection, final String propertyName) {
	List list = Lists.newArrayList();
	try {
		if (collection != null) {
			Object item = null;
			for (Object obj : collection) {
				if (obj instanceof Map) {
					item = ((Map) obj).get(propertyName);
				} else {
					item = BeanUtil.getFieldValue(obj, propertyName);
				}
				if (item != null) {
					list.add(item);
				}
			}
		}
	} catch (Exception e) {
		throw e;
	}

	return list;
}
 
Example #4
Source File: MockUrlServiceImpl.java    From v-mock with MIT License 6 votes vote down vote up
/**
 * 根据逻辑创建正则查url
 *
 * @param requestUrlLogic logic string
 * @return mockUrl entity
 */
@SneakyThrows
@Override
public MockUrl getUrlByRegexp(String requestUrlLogic) {
    if (StrUtil.isNotBlank(requestUrlLogic)) {
        // 注册一个带正则的Connection
        @Cleanup Connection connection = DriverManager.getConnection(dbPath);
        DataBaseUtils.createRegexpFun(connection);
        // sql gen
        // "12,13,14" => ["12","13","14"]
        String[] afterSplit = requestUrlLogic.split(COMMA);
        StringJoiner regexpJoiner = new StringJoiner(StrUtil.COMMA);
        // 将数组遍历 拼接 为正则
        Arrays.stream(afterSplit).forEach(item ->
                // path 直接拼接,数字logic 加上或逻辑拼接
                regexpJoiner.add(CommonConst.PATH_PLACEHOLDER.equals(item) ? SQL_REGEXP_PATH : StrUtil.format(SQL_REGEXP_FORMAT, item)));
        String regexp = "'^".concat(regexpJoiner.toString()).concat("$'");
        // 查询
        Map<String, Object> mockUrlMap = DataBaseUtils.queryMap(connection, StrUtil.format(SQL_REGEXP, regexp));
        if (mockUrlMap != null) {
            // 转为实体
            return BeanUtil.mapToBean(mockUrlMap, MockUrl.class, true);
        }
    }
    return null;
}
 
Example #5
Source File: NacosDynRouteLocator.java    From microservices-platform with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, ZuulProperties.ZuulRoute> loadDynamicRoute() {
    Map<String, ZuulRoute> routes = new LinkedHashMap<>();
    if (zuulRouteEntities == null) {
        zuulRouteEntities = getNacosConfig();
    }
    for (ZuulRouteEntity result : zuulRouteEntities) {
        if (StrUtil.isBlank(result.getPath()) || !result.isEnabled()) {
            continue;
        }
        ZuulRoute zuulRoute = new ZuulRoute();
        BeanUtil.copyProperties(result, zuulRoute);
        routes.put(zuulRoute.getPath(), zuulRoute);
    }
    return routes;
}
 
Example #6
Source File: RoleController.java    From Guns with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 查看角色
 *
 * @author fengshuonan
 * @Date 2018/12/23 6:31 PM
 */
@RequestMapping(value = "/view/{roleId}")
@ResponseBody
public ResponseData view(@PathVariable Long roleId) {
    if (ToolUtil.isEmpty(roleId)) {
        throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
    }
    Role role = this.roleService.getById(roleId);
    Map<String, Object> roleMap = BeanUtil.beanToMap(role);

    Long pid = role.getPid();
    String pName = ConstantFactory.me().getSingleRoleName(pid);
    roleMap.put("pName", pName);

    return ResponseData.success(roleMap);
}
 
Example #7
Source File: SysUserController.java    From microservices-platform with Apache License 2.0 6 votes vote down vote up
@PostMapping(value = "/users/import")
public Result importExcl(@RequestParam("file") MultipartFile excl) throws Exception {
    int rowNum = 0;
    if(!excl.isEmpty()) {
        List<SysUserExcel> list = ExcelUtil.importExcel(excl, 0, 1, SysUserExcel.class);
        rowNum = list.size();
        if (rowNum > 0) {
            List<SysUser> users = new ArrayList<>(rowNum);
            list.forEach(u -> {
                SysUser user = new SysUser();
                BeanUtil.copyProperties(u, user);
                user.setPassword(CommonConstant.DEF_USER_PASSWORD);
                user.setType(UserType.BACKEND.name());
                users.add(user);
            });
            appUserService.saveBatch(users);
        }
    }
    return Result.succeed("导入数据成功,一共【"+rowNum+"】行");
}
 
Example #8
Source File: BaseDbLogService.java    From Jpom with MIT License 6 votes vote down vote up
/**
 * 根据主键查询实体
 *
 * @param keyValue 主键值
 * @return 数据
 */
public T getByKey(String keyValue) {
    Entity where = new Entity(tableName);
    where.set(key, keyValue);
    Db db = Db.use();
    db.setWrapper((Character) null);
    Entity entity;
    try {
        entity = db.get(where);
    } catch (SQLException e) {
        throw new JpomRuntimeException("数据库异常", e);
    }
    if (entity == null) {
        return null;
    }
    CopyOptions copyOptions = new CopyOptions();
    copyOptions.setIgnoreError(true);
    copyOptions.setIgnoreCase(true);
    return BeanUtil.mapToBean(entity, this.tClass, copyOptions);
}
 
Example #9
Source File: HutoolController.java    From mall-learning with Apache License 2.0 6 votes vote down vote up
@ApiOperation("BeanUtil使用:JavaBean的工具类")
@GetMapping("/beanUtil")
public CommonResult beanUtil() {
    PmsBrand brand = new PmsBrand();
    brand.setId(1L);
    brand.setName("小米");
    brand.setShowStatus(0);
    //Bean转Map
    Map<String, Object> map = BeanUtil.beanToMap(brand);
    LOGGER.info("beanUtil bean to map:{}", map);
    //Map转Bean
    PmsBrand mapBrand = BeanUtil.mapToBean(map, PmsBrand.class, false);
    LOGGER.info("beanUtil map to bean:{}", mapBrand);
    //Bean属性拷贝
    PmsBrand copyBrand = new PmsBrand();
    BeanUtil.copyProperties(brand, copyBrand);
    LOGGER.info("beanUtil copy properties:{}", copyBrand);
    return CommonResult.success(null, "操作成功");
}
 
Example #10
Source File: IndexController.java    From pre with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 保存完信息然后跳转到绑定用户信息页面
 *
 * @param request
 * @param response
 * @throws IOException
 */
@GetMapping("/socialSignUp")
public void socialSignUp(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String uuid = UUID.randomUUID().toString();
    SocialUserInfo userInfo = new SocialUserInfo();
    Connection<?> connectionFromSession = providerSignInUtils.getConnectionFromSession(new ServletWebRequest(request));
    userInfo.setHeadImg(connectionFromSession.getImageUrl());
    userInfo.setNickname(connectionFromSession.getDisplayName());
    userInfo.setProviderId(connectionFromSession.getKey().getProviderId());
    userInfo.setProviderUserId(connectionFromSession.getKey().getProviderUserId());
    ConnectionData data = connectionFromSession.createData();
    PreConnectionData preConnectionData = new PreConnectionData();
    BeanUtil.copyProperties(data, preConnectionData);
    socialRedisHelper.saveConnectionData(uuid, preConnectionData);
    // 跳转到用户绑定页面
    response.sendRedirect(url + "/bind?key=" + uuid);
}
 
Example #11
Source File: StationServiceImpl.java    From zuihou-admin-cloud with Apache License 2.0 6 votes vote down vote up
@Override
// 启用属性自动注入
@InjectionResult
public IPage<Station> findStationPage(IPage page, StationPageDTO data) {
    Station station = BeanUtil.toBean(data, Station.class);

    //Wraps.lbQ(station); 这种写法值 不能和  ${ew.customSqlSegment} 一起使用
    LbqWrapper<Station> wrapper = Wraps.lbQ();

    // ${ew.customSqlSegment} 语法一定要手动eq like 等
    wrapper.like(Station::getName, station.getName())
            .like(Station::getDescribe, station.getDescribe())
            .eq(Station::getOrg, station.getOrg())
            .eq(Station::getStatus, station.getStatus())
            .geHeader(Station::getCreateTime, data.getStartCreateTime())
            .leFooter(Station::getCreateTime, data.getEndCreateTime());
    return baseMapper.findStationPage(page, wrapper, new DataScope());
}
 
Example #12
Source File: RestRoleController.java    From Guns with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 查看角色
 *
 * @author fengshuonan
 * @Date 2018/12/23 6:31 PM
 */
@RequestMapping(value = "/view/{roleId}")
public ResponseData view(@PathVariable Long roleId) {
    if (ToolUtil.isEmpty(roleId)) {
        throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
    }
    RestRole role = this.restRoleService.getById(roleId);
    Map<String, Object> roleMap = BeanUtil.beanToMap(role);

    Long pid = role.getPid();
    String pName = ConstantFactory.me().getSingleRoleName(pid);
    roleMap.put("pName", pName);

    //获取角色绑定的菜单
    List<Long> menuIds = this.restMenuService.getMenuIdsByRoleId(roleId);
    List<String> menuNames = this.restMenuService.getBaseMapper().getMenuNamesByRoleId(roleId);
    if (ToolUtil.isNotEmpty(menuIds)) {
        roleMap.put("menuIds", menuIds);
        roleMap.put("menuNames", menuNames);
    } else {
        roleMap.put("menuIds", new ArrayList<>());
        roleMap.put("menuNames", new ArrayList<>());
    }

    return ResponseData.success(roleMap);
}
 
Example #13
Source File: BaseDao.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 根据对象查询
 *
 * @param t 查询条件
 * @return 对象列表
 */
public List<T> findByExample(T t) {
	String tableName = getTableName(t);
	List<Field> filterField = getField(t, true);
	List<String> columnList = getColumns(filterField);

	List<String> columns = columnList.stream().map(s -> " and " + s + " = ? ").collect(Collectors.toList());

	String where = StrUtil.join(" ", columns);
	// 构造值
	Object[] values = filterField.stream().map(field -> ReflectUtil.getFieldValue(t, field)).toArray();

	String sql = StrUtil.format("SELECT * FROM {table} where 1=1 {where}", Dict.create().set("table", tableName).set("where", StrUtil.isBlank(where) ? "" : where));
	log.debug("【执行SQL】SQL:{}", sql);
	log.debug("【执行SQL】参数:{}", JSONUtil.toJsonStr(values));
	List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql, values);
	List<T> ret = CollUtil.newArrayList();
	maps.forEach(map -> ret.add(BeanUtil.fillBeanWithMap(map, ReflectUtil.newInstance(clazz), true, false)));
	return ret;
}
 
Example #14
Source File: NoBootTest.java    From zuihou-admin-boot with Apache License 2.0 6 votes vote down vote up
@Test
public void testBeanUtil() {

    //10000 - 511
    //50000 - 719
    //100000 - 812
    //1000000 - 2303

    TimeInterval timer = DateUtil.timer();
    for (int i = 0; i <= 1000000; i++) {
        Org org = Org.builder()
                .label("string")
                .id(123L + i)
                .createTime(LocalDateTime.now())
                .build();
        Station station = Station.builder().id(1L + i).name("nihaoa").createTime(LocalDateTime.now()).orgId(new RemoteData(12L, org)).build();

        StationPageDTO stationPageDTO = new StationPageDTO();

        BeanUtil.copyProperties(station, stationPageDTO);
    }

    long interval = timer.interval();// 花费毫秒数
    long intervalMinute = timer.intervalMinute();// 花费分钟数
    StaticLog.info("本次程序执行 花费毫秒数: {} ,   花费分钟数:{} . ", interval, intervalMinute);
}
 
Example #15
Source File: UserController.java    From kvf-admin with MIT License 6 votes vote down vote up
@GetMapping(value = "edit")
public ModelAndView edit(Long id) {
    ModelAndView mv = new ModelAndView("sys/user_edit");
    UserEditDTO userEditDTO = new UserEditDTO();
    UserRoleGroupDTO userRoleGroupDTO = new UserRoleGroupDTO();
    if (id != null) {
        User user = userService.getById(id);
        Dept dept = deptService.getById(user.getDeptId());
        userRoleGroupDTO = userRoleService.getUserRoleGroupDTOByUserId(id);
        BeanUtil.copyProperties(user, userEditDTO);
        userEditDTO.setDeptName(dept == null ? "" : dept.getName());
    }
    userEditDTO.setUserRole(userRoleGroupDTO);
    mv.addObject("editInfo", userEditDTO);
    return mv;
}
 
Example #16
Source File: RbacLoginService.java    From Aooms with Apache License 2.0 6 votes vote down vote up
@Transactional(readOnly = true)
   public AuthenticationInfo login(String username, String password) {
       Record record = db.findObject(RbacMapper.PKG.by("UserMapper.findByAccount"),SqlPara.fromDataBoss());
       if(record == null){
           return null;
       }

       String storePassword = record.getString("password");
       if(!PasswordHash.validatePassword(password,storePassword)){
           return null;
       }

       AuthenticationInfo authenticationInfo = new AuthenticationInfo();
       BeanUtil.fillBeanWithMap(record, authenticationInfo, true, true);
       return authenticationInfo;
}
 
Example #17
Source File: BaseDao.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 根据对象查询
 *
 * @param t 查询条件
 * @return 对象列表
 */
public List<T> findByExample(T t) {
	String tableName = getTableName(t);
	List<Field> filterField = getField(t, true);
	List<String> columnList = getColumns(filterField);

	List<String> columns = columnList.stream().map(s -> " and " + s + " = ? ").collect(Collectors.toList());

	String where = StrUtil.join(" ", columns);
	// 构造值
	Object[] values = filterField.stream().map(field -> ReflectUtil.getFieldValue(t, field)).toArray();

	String sql = StrUtil.format("SELECT * FROM {table} where 1=1 {where}", Dict.create().set("table", tableName).set("where", StrUtil.isBlank(where) ? "" : where));
	log.debug("【执行SQL】SQL:{}", sql);
	log.debug("【执行SQL】参数:{}", JSONUtil.toJsonStr(values));
	List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql, values);
	List<T> ret = CollUtil.newArrayList();
	maps.forEach(map -> ret.add(BeanUtil.fillBeanWithMap(map, ReflectUtil.newInstance(clazz), true, false)));
	return ret;
}
 
Example #18
Source File: MenuController.java    From Guns with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 获取菜单信息
 *
 * @author fengshuonan
 * @Date 2018/12/23 5:53 PM
 */
@RequestMapping(value = "/getMenuInfo")
@ResponseBody
public ResponseData getMenuInfo(@RequestParam Long menuId) {
    if (ToolUtil.isEmpty(menuId)) {
        throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
    }

    Menu menu = this.menuService.getById(menuId);

    MenuDto menuDto = new MenuDto();
    BeanUtil.copyProperties(menu, menuDto);

    //设置pid和父级名称
    menuDto.setPid(ConstantFactory.me().getMenuIdByCode(menuDto.getPcode()));
    menuDto.setPcodeName(ConstantFactory.me().getMenuNameByCode(menuDto.getPcode()));

    return ResponseData.success(menuDto);
}
 
Example #19
Source File: AoomsRestTemplate.java    From Aooms with Apache License 2.0 6 votes vote down vote up
public DataResult get(String url, Map<String, Object> params) {
    DataResult dataResult = new DataResult();
    Map map = null;
    if(useRegistry()){
        map = loadBalancedRestTemplate.getForObject(url,Map.class);
    }else{
        String serverUrl = getLocalServerUrl(url);
        if(logger.isInfoEnabled()){
            logger.info("Convert " + url + " -> " + serverUrl);
        }
        map = restTemplate.getForObject(serverUrl,Map.class,params);
    }

    Map mapStatus = (Map) map.get(AoomsVar.RS_META);
    DataResultStatus status = BeanUtil.mapToBean(mapStatus,DataResultStatus.class,true);
    map.put(AoomsVar.RS_META,status);
    dataResult.setData(map);
    return dataResult;
}
 
Example #20
Source File: RestMenuController.java    From Guns with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 获取菜单信息
 *
 * @author fengshuonan
 * @Date 2018/12/23 5:53 PM
 */
@RequestMapping(value = "/getMenuInfo")
public ResponseData getMenuInfo(@RequestParam Long menuId) {
    if (ToolUtil.isEmpty(menuId)) {
        throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
    }

    RestMenu menu = this.restMenuService.getById(menuId);

    MenuDto menuDto = new MenuDto();
    BeanUtil.copyProperties(menu, menuDto);

    //设置pid和父级名称
    menuDto.setPid(ConstantFactory.me().getMenuIdByCode(menuDto.getPcode()));
    menuDto.setPcodeName(ConstantFactory.me().getMenuNameByCode(menuDto.getPcode()));

    return ResponseData.success(menuDto);
}
 
Example #21
Source File: SystemController.java    From Guns with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 跳转到查看用户详情页面
 *
 * @author fengshuonan
 * @Date 2018/12/24 22:43
 */
@RequestMapping("/user_info")
public String userInfo(Model model) {
    Long userId = LoginContextHolder.getContext().getUserId();
    User user = this.userService.getById(userId);

    model.addAllAttributes(BeanUtil.beanToMap(user));
    model.addAttribute("roleName", ConstantFactory.me().getRoleName(user.getRoleId()));
    model.addAttribute("deptName", ConstantFactory.me().getDeptName(user.getDeptId()));
    model.addAttribute("avatar", DefaultImages.defaultAvatarUrl());
    LogObjectHolder.me().set(user);

    return "/modular/frame/user_info.html";
}
 
Example #22
Source File: SpringBootDemoMultiDatasourceJpaApplicationTests.java    From spring-boot-demo with MIT License 5 votes vote down vote up
@Test
public void testInsert() {
    PrimaryMultiTable primary = new PrimaryMultiTable(snowflake.nextId(),"测试名称-1");
    primaryRepo.save(primary);

    SecondMultiTable second = new SecondMultiTable();
    BeanUtil.copyProperties(primary, second);
    secondRepo.save(second);
}
 
Example #23
Source File: SysDictServiceImpl.java    From pre with GNU General Public License v3.0 5 votes vote down vote up
@Transactional(rollbackFor = Exception.class)
@Override
public boolean updateDict(DictDTO dictDto) {
    SysDict sysDict = new SysDict();
    BeanUtil.copyProperties(dictDto, sysDict);
    return updateById(sysDict);
}
 
Example #24
Source File: DbBuildHistoryLogService.java    From Jpom with MIT License 5 votes vote down vote up
private void doClearPage(int pageNo, long time, String buildDataId) {
    Entity entity = Entity.create(getTableName());
    entity.set("startTime", "< " + time);
    if (buildDataId != null) {
        entity.set("buildDataId", buildDataId);
    }
    Page page = new Page(pageNo, 10);
    page.addOrder(new Order("startTime", Direction.DESC));
    PageResult<Entity> pageResult;
    try {
        pageResult = Db.use().setWrapper((Character) null).page(entity, page);
        if (pageResult.isEmpty()) {
            return;
        }
        pageResult.forEach(entity1 -> {
            CopyOptions copyOptions = new CopyOptions();
            copyOptions.setIgnoreError(true);
            copyOptions.setIgnoreCase(true);
            BuildHistoryLog v1 = BeanUtil.mapToBean(entity1, BuildHistoryLog.class, copyOptions);
            String id = v1.getId();
            JsonMessage<String> jsonMessage = deleteLogAndFile(id);
            if (jsonMessage.getCode() != HttpStatus.HTTP_OK) {
                DefaultSystemLog.getLog().info(jsonMessage.toString());
            }
        });
        if (pageResult.getTotalPage() > pageResult.getPage()) {
            doClearPage(pageNo + 1, time, buildDataId);
        }
    } catch (SQLException e) {
        DefaultSystemLog.getLog().error("数据库查询异常", e);
    }
}
 
Example #25
Source File: OnlineUser.java    From spring-boot-demo with MIT License 5 votes vote down vote up
public static OnlineUser create(User user) {
    OnlineUser onlineUser = new OnlineUser();
    BeanUtil.copyProperties(user, onlineUser);
    // 脱敏
    onlineUser.setPhone(StrUtil.hide(user.getPhone(), 3, 7));
    onlineUser.setEmail(StrUtil.hide(user.getEmail(), 1, StrUtil.indexOfIgnoreCase(user.getEmail(), Consts.SYMBOL_EMAIL)));
    return onlineUser;
}
 
Example #26
Source File: SpringBootDemoMultiDatasourceJpaApplicationTests.java    From spring-boot-demo with MIT License 5 votes vote down vote up
@Test
public void testUpdate() {
    primaryRepo.findAll().forEach(primary -> {
        primary.setName("修改后的"+primary.getName());
        primaryRepo.save(primary);

        SecondMultiTable second = new SecondMultiTable();
        BeanUtil.copyProperties(primary, second);
        secondRepo.save(second);
    });
}
 
Example #27
Source File: PrepareMsgQueue.java    From md_blockchain with Apache License 2.0 5 votes vote down vote up
/**
 * 收到节点(包括自己)针对某Block的Prepare消息
 *
 * @param voteMsg
 *         voteMsg
 */
@Override
protected void deal(VoteMsg voteMsg, List<VoteMsg> voteMsgs) {
    String hash = voteMsg.getHash();
    //如果我已经对该hash的commit投过票了,就不再继续
    if (voteStateConcurrentHashMap.get(hash) != null) {
        return;
    }

    VoteMsg commitMsg = new VoteMsg();
    BeanUtil.copyProperties(voteMsg, commitMsg);
    commitMsg.setVoteType(VoteType.COMMIT);
    commitMsg.setAppId(AppId.value);
    //开始校验并决定是否进入commit阶段
    //校验该vote是否合法
    if (commitMsgQueue.hasOtherConfirm(hash, voteMsg.getNumber())) {
         agree(commitMsg, false);
    } else {
        //开始校验拜占庭数量,如果agree的超过2f + 1,就commit
        long agreeCount = voteMsgs.stream().filter(VoteMsg::isAgree).count();
        long unAgreeCount = voteMsgs.size() - agreeCount;

        //开始发出commit的同意or拒绝的消息
        if (agreeCount >= pbftAgreeSize()) {
            agree(commitMsg, true);
        } else if (unAgreeCount >= pbftSize() + 1) {
            agree(commitMsg, false);
        }
    }

}
 
Example #28
Source File: OnlineUser.java    From spring-boot-demo with MIT License 5 votes vote down vote up
public static OnlineUser create(User user) {
    OnlineUser onlineUser = new OnlineUser();
    BeanUtil.copyProperties(user, onlineUser);
    // 脱敏
    onlineUser.setPhone(StrUtil.hide(user.getPhone(), 3, 7));
    onlineUser.setEmail(StrUtil.hide(user.getEmail(), 1, StrUtil.indexOfIgnoreCase(user.getEmail(), Consts.SYMBOL_EMAIL)));
    return onlineUser;
}
 
Example #29
Source File: PersonServiceImpl.java    From spring-boot-demo with MIT License 5 votes vote down vote up
@Override
public List<Person> searchList(String index) {
    SearchResponse searchResponse = search(index);
    SearchHit[] hits = searchResponse.getHits().getHits();
    List<Person> personList = new ArrayList<>();
    Arrays.stream(hits).forEach(hit -> {
        Map<String, Object> sourceAsMap = hit.getSourceAsMap();
        Person person = BeanUtil.mapToBean(sourceAsMap, Person.class, true);
        personList.add(person);
    });
    return personList;
}
 
Example #30
Source File: BeanConvertTest.java    From javatech with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
@Test
public void convertTest() {
    Person person = new Person();
    person.setName("Jack").setAge(20).setSex(Sex.MALE);
    // Bean 转换
    User user = BeanUtil.toBean(person, User.class);
    Assertions.assertEquals(person.getName(), user.getName());
    Assertions.assertEquals(person.getAge(), user.getAge());
    Assertions.assertEquals(person.getSex().name(), user.getSex());
}