cn.hutool.core.util.ObjectUtil Java Examples

The following examples show how to use cn.hutool.core.util.ObjectUtil. 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: SysUserServiceImpl.java    From pre with GNU General Public License v3.0 6 votes vote down vote up
@Transactional(rollbackFor = Exception.class)
@Override
public boolean register(UserDTO userDTO) {
    // 查询用户名是否存在
    SysUser byUserInfoName = findSecurityUser(userDTO.getUsername());
    if (ObjectUtil.isNotNull(byUserInfoName)) {
        throw new PreBaseException("账户名已被注册");
    }
    SysUser securityUser = findSecurityUser(userDTO.getPhone());
    if (ObjectUtil.isNotNull(securityUser)) {
        throw new PreBaseException("手机号已被注册");
    }
    userDTO.setDeptId(6);
    userDTO.setLockFlag("0");
    SysUser sysUser = new SysUser();
    // 对象拷贝
    BeanUtil.copyProperties(userDTO, sysUser);
    // 加密后的密码
    sysUser.setPassword(PreUtil.encode(userDTO.getPassword()));
    baseMapper.insertUser(sysUser);
    SysUserRole sysUserRole = new SysUserRole();
    sysUserRole.setRoleId(14);
    sysUserRole.setUserId(sysUser.getUserId());
    return userRoleService.save(sysUserRole);
}
 
Example #2
Source File: WechatReplyController.java    From yshopmall with Apache License 2.0 6 votes vote down vote up
@ApiOperation(value = "新增自动回复")
@PostMapping(value = "/yxWechatReply")
@PreAuthorize("@el.check('admin','YXWECHATREPLY_ALL','YXWECHATREPLY_CREATE')")
public ResponseEntity create(@RequestBody String jsonStr){

    JSONObject jsonObject = JSON.parseObject(jsonStr);
    YxWechatReply yxWechatReply = new YxWechatReply();
    YxWechatReply isExist = yxWechatReplyService.isExist(jsonObject.get("key").toString());
    yxWechatReply.setKey(jsonObject.get("key").toString());
    yxWechatReply.setStatus(Integer.valueOf(jsonObject.get("status").toString()));
    yxWechatReply.setData(jsonObject.get("data").toString());
    yxWechatReply.setType(jsonObject.get("type").toString());
    if(ObjectUtil.isNull(isExist)){
        yxWechatReplyService.create(yxWechatReply);
    }else{
        yxWechatReply.setId(isExist.getId());
        yxWechatReplyService.upDate(yxWechatReply);
    }

    return new ResponseEntity(HttpStatus.CREATED);
}
 
Example #3
Source File: LogServiceImpl.java    From sk-admin with Apache License 2.0 6 votes vote down vote up
@Override
public void download(List<Log> logs, HttpServletResponse response) throws IOException {
    List<Map<String, Object>> list = new ArrayList<>();
    for (Log log : logs) {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("用户名", log.getUsername());
        map.put("IP", log.getRequestIp());
        map.put("IP来源", log.getAddress());
        map.put("描述", log.getDescription());
        map.put("浏览器", log.getBrowser());
        map.put("请求耗时/毫秒", log.getTime());
        map.put("异常详情", new String(ObjectUtil.isNotNull(log.getExceptionDetail()) ? log.getExceptionDetail() : "".getBytes()));
        map.put("创建日期", log.getCreateTime());
        list.add(map);
    }
    FileUtils.downloadExcel(list, response);
}
 
Example #4
Source File: SysDeptServiceImpl.java    From RuoYi with Apache License 2.0 6 votes vote down vote up
/**
 * 修改保存部门信息
 *
 * @param dept 部门信息
 * @return 结果
 */
@Override
public int updateDept(SysDept dept) {
    SysDept newParentDept = deptMapper.selectDeptById(dept.getParentId());
    SysDept oldDept = selectDeptById(dept.getDeptId());
    if (ObjectUtil.isNotNull(newParentDept) && ObjectUtil.isNotNull(oldDept)) {
        String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getDeptId();
        String oldAncestors = oldDept.getAncestors();
        dept.setAncestors(newAncestors);
        updateDeptChildren(dept.getDeptId(), newAncestors, oldAncestors);
    }
    int result = deptMapper.updateDept(dept);
    if(UserConstants.DEPT_NORMAL.equals(dept.getStatus())){
        //如果该部门是启用状态,这启用该部门的所有上级部门
        updateParentDeptStatus(dept);
    }
    return result;
}
 
Example #5
Source File: LogoutFilter.java    From RuoYi with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean preHandle(ServletRequest request, ServletResponse response){
    try {
        Subject subject = getSubject(request, response);
        String redirectUrl = getRedirectUrl(request, response, subject);
        SysUser user = ShiroUtils.getSysUser();
        if (ObjectUtil.isNotNull(user)) {
            String loginName = user.getLoginName();
            // 记录用户退出日志
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginName, Constants.LOGOUT, MessageUtils.message("user.logout.success")));
            // 清理缓存
            cache.remove(loginName);
        }
        // 退出登录
        subject.logout();
        issueRedirect(request, response, redirectUrl);
    } catch (Exception e) {
        log.error("Encountered session exception during logout.  This can generally safely be ignored." , e);
    }
    return false;
}
 
Example #6
Source File: SysUserController.java    From pre with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 修改密码
 *
 * @return
 */
@SysOperaLog(descrption = "修改邮箱")
@PutMapping("updateEmail")
@PreAuthorize("hasAuthority('sys:user:updateEmail')")
public R updateEmail(@RequestParam String mail, @RequestParam String code, @RequestParam String pass, HttpServletRequest request) {
    // 校验验证码流程
    String ccode = (String) request.getSession().getAttribute(PreConstant.RESET_MAIL);
    if (ObjectUtil.isNull(ccode)) {
        throw new PreBaseException("验证码已过期");
    }
    if (!StrUtil.equals(code.toLowerCase(), ccode)) {
        throw new PreBaseException("验证码错误");
    }
    // 校验密码流程
    SysUser sysUser = userService.findSecurityUserByUser(new SysUser().setUsername(SecurityUtil.getUser().getUsername()));
    if (!PreUtil.validatePass(pass, sysUser.getPassword())) {
        throw new PreBaseException("密码错误");
    }
    // 修改邮箱流程
    SysUser user = new SysUser();
    user.setUserId(sysUser.getUserId());
    user.setEmail(mail);
    return R.ok(userService.updateUserInfo(user));
}
 
Example #7
Source File: LogServiceImpl.java    From yshopmall with Apache License 2.0 6 votes vote down vote up
@Override
public void download(List<co.yixiang.logging.domain.Log> logs, HttpServletResponse response) throws IOException {
    List<Map<String, Object>> list = new ArrayList<>();
    for (co.yixiang.logging.domain.Log log : logs) {
        Map<String,Object> map = new LinkedHashMap<>();
        map.put("用户名", log.getUsername());
        map.put("IP", log.getRequestIp());
        map.put("IP来源", log.getAddress());
        map.put("描述", log.getDescription());
        map.put("浏览器", log.getBrowser());
        map.put("请求耗时/毫秒", log.getTime());
        map.put("异常详情", new String(ObjectUtil.isNotNull(log.getExceptionDetail()) ? log.getExceptionDetail() : "".getBytes()));
        map.put("创建日期", log.getCreateTime());
        list.add(map);
    }
    FileUtil.downloadExcel(list, response);
}
 
Example #8
Source File: DataSourceAspect.java    From RuoYi with Apache License 2.0 6 votes vote down vote up
@Around("dsPointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
    MethodSignature signature = (MethodSignature) point.getSignature();

    Method method = signature.getMethod();

    DataSource dataSource = method.getAnnotation(DataSource.class);

    if (ObjectUtil.isNotNull(dataSource)) {
        DynamicDataSourceContextHolder.setDataSourceType(dataSource.value().name());
    }

    try {
        return point.proceed();
    } finally {
        // 销毁数据源 在执行方法之后
        DynamicDataSourceContextHolder.clearDataSourceType();
    }
}
 
Example #9
Source File: MemberController.java    From yshopmall with Apache License 2.0 6 votes vote down vote up
@Log("查询用户")
@ApiOperation(value = "查询用户")
@GetMapping(value = "/yxUser")
@PreAuthorize("@el.check('admin','YXUSER_ALL','YXUSER_SELECT')")
public ResponseEntity getYxUsers(YxUserQueryCriteria criteria, Pageable pageable){
    if(ObjectUtil.isNotNull(criteria.getIsPromoter())){
        if(criteria.getIsPromoter() == 1){
            String key = yxSystemConfigService.findByKey(SystemConfigConstants.STORE_BROKERAGE_STATU)
                    .getValue();
            if(Integer.valueOf(key) == 2){
                return new ResponseEntity(null,HttpStatus.OK);
            }
        }
    }
    return new ResponseEntity(yxUserService.queryAll(criteria,pageable),HttpStatus.OK);
}
 
Example #10
Source File: LocalStorageServiceImpl.java    From eladmin with Apache License 2.0 6 votes vote down vote up
@Override
@Transactional(rollbackFor = Exception.class)
public void create(String name, MultipartFile multipartFile) {
    FileUtil.checkSize(properties.getMaxSize(), multipartFile.getSize());
    String suffix = FileUtil.getExtensionName(multipartFile.getOriginalFilename());
    String type = FileUtil.getFileType(suffix);
    File file = FileUtil.upload(multipartFile, properties.getPath().getPath() + type +  File.separator);
    if(ObjectUtil.isNull(file)){
        throw new BadRequestException("上传失败");
    }
    try {
        name = StringUtils.isBlank(name) ? FileUtil.getFileNameNoEx(multipartFile.getOriginalFilename()) : name;
        LocalStorage localStorage = new LocalStorage(
                file.getName(),
                name,
                suffix,
                file.getPath(),
                type,
                FileUtil.getSize(multipartFile.getSize())
        );
        localStorageRepository.save(localStorage);
    }catch (Exception e){
        FileUtil.del(file);
        throw e;
    }
}
 
Example #11
Source File: GeneratorServiceImpl.java    From eladmin with Apache License 2.0 6 votes vote down vote up
@Override
public Object getTables(String name, int[] startEnd) {
    // 使用预编译防止sql注入
    String sql = "select table_name ,create_time , engine, table_collation, table_comment from information_schema.tables " +
            "where table_schema = (select database()) " +
            "and table_name like ? order by create_time desc";
    Query query = em.createNativeQuery(sql);
    query.setFirstResult(startEnd[0]);
    query.setMaxResults(startEnd[1] - startEnd[0]);
    query.setParameter(1, StringUtils.isNotBlank(name) ? ("%" + name + "%") : "%%");
    List result = query.getResultList();
    List<TableInfo> tableInfos = new ArrayList<>();
    for (Object obj : result) {
        Object[] arr = (Object[]) obj;
        tableInfos.add(new TableInfo(arr[0], arr[1], arr[2], arr[3], ObjectUtil.isNotEmpty(arr[4]) ? arr[4] : "-"));
    }
    Query query1 = em.createNativeQuery("SELECT COUNT(*) from information_schema.tables where table_schema = (select database())");
    Object totalElements = query1.getSingleResult();
    return PageUtil.toPage(tableInfos, totalElements);
}
 
Example #12
Source File: YxStoreProductServiceImpl.java    From yshopmall with Apache License 2.0 6 votes vote down vote up
@Override
public List<ProductFormatDto> isFormatAttr(Integer id, String jsonStr) {
    if(ObjectUtil.isNull(id)) throw new BadRequestException("产品不存在");

    YxStoreProductDto yxStoreProductDTO = generator.convert(this.getById(id),YxStoreProductDto.class);
    DetailDto detailDTO = attrFormat(jsonStr);
    List<ProductFormatDto> newList = new ArrayList<>();
    for (Map<String, Map<String,String>> map : detailDTO.getRes()) {
        ProductFormatDto productFormatDTO = new ProductFormatDto();
        productFormatDTO.setDetail(map.get("detail"));
        productFormatDTO.setCost(yxStoreProductDTO.getCost().doubleValue());
        productFormatDTO.setPrice(yxStoreProductDTO.getPrice().doubleValue());
        productFormatDTO.setSales(yxStoreProductDTO.getSales());
        productFormatDTO.setPic(yxStoreProductDTO.getImage());
        productFormatDTO.setCheck(false);
        newList.add(productFormatDTO);
    }
    return newList;
}
 
Example #13
Source File: DatasourceQueryServiceImpl.java    From datax-web with MIT License 6 votes vote down vote up
@Override
public List<String> getColumns(Long id, String tableName) throws IOException {
    //获取数据源对象
    JobDatasource datasource = jobDatasourceService.getById(id);
    //queryTool组装
    if (ObjectUtil.isNull(datasource)) {
        return Lists.newArrayList();
    }
    if (JdbcConstants.HBASE.equals(datasource.getDatasource())) {
        return new HBaseQueryTool(datasource).getColumns(tableName);
    } else if (JdbcConstants.MONGODB.equals(datasource.getDatasource())) {
        return new MongoDBQueryTool(datasource).getColumns(tableName);
    } else {
        BaseQueryTool queryTool = QueryToolFactory.getByDbType(datasource);
        return queryTool.getColumnNames(tableName, datasource.getDatasource());
    }
}
 
Example #14
Source File: SmsCodeFilter.java    From pre with GNU General Public License v3.0 6 votes vote down vote up
private void validate(HttpServletRequest request) {
    //短信验证码
    String smsCode = obtainSmsCode(request);
    // 手机号
    String mobile = obtainMobile(request);
    Object redisCode = redisTemplate.opsForValue().get(mobile);
    if (smsCode == null || smsCode.isEmpty()) {
        throw new ValidateCodeException("短信验证码不能为空");
    }
    if (ObjectUtil.isNull(redisCode)) {
        throw new ValidateCodeException("验证码已失效");
    }
    if (!smsCode.toLowerCase().equals(redisCode)) {
        throw new ValidateCodeException("短信验证码错误");
    }
}
 
Example #15
Source File: SysUserController.java    From RuoYi with Apache License 2.0 6 votes vote down vote up
@ApiOperation("新增用户")
@ApiImplicitParam(name = "user", value = "新增用户信息", dataType = "SysUser")
@RequiresPermissions("system:user:add")
@Log(title = "用户管理", businessType = BusinessType.INSERT)
@PostMapping("/add")
@Transactional(rollbackFor = Exception.class)
@ResponseBody
public AjaxResult addSave(SysUser user) {
    if (ObjectUtil.isNotNull(user.getUserId()) && SysUser.isAdmin(user.getUserId())) {
        return error("不允许修改超级管理员用户");
    }
    if (UserConstants.USER_NAME_NOT_UNIQUE.equals(userService.checkLoginNameUnique(user.getLoginName()))){
        return error("保存用户'" + user.getLoginName() + "'失败,账号已存在");
    }
    user.setSalt(ShiroUtils.randomSalt());
    user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
    user.setCreateBy(ShiroUtils.getLoginName());
    return toAjax(userService.insertUser(user));
}
 
Example #16
Source File: BaseDao.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 获取字段列表 {@code 过滤数据库中不存在的字段,以及自增列}
 *
 * @param t          对象
 * @param ignoreNull 是否忽略空值
 * @return 字段列表
 */
private List<Field> getField(T t, Boolean ignoreNull) {
	// 获取所有字段,包含父类中的字段
	Field[] fields = ReflectUtil.getFields(t.getClass());

	// 过滤数据库中不存在的字段,以及自增列
	List<Field> filterField;
	Stream<Field> fieldStream = CollUtil.toList(fields).stream().filter(field -> ObjectUtil.isNull(field.getAnnotation(Ignore.class)) || ObjectUtil.isNull(field.getAnnotation(Pk.class)));

	// 是否过滤字段值为null的字段
	if (ignoreNull) {
		filterField = fieldStream.filter(field -> ObjectUtil.isNotNull(ReflectUtil.getFieldValue(t, field))).collect(Collectors.toList());
	} else {
		filterField = fieldStream.collect(Collectors.toList());
	}
	return filterField;
}
 
Example #17
Source File: BaseDao.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 获取字段列表 {@code 过滤数据库中不存在的字段,以及自增列}
 *
 * @param t          对象
 * @param ignoreNull 是否忽略空值
 * @return 字段列表
 */
private List<Field> getField(T t, Boolean ignoreNull) {
	// 获取所有字段,包含父类中的字段
	Field[] fields = ReflectUtil.getFields(t.getClass());

	// 过滤数据库中不存在的字段,以及自增列
	List<Field> filterField;
	Stream<Field> fieldStream = CollUtil.toList(fields).stream().filter(field -> ObjectUtil.isNull(field.getAnnotation(Ignore.class)) || ObjectUtil.isNull(field.getAnnotation(Pk.class)));

	// 是否过滤字段值为null的字段
	if (ignoreNull) {
		filterField = fieldStream.filter(field -> ObjectUtil.isNotNull(ReflectUtil.getFieldValue(t, field))).collect(Collectors.toList());
	} else {
		filterField = fieldStream.collect(Collectors.toList());
	}
	return filterField;
}
 
Example #18
Source File: BaseDao.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 获取列
 *
 * @param fieldList 字段列表
 * @return 列信息列表
 */
private List<String> getColumns(List<Field> fieldList) {
	// 构造列
	List<String> columnList = CollUtil.newArrayList();
	for (Field field : fieldList) {
		Column columnAnnotation = field.getAnnotation(Column.class);
		String columnName;
		if (ObjectUtil.isNotNull(columnAnnotation)) {
			columnName = columnAnnotation.name();
		} else {
			columnName = field.getName();
		}
		columnList.add(StrUtil.format("`{}`", columnName));
	}
	return columnList;
}
 
Example #19
Source File: BaseController.java    From open-cloud with MIT License 6 votes vote down vote up
/**
 * 构建Cascader数据
 */
protected List<Map<String, Object>> toCascader(List<Map<String, Object>> maps) {
    maps.forEach(map -> {
        Object obj = map.get("isParent");
        Object label = map.get("label");
        Object id = map.get("value");
        map.put("title", label);
        map.put("id", id);
        Integer isParent = (ObjectUtil.isNotNull(obj) && obj.equals(1)) ? 1 : 0;
        if (isParent.equals(1)) {
            map.put("children", new ArrayList<>());
            map.put("loading", false);
        }
    });
    return maps;
}
 
Example #20
Source File: StoreCouponIssueController.java    From yshopmall with Apache License 2.0 6 votes vote down vote up
@Log("发布")
@ApiOperation(value = "发布")
@PostMapping(value = "/yxStoreCouponIssue")
@PreAuthorize("@el.check('admin','YXSTORECOUPONISSUE_ALL','YXSTORECOUPONISSUE_CREATE')")
public ResponseEntity create(@Validated @RequestBody YxStoreCouponIssue resources){
    if(ObjectUtil.isNotNull(resources.getStartTimeDate())){
        resources.setStartTime(OrderUtil.
                dateToTimestamp(resources.getStartTimeDate()));
    }
    if(ObjectUtil.isNotNull(resources.getEndTimeDate())){
        resources.setEndTime(OrderUtil.
                dateToTimestamp(resources.getEndTimeDate()));
    }
    if(resources.getTotalCount() > 0) {
        resources.setRemainCount(resources.getTotalCount());
    }
    resources.setAddTime(OrderUtil.getSecondTimestampTwo());
    return new ResponseEntity(yxStoreCouponIssueService.save(resources),HttpStatus.CREATED);
}
 
Example #21
Source File: StoreBargainController.java    From yshopmall with Apache License 2.0 6 votes vote down vote up
@Log("修改砍价")
@ApiOperation(value = "修改砍价")
@PutMapping(value = "/yxStoreBargain")
@PreAuthorize("@el.check('admin','YXSTOREBARGAIN_ALL','YXSTOREBARGAIN_EDIT')")
public ResponseEntity update(@Validated @RequestBody YxStoreBargain resources){

    if(ObjectUtil.isNotNull(resources.getStartTimeDate())){
        resources.setStartTime(OrderUtil.
                dateToTimestamp(resources.getStartTimeDate()));
    }
    if(ObjectUtil.isNotNull(resources.getEndTimeDate())){
        resources.setStopTime(OrderUtil.
                dateToTimestamp(resources.getEndTimeDate()));
    }
    if(ObjectUtil.isNull(resources.getId())){
        resources.setAddTime(OrderUtil.getSecondTimestampTwo());
        return new ResponseEntity(yxStoreBargainService.save(resources),HttpStatus.CREATED);
    }else{
        yxStoreBargainService.saveOrUpdate(resources);
        return new ResponseEntity(HttpStatus.NO_CONTENT);
    }
}
 
Example #22
Source File: PermissionUtils.java    From RuoYi with Apache License 2.0 6 votes vote down vote up
/**
 * 返回用户属性值
 *
 * @param property 属性名称
 * @return 用户属性值
 */
public static Object getPrincipalProperty(String property) {
    Subject subject = SecurityUtils.getSubject();
    if (ObjectUtil.isNotNull(subject)) {
        Object principal = subject.getPrincipal();
        try {
            BeanInfo bi = Introspector.getBeanInfo(principal.getClass());
            for (PropertyDescriptor pd : bi.getPropertyDescriptors()) {
                if (pd.getName().equals(property)) {
                    return pd.getReadMethod().invoke(principal, (Object[]) null);
                }
            }
        } catch (Exception e) {
            log.error("Error reading property [{}] from principal of type [{}]", property,
                    principal.getClass().getName());
        }
    }
    return null;
}
 
Example #23
Source File: LocalStorageServiceImpl.java    From yshopmall with Apache License 2.0 5 votes vote down vote up
@Override
public LocalStorageDto create(String name, MultipartFile multipartFile) {
    FileUtil.checkSize(maxSize, multipartFile.getSize());
    String suffix = FileUtil.getExtensionName(multipartFile.getOriginalFilename());
    String type = FileUtil.getFileType(suffix);
    File file = FileUtil.upload(multipartFile, path + type +  File.separator);
    if(ObjectUtil.isNull(file)){
        throw new BadRequestException("上传失败");
    }
    try {
        name = StringUtils.isBlank(name) ? FileUtil.getFileNameNoEx(multipartFile.getOriginalFilename()) : name;
        LocalStorage localStorage = new LocalStorage(
                file.getName(),
                name,
                suffix,
                file.getPath(),
                type,
                FileUtil.getSize(multipartFile.getSize()),
                SecurityUtils.getUsername()
        );
        this.save(localStorage);
        return generator.convert(localStorage,LocalStorageDto.class);
    }catch (Exception e){
        FileUtil.del(file);
        throw e;
    }
}
 
Example #24
Source File: PageUtil.java    From spring-boot-demo with MIT License 5 votes vote down vote up
/**
 * 校验分页参数,为NULL,设置分页参数默认值
 *
 * @param condition 查询参数
 * @param clazz     类
 * @param <T>       {@link PageCondition}
 */
public static <T extends PageCondition> void checkPageCondition(T condition, Class<T> clazz) {
    if (ObjectUtil.isNull(condition)) {
        condition = ReflectUtil.newInstance(clazz);
    }
    // 校验分页参数
    if (ObjectUtil.isNull(condition.getCurrentPage())) {
        condition.setCurrentPage(Consts.DEFAULT_CURRENT_PAGE);
    }
    if (ObjectUtil.isNull(condition.getPageSize())) {
        condition.setPageSize(Consts.DEFAULT_PAGE_SIZE);
    }
}
 
Example #25
Source File: SysUserServiceImpl.java    From pre with GNU General Public License v3.0 5 votes vote down vote up
@Override
public SysUser findSecurityUserByUser(SysUser sysUser) {
    LambdaQueryWrapper<SysUser> select = Wrappers.<SysUser>lambdaQuery()
            .select(SysUser::getUserId, SysUser::getUsername, SysUser::getPassword);
    if (StrUtil.isNotEmpty(sysUser.getUsername())) {
        select.eq(SysUser::getUsername, sysUser.getUsername());
    } else if (StrUtil.isNotEmpty(sysUser.getPhone())) {
        select.eq(SysUser::getPhone, sysUser.getPhone());
    } else if (ObjectUtil.isNotNull(sysUser.getUserId()) && sysUser.getUserId() != 0) {
        select.eq(SysUser::getUserId, sysUser.getUserId());
    }
    return baseMapper.selectOne(select);
}
 
Example #26
Source File: SystemConfigController.java    From yshopmall with Apache License 2.0 5 votes vote down vote up
@Log("新增或修改")
@ApiOperation(value = "新增或修改")
@PostMapping(value = "/yxSystemConfig")
@CacheEvict(cacheNames = ShopConstants.YSHOP_REDIS_INDEX_KEY,allEntries = true)
@PreAuthorize("@el.check('admin','YXSYSTEMCONFIG_ALL','YXSYSTEMCONFIG_CREATE')")
public ResponseEntity create(@RequestBody String jsonStr){

    JSONObject jsonObject = JSON.parseObject(jsonStr);
    jsonObject.forEach(
            (key,value)->{
                YxSystemConfig yxSystemConfig = yxSystemConfigService.getOne(new LambdaQueryWrapper<YxSystemConfig>()
                        .eq(YxSystemConfig::getMenuName,key));
                YxSystemConfig yxSystemConfigModel = new YxSystemConfig();
                yxSystemConfigModel.setMenuName(key);
                yxSystemConfigModel.setValue(value.toString());
                //重新配置微信相关
                if(SystemConfigConstants.WECHAT_APPID.equals(key)){
                    WxMpConfiguration.removeWxMpService();
                    WxPayConfiguration.removeWxPayService();
                }
                if(SystemConfigConstants.WXPAY_MCHID.equals(key) || SystemConfigConstants.WXAPP_APPID.equals(key)){
                    WxPayConfiguration.removeWxPayService();
                }
                RedisUtil.set(key,value.toString(),0);
                if(ObjectUtil.isNull(yxSystemConfig)){
                    yxSystemConfigService.save(yxSystemConfigModel);
                }else{
                    yxSystemConfigModel.setId(yxSystemConfig.getId());
                    yxSystemConfigService.saveOrUpdate(yxSystemConfigModel);
                }
            }
    );

    return new ResponseEntity(HttpStatus.CREATED);
}
 
Example #27
Source File: IndexController.java    From spring-boot-demo with MIT License 5 votes vote down vote up
@GetMapping(value = {"", "/"})
public ModelAndView index(HttpServletRequest request) {
	ModelAndView mv = new ModelAndView();

	User user = (User) request.getSession().getAttribute("user");
	if (ObjectUtil.isNull(user)) {
		mv.setViewName("redirect:/user/login");
	} else {
		mv.setViewName("page/index");
		mv.addObject(user);
	}

	return mv;
}
 
Example #28
Source File: UserServiceTest.java    From spring-boot-demo with MIT License 5 votes vote down vote up
@Test
public void saveUser() {
    String salt = IdUtil.fastSimpleUUID();
    User user = User.builder().name("testSave3").password(SecureUtil.md5("123456" + salt)).salt(salt).email("[email protected]").phoneNumber("17300000003").status(1).lastLoginTime(new DateTime()).createTime(new DateTime()).lastUpdateTime(new DateTime()).build();

    user = userService.saveUser(user);
    Assert.assertTrue(ObjectUtil.isNotNull(user.getId()));
    log.debug("【user】= {}", user);
}
 
Example #29
Source File: SysDictTypeServiceImpl.java    From RuoYi with Apache License 2.0 5 votes vote down vote up
/**
 * 校验字典类型称是否唯一
 *
 * @param dict 字典类型
 * @return 结果
 */
@Override
public String checkDictTypeUnique(SysDictType dict) {
    SysDictType dictType = dictTypeMapper.checkDictTypeUnique(dict.getDictType());
    if (ObjectUtil.isNotNull(dictType) && !dictType.getDictId().equals(dict.getDictId())) {
        return UserConstants.DICT_TYPE_NOT_UNIQUE;
    }
    return UserConstants.DICT_TYPE_UNIQUE;
}
 
Example #30
Source File: UserServiceImpl.java    From spring-boot-demo with MIT License 5 votes vote down vote up
/**
 * 更新用户
 *
 * @param user 用户
 * @return 更新后的用户
 */
@Override
public User updateUser(User user) {
    if (ObjectUtil.isNull(user)) {
        throw new RuntimeException("用户id不能为null");
    }
    userDao.updateTemplateById(user);
    return userDao.single(user.getId());
}