Java Code Examples for cn.hutool.core.util.ObjectUtil

The following examples show how to use cn.hutool.core.util.ObjectUtil. These examples are extracted from open source projects. 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 Project: pre   Author: LiHaodong888   File: SysUserServiceImpl.java    License: 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 Project: pre   Author: LiHaodong888   File: SysUserController.java    License: 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 #3
Source Project: RuoYi   Author: lerry903   File: LogoutFilter.java    License: 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 #4
Source Project: RuoYi   Author: lerry903   File: SysDeptServiceImpl.java    License: 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 Project: sk-admin   Author: DengSinkiang   File: LogServiceImpl.java    License: 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 #6
Source Project: eladmin   Author: elunez   File: GeneratorServiceImpl.java    License: 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 #7
Source Project: datax-web   Author: WeiYe-Jing   File: DatasourceQueryServiceImpl.java    License: 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 #8
Source Project: open-cloud   Author: liuyadu   File: BaseController.java    License: 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 #9
Source Project: spring-boot-demo   Author: xkcoding   File: BaseDao.java    License: 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 #10
Source Project: pre   Author: LiHaodong888   File: SmsCodeFilter.java    License: 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 #11
Source Project: RuoYi   Author: lerry903   File: SysUserController.java    License: 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 #12
Source Project: spring-boot-demo   Author: jiangsongHB   File: BaseDao.java    License: 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 #13
Source Project: spring-boot-demo   Author: jiangsongHB   File: BaseDao.java    License: 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 #14
Source Project: yshopmall   Author: guchengwuyue   File: StoreCouponIssueController.java    License: 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 #15
Source Project: yshopmall   Author: guchengwuyue   File: StoreBargainController.java    License: 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 #16
Source Project: yshopmall   Author: guchengwuyue   File: YxStoreProductServiceImpl.java    License: 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 #17
Source Project: RuoYi   Author: lerry903   File: PermissionUtils.java    License: 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 #18
Source Project: eladmin   Author: elunez   File: LocalStorageServiceImpl.java    License: 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 #19
Source Project: yshopmall   Author: guchengwuyue   File: MemberController.java    License: 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 #20
Source Project: yshopmall   Author: guchengwuyue   File: WechatReplyController.java    License: 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 #21
Source Project: yshopmall   Author: guchengwuyue   File: LogServiceImpl.java    License: 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 #22
Source Project: RuoYi   Author: lerry903   File: DataSourceAspect.java    License: 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 #23
Source Project: eladmin   Author: elunez   File: QueryHelp.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private static <T, R> Expression<T> getExpression(String attributeName, Join join, Root<R> root) {
    if (ObjectUtil.isNotEmpty(join)) {
        return join.get(attributeName);
    } else {
        return root.get(attributeName);
    }
}
 
Example #24
Source Project: RuoYi   Author: lerry903   File: SysDeptController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 修改
 */
@GetMapping("/edit/{deptId}")
public String edit(@PathVariable("deptId") Long deptId, ModelMap mmap) {
    SysDept dept = deptService.selectDeptById(deptId);
    if (ObjectUtil.isNotNull(dept) && 100L == deptId) {
        dept.setParentName("无");
    }
    mmap.put("dept", dept);
    return prefix + "/edit";
}
 
Example #25
Source Project: spring-boot-demo   Author: xkcoding   File: PageController.java    License: MIT License 5 votes vote down vote up
/**
 * 跳转到 登录页
 *
 * @param redirect 是否是跳转回来的
 */
@GetMapping("/login")
public ModelAndView login(Boolean redirect) {
    ModelAndView mv = new ModelAndView();

    if (ObjectUtil.isNotNull(redirect) && ObjectUtil.equal(true, redirect)) {
        mv.addObject("message", "请先登录!");
    }
    mv.setViewName("login");
    return mv;
}
 
Example #26
Source Project: spring-boot-demo   Author: xkcoding   File: IndexController.java    License: 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.btl");
		mv.addObject(user);
	}

	return mv;
}
 
Example #27
Source Project: pre   Author: LiHaodong888   File: PreJwtAuthenticationTokenFilter.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {

    PreSecurityUser securityUser = jwtUtil.getUserFromToken(request);
    if (ObjectUtil.isNotNull(securityUser)){
        Set<String> permissions = userService.findPermsByUserId(securityUser.getUserId());
        Collection<? extends GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(permissions.toArray(new String[0]));

        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(securityUser, null, authorities);
        authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
    }

    chain.doFilter(request, response);
}
 
Example #28
Source Project: supplierShop   Author: guchengwuyue   File: OrderServiceImpl.java    License: MIT License 5 votes vote down vote up
/**
 * 操作订单
 * @param orderId
 * @param type 操作类型 1-取消订单 2-确认收货 3-退货
 */
@Override
@Transactional
public void orderHandle(int orderId, int type,int userId) {
    QueryWrapper<StoreOrder> wrapper = new QueryWrapper<>();
    wrapper.eq("deleted",0).eq("user_id",userId).eq("order_id",orderId);
    StoreOrder storeOrder = baseMapper.selectOne(wrapper);
    if(ObjectUtil.isNull(storeOrder)){
        throw new LightSecurityException("订单不存在");
    }

    StoreOrder order = new StoreOrder();
    order.setOrderId(orderId);
    switch (type){
        case 1:
            if(storeOrder.getPayStatus() != 0){
                throw new LightSecurityException("只有未付款订单才能取消");
            }
            order.setDeleted(1);
            order.setDeletedTime(OrderUtil.getSecondTimestampTwo());
            break;
        case 2:
            if(storeOrder.getShippingStatus() != 1){
                throw new LightSecurityException("只能操作已经发货订单");
            }
            order.setOrderStatus(1);
            order.setConfirmTime(OrderUtil.getSecondTimestampTwo());
            break;
        case 3:
            if(storeOrder.getShippingStatus() == 1 && storeOrder.getOrderStatus() == 0){
                throw new LightSecurityException("已发货订单才能操作退货");
            }
            order.setShippingStatus(2);
            break;
    }

    baseMapper.updateById(order);


}
 
Example #29
Source Project: supplierShop   Author: guchengwuyue   File: GoodsServiceImpl.java    License: MIT License 5 votes vote down vote up
/**
 * 收藏判断
 * @param goodsId
 * @param userId
 * @return
 */
@Override
public boolean isCollect(int goodsId, int userId) {
    QueryWrapper<StoreGoodsCollect> wrapper = new QueryWrapper<>();
    wrapper.eq("goods_id",goodsId).eq("user_id",userId);
    StoreGoodsCollect goodsCollect = storeGoodsCollectMapper.selectOne(wrapper);
    if(ObjectUtil.isNotNull(goodsCollect)) return true;
    return false;
}
 
Example #30
Source Project: supplierShop   Author: guchengwuyue   File: GoodsServiceImpl.java    License: MIT License 5 votes vote down vote up
@Override
public Map<String,StoreSpecGoodsPrice> goodsSpecPrice(int goodsId) {
    QueryWrapper<StoreSpecGoodsPrice> wrapper = new QueryWrapper<>();
    wrapper.eq("goods_id",goodsId);
    List<StoreSpecGoodsPrice> specGoodsPriceList = storeSpecGoodsPriceMapper
            .selectList(wrapper);
    if(ObjectUtil.isNull(specGoodsPriceList)){
        System.out.println("2222");
        throw new EntityExistException(specGoodsPriceList.getClass());
    }
    Map<String, StoreSpecGoodsPrice> listMap = specGoodsPriceList.stream().collect(
            Collectors.toMap(StoreSpecGoodsPrice::getKey,o->o));

    return listMap;
}