Java Code Examples for cn.hutool.core.collection.CollectionUtil#isNotEmpty()
The following examples show how to use
cn.hutool.core.collection.CollectionUtil#isNotEmpty() .
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: MsgsCenterInfoServiceImpl.java From zuihou-admin-cloud with Apache License 2.0 | 6 votes |
@Override @Transactional(rollbackFor = Exception.class) public MsgsCenterInfo saveMsgs(MsgsCenterInfoSaveDTO data) { MsgsCenterInfo info = BeanPlusUtil.toBean(data.getMsgsCenterInfoDTO(), MsgsCenterInfo.class); info.setTitle(getOrDef(info.getTitle(), info.getContent())); info.setAuthor(getOrDef(info.getAuthor(), BaseContextHandler.getName())); super.save(info); //公式公告,不会指定接收人 Set<Long> userIdList = data.getUserIdList(); if (CollectionUtil.isNotEmpty(userIdList)) { List<MsgsCenterInfoReceive> receiveList = userIdList.stream().map((userId) -> MsgsCenterInfoReceive.builder() .isRead(false) .userId(userId) .msgsCenterId(info.getId()) .build()).collect(Collectors.toList()); msgsCenterInfoReceiveService.saveBatch(receiveList); } return info; }
Example 2
Source File: JobSpringExecutor.java From datax-web with MIT License | 6 votes |
private void initJobHandlerRepository(ApplicationContext applicationContext) { if (applicationContext == null) { return; } // init job handler action Map<String, Object> serviceBeanMap = applicationContext.getBeansWithAnnotation(JobHandler.class); if (CollectionUtil.isNotEmpty(serviceBeanMap)) { for (Object serviceBean : serviceBeanMap.values()) { if (serviceBean instanceof IJobHandler) { String name = serviceBean.getClass().getAnnotation(JobHandler.class).value(); IJobHandler handler = (IJobHandler) serviceBean; if (loadJobHandler(name) != null) { throw new RuntimeException("datax-web jobhandler[" + name + "] naming conflicts."); } registJobHandler(name, handler); } } } }
Example 3
Source File: InterceptorProvider.java From redant with Apache License 2.0 | 6 votes |
public static List<Interceptor> getInterceptors(){ // 优先获取用户自定义的 InterceptorBuilder 构造的 Interceptor if(!loaded){ synchronized (InterceptorProvider.class) { if(!loaded) { Set<Class<?>> builders = ClassScaner.scanPackageBySuper(CommonConstants.INTERCEPTOR_SCAN_PACKAGE, InterceptorBuilder.class); if (CollectionUtil.isNotEmpty(builders)) { try { for (Class<?> cls : builders) { builder = (InterceptorBuilder) cls.newInstance(); break; } } catch (IllegalAccessException | InstantiationException e) { e.printStackTrace(); } } loaded = true; } } } if(builder!=null){ return builder.build(); } // 获取不到时,再扫描所有指定目录下的 Interceptor return InterceptorsHolder.interceptors; }
Example 4
Source File: BlockInterceptor.java From redant with Apache License 2.0 | 6 votes |
@Override public boolean preHandle(Map<String, List<String>> paramMap) { if(CollectionUtil.isNotEmpty(paramMap)) { String blockKey = "block"; String blockVal = "true"; List<String> values = paramMap.get(blockKey); if(CollectionUtil.isNotEmpty(values)){ String val = values.get(0); if(blockVal.equals(val)){ JSONObject content = new JSONObject(); content.put("status","你被前置方法拦截了"); content.put("reason","请求参数中有 block=true"); FullHttpResponse response = HttpRenderUtil.render(content, RenderType.JSON); RedantContext.currentContext().setResponse(response); LOGGER.info("[BlockInterceptor] blocked preHandle"); return false; } } } return true; }
Example 5
Source File: SysDeptServiceImpl.java From RuoYi with Apache License 2.0 | 6 votes |
/** * 对象转部门树 * * @param deptList 部门列表 * @param roleDeptList 角色已存在菜单列表 * @return 部门树 */ private List<Ztree> initZtree(List<SysDept> deptList, List<String> roleDeptList) { List<Ztree> ztrees = new ArrayList<>(); boolean isCheck = CollectionUtil.isNotEmpty(roleDeptList); if(CollectionUtil.isNotEmpty(deptList)){ deptList.stream() .filter(dept-> UserConstants.DEPT_NORMAL.equals(dept.getStatus())) .forEach(dept->{ Ztree ztree = new Ztree(); ztree.setId(dept.getDeptId()); ztree.setPId(dept.getParentId()); ztree.setName(dept.getDeptName()); ztree.setTitle(dept.getDeptName()); if (isCheck){ ztree.setChecked(roleDeptList.contains(dept.getDeptId() + dept.getDeptName())); } ztrees.add(ztree); }); } return ztrees; }
Example 6
Source File: DeptController.java From sk-admin with Apache License 2.0 | 6 votes |
@Log("删除部门") @ApiOperation("删除部门") @DeleteMapping @PreAuthorize("@sk.check('dept:del')") public ResponseEntity<Object> delete(@RequestBody Set<Long> ids){ Set<DeptDTO> deptDtos = new HashSet<>(); for (Long id : ids) { List<Dept> deptList = deptService.findByPid(id); deptDtos.add(deptService.findById(id)); if(CollectionUtil.isNotEmpty(deptList)){ deptDtos = deptService.getDeleteDepts(deptList, deptDtos); } } try { deptService.delete(deptDtos); }catch (Throwable e){ ThrowableUtil.throwForeignKeyException(e, "所选部门中存在岗位或者角色关联,请取消关联后再试"); } return new ResponseEntity<>(HttpStatus.OK); }
Example 7
Source File: ApiDocInterfaceController.java From feiqu-opensource with Apache License 2.0 | 6 votes |
/** * 更新ApiDocInterface页面 */ @RequestMapping("/debug/{apiDocInterfaceId}") public Object debug(@PathVariable Long apiDocInterfaceId, Model model) { ApiDocInterface apiDocInterface = apiDocInterfaceService.selectByPrimaryKey(apiDocInterfaceId); apiDocInterface.setTrueexam(HtmlUtils.htmlUnescape(apiDocInterface.getTrueexam())); apiDocInterface.setFalseexam(HtmlUtils.htmlUnescape(apiDocInterface.getFalseexam())); model.addAttribute("apiDocInterface", JSON.toJSON(apiDocInterface)); ApiDocModuleExample example = new ApiDocModuleExample(); example.createCriteria().andProjectIdEqualTo(apiDocInterface.getProjectid()); List<ApiDocModule> modules = apiDocModuleService.selectByExample(example); List<KeyValue> keyValues = Lists.newArrayList(); if(CollectionUtil.isNotEmpty(modules)){ modules.forEach(module -> { KeyValue keyValue = new KeyValue(module.getId().toString(),module.getModuleName()); keyValues.add(keyValue); }); } model.addAttribute("modules", keyValues); model.addAttribute("apiDocInterfaceId", apiDocInterfaceId); return "/apiDocInterface/debug.html"; }
Example 8
Source File: RestExceptionHandler.java From plumemo with Apache License 2.0 | 5 votes |
/** * validation 异常处理 * * @param request 请求体 * @param e MethodArgumentNotValidException * @return HttpResult */ @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseBody public Result onMethodArgumentNotValidException(HttpServletRequest request, MethodArgumentNotValidException e) { BindingResult result = e.getBindingResult(); if (result != null && result.hasErrors()) { StringBuilder sb = new StringBuilder(); List<FieldError> errors = result.getFieldErrors(); if(CollectionUtil.isNotEmpty(errors)){ FieldError error = errors.get(0); String rejectedValue = Objects.toString(error.getRejectedValue(), ""); String defMsg = error.getDefaultMessage(); // 排除类上面的注解提示 if(rejectedValue.contains(Constants.DELIMITER_TO)){ // 自己去确定错误字段 sb.append(defMsg); }else{ if(Constants.DELIMITER_COLON.contains(defMsg)){ sb.append(error.getField()).append(" ").append(defMsg); }else{ sb.append(error.getField()).append(" ").append(defMsg).append(":").append(rejectedValue); } } } else { String msg = result.getAllErrors().get(0).getDefaultMessage(); sb.append(msg); } return Result.createWithErrorMessage(sb.toString(), ErrorEnum.PARAM_ERROR.getCode()); } return null; }
Example 9
Source File: DefaultHtmlMaker.java From redant with Apache License 2.0 | 5 votes |
@Override public String make(String htmlTemplate, Map<String, Object> contentMap) { String html = htmlTemplate; if(CollectionUtil.isNotEmpty(contentMap)){ for(Map.Entry<String,Object> entry : contentMap.entrySet()){ String key = entry.getKey(); Object val = entry.getValue(); if(val instanceof String){ html = html.replaceAll(HtmlKeyHolder.START_ESCAPE+key+HtmlKeyHolder.END,val.toString()); } } } return html; }
Example 10
Source File: SearchController.java From mall4j with GNU Affero General Public License v3.0 | 5 votes |
private ResponseEntity<List<HotSearchDto>> getListResponseEntity(Integer number, Integer sort, List<HotSearchDto> list) { if(sort == null || sort == 0){ Collections.shuffle(list); } if(!CollectionUtil.isNotEmpty(list) || list.size()< number){ return ResponseEntity.ok(list); } return ResponseEntity.ok(list.subList(0, number)); }
Example 11
Source File: ProductServiceImpl.java From mall4j with GNU Affero General Public License v3.0 | 5 votes |
@Override @Transactional(rollbackFor = Exception.class) public void saveProduct(Product product) { productMapper.insert(product); if (CollectionUtil.isNotEmpty(product.getSkuList())) { skuMapper.insertBatch(product.getProdId(), product.getSkuList()); } prodTagReferenceMapper.insertBatch(product.getShopId(), product.getProdId(), product.getTagList()); }
Example 12
Source File: TransportServiceImpl.java From mall4j with GNU Affero General Public License v3.0 | 5 votes |
@Override @Transactional(rollbackFor = Exception.class) @CacheEvict(cacheNames = "TransportAndAllItems", key = "#transport.transportId") public void updateTransportAndTransfee(Transport transport) { Transport dbTransport = getTransportAndAllItems(transport.getTransportId()); // 删除所有的运费项 transfeeMapper.deleteByTransportId(transport.getTransportId()); // 删除所有的指定包邮条件项 transfeeMapper.deleteTransfeeFreesByTransportId(transport.getTransportId()); List<Long> transfeeIds = dbTransport.getTransfees().stream().map(Transfee::getTransfeeId).collect(Collectors.toList()); List<Long> transfeeFreeIds = dbTransport.getTransfeeFrees().stream().map(TransfeeFree::getTransfeeFreeId).collect(Collectors.toList()); // 删除所有运费项包含的城市 transcityMapper.deleteBatchByTransfeeIds(transfeeIds); if(CollectionUtil.isNotEmpty(transfeeFreeIds)) { // 删除所有指定包邮条件项包含的城市 transcityMapper.deleteBatchByTransfeeFreeIds(transfeeFreeIds); } // 更新运费模板 transportMapper.updateById(transport); // 插入所有的运费项和城市 insertTransfeeAndTranscity(transport); // 插入所有的指定包邮条件项和城市 if (transport.getHasFreeCondition() == 1) { insertTransfeeFreeAndTranscityFree(transport); } }
Example 13
Source File: RoleServiceImpl.java From eladmin with Apache License 2.0 | 5 votes |
/** * 清理缓存 * @param id / */ public void delCaches(Long id, List<User> users) { users = CollectionUtil.isEmpty(users) ? userRepository.findByRoleId(id) : users; if (CollectionUtil.isNotEmpty(users)) { users.forEach(item -> userCacheClean.cleanUserCache(item.getUsername())); Set<Long> userIds = users.stream().map(User::getId).collect(Collectors.toSet()); redisUtils.delByKeys(CacheKey.DATE_USER, userIds); redisUtils.delByKeys(CacheKey.MENU_USER, userIds); redisUtils.delByKeys(CacheKey.ROLE_AUTH, userIds); redisUtils.del(CacheKey.ROLE_ID + id); } }
Example 14
Source File: DefaultBeanContext.java From redant with Apache License 2.0 | 5 votes |
/** * 初始化Bean */ private void initBean() { LOGGER.info("[DefaultBeanContext] start initBean"); try { /* * 扫描指定package下指定的类,并返回set */ Set<Class<?>> classSet = ClassScaner.scanPackageByAnnotation(CommonConstants.BEAN_SCAN_PACKAGE, Bean.class); beanMap = new LinkedHashMap<>(classSet.size() + 1); if (CollectionUtil.isNotEmpty(classSet)) { /* * 遍历所有类,找出有beanClass注解的类,并封装到linkedHashMap里 */ for (Class<?> cls : classSet) { Bean bean = cls.getAnnotation(Bean.class); if (bean != null) { String beanName = StrUtil.isNotBlank(bean.name()) ? bean.name() : cls.getName(); if (beanMap.containsKey(beanName)) { LOGGER.warn("[DefaultBeanContext] duplicate bean with name={}", beanName); continue; } beanMap.put(beanName, cls.newInstance()); } } LOGGER.info("[DefaultBeanContext] initBean success!"); } else { LOGGER.warn("[DefaultBeanContext] no bean classes scanned!"); } } catch (Exception e) { LOGGER.error("[DefaultBeanContext] initBean error,cause:{}", e.getMessage(), e); } }
Example 15
Source File: GeneratorServiceImpl.java From eladmin with Apache License 2.0 | 5 votes |
@Override public List<ColumnInfo> getColumns(String tableName) { List<ColumnInfo> columnInfos = columnInfoRepository.findByTableNameOrderByIdAsc(tableName); if (CollectionUtil.isNotEmpty(columnInfos)) { return columnInfos; } else { columnInfos = query(tableName); return columnInfoRepository.saveAll(columnInfos); } }
Example 16
Source File: RedantContext.java From redant with Apache License 2.0 | 5 votes |
public RedantContext addCookies(Set<Cookie> cookieSet){ if(CollectionUtil.isNotEmpty(cookieSet)){ if(CollectionUtil.isEmpty(cookies)){ cookies = new HashSet<>(); } cookies.addAll(cookieSet); } return this; }
Example 17
Source File: GeneratorServiceImpl.java From sk-admin with Apache License 2.0 | 5 votes |
@Override public List<ColumnInfo> getColumns(String tableName) { List<ColumnInfo> columnInfos = columnInfoDao.findByTableNameOrderByIdAsc(tableName); if (CollectionUtil.isNotEmpty(columnInfos)) { return columnInfos; } else { columnInfos = query(tableName); return columnInfoDao.saveAll(columnInfos); } }
Example 18
Source File: BeautyController.java From feiqu-opensource with Apache License 2.0 | 4 votes |
@GetMapping("{beautyId}") public Object detail(@PathVariable Integer beautyId, Model model){ try { FqUserCache fqUser = getCurrentUser(); if(fqUser == null){ return USER_LOGIN_REDIRECT_URL; } //暂时只支持男生看 因为我老婆看了感觉不正经 所以关闭女性观看的权限 if(fqUser.getSex() == null || SexEnum.GIRL.getValue().equals(fqUser.getSex())){ model.addAttribute(CommonConstant.GENERAL_CUSTOM_ERROR_CODE,"暂时只支持男生看"); return GENERAL_CUSTOM_ERROR_URL; } SuperBeautyExample example = new SuperBeautyExample(); example.createCriteria().andIdEqualTo(beautyId); List<BeautyUserResponse> beautyUserResponses = superBeautyService.selectDetailById(beautyId); if(CollectionUtil.isNotEmpty(beautyUserResponses)){ SuperBeauty superBeauty = beautyUserResponses.get(0); SuperBeauty superBeautyToupdate = new SuperBeauty(); superBeautyToupdate.setId(superBeauty.getId()); superBeautyToupdate.setSeeCount(superBeauty.getSeeCount() == null?1:superBeauty.getSeeCount() + 1); superBeautyService.updateByPrimaryKeySelective(superBeautyToupdate); model.addAttribute("beauty",beautyUserResponses.get(0)); String picList = superBeauty.getPicList(); String picDescList = superBeauty.getPicDescList(); List<KeyValue> list = Lists.newArrayList(); if(picList != null){ String[] picListStr = picList.split(","); String[] picDescStr = picDescList.split(","); for(int i = 0;i<picListStr.length;i++){ list.add(new KeyValue(picDescStr[i],picListStr[i])); } } model.addAttribute("picList",list); GeneralCommentExample commentExample = new GeneralCommentExample(); commentExample.createCriteria().andTopicIdEqualTo(beautyId).andTopicTypeEqualTo(TopicTypeEnum.PIC_TYPE.getValue()); List<DetailCommentResponse> comments = commentService.selectUserByExample(commentExample); model.addAttribute("comments",comments); model.addAttribute("commentsSize",comments.size()); /*if(!fqUser.getId().equals(superBeauty.getUploadUserId())){ CommonUtils.addOrDelUserQudouNum(fqUser,-10); }*/ }else { return GENERAL_NOT_FOUNF_404_URL; } } catch (Exception e) { logger.error("beauty detail error",e); model.addAttribute(CommonConstant.SYSTEM_ERROR_CODE,"出错了"); return GENERAL_CUSTOM_ERROR_URL; } return "/beauty/detail.html"; }
Example 19
Source File: HotContentJob.java From feiqu-opensource with Apache License 2.0 | 4 votes |
@Scheduled(cron = "0 0/30 9-18 * * ? ")//从9点到18点 每半个小时更新一次 // @Scheduled(cron = "0 51 15 * * ? ") public void work(){ Stopwatch stopwatch = Stopwatch.createStarted(); PageHelper.startPage(1, 5 , false); ThoughtExample thoughtExample = new ThoughtExample(); thoughtExample.setOrderByClause("create_time desc"); thoughtExample.createCriteria().andDelFlagEqualTo(YesNoEnum.NO.getValue()); List<ThoughtWithUser> newThoughts = thoughtService.getThoughtWithUser(thoughtExample); if(CollectionUtil.isNotEmpty(newThoughts)){ newThoughts.forEach(t->{ if(StringUtils.isNotEmpty(t.getPicList())){ t.setPictures(Arrays.asList(t.getPicList().split(","))); } }); } CommonConstant.NEW_THOUGHT_LIST = newThoughts; PageHelper.startPage(1, 5 , false); thoughtExample.clear(); thoughtExample.setOrderByClause("comment_count desc "); thoughtExample.createCriteria().andDelFlagEqualTo(YesNoEnum.NO.getValue()); CommonConstant.HOT_THOUGHT_LIST = thoughtService.getThoughtWithUser(thoughtExample); ArticleExample example = new ArticleExample(); example.setOrderByClause("browse_count desc"); example.createCriteria().andCreateTimeGreaterThan(DateUtil.offsetDay(new Date(),-31)); PageHelper.startPage(0,10,false); List<Article> hotArticles = articleService.selectByExample(example); /*for(Article article : hotArticles){ if(article.getArticleTitle().length() > 20){ article.setArticleTitle(StringUtils.substring(article.getArticleTitle(),0,20) + "……"); } }*/ if(CollectionUtil.isNotEmpty(hotArticles)){ CommonConstant.HOT_ARTICLE_LIST = hotArticles; } FqNoticeExample fqNoticeExample = new FqNoticeExample(); fqNoticeExample.setOrderByClause("fq_order asc"); fqNoticeExample.createCriteria().andIsShowEqualTo(YesNoEnum.YES.getValue()); List<FqNotice> list = fqNoticeService.selectByExample(fqNoticeExample); if(CollectionUtil.isNotEmpty(list)){ CommonConstant.FQ_NOTICE_LIST = list; } PageHelper.startPage(0,5,false); SuperBeautyExample beautyExample = new SuperBeautyExample(); beautyExample.setOrderByClause("like_count desc"); List<BeautyUserResponse> beauties = superBeautyService.selectDetailByExample(beautyExample); if(CollectionUtil.isNotEmpty(beauties)){ CommonConstant.HOT_BEAUTY_LIST = beauties; } try { int month = DateUtil.thisMonth()+1; JedisCommands commands = JedisProviderFactory.getJedisCommands(null); Set<String> userIds =commands.zrevrange(CommonConstant.FQ_ACTIVE_USER_SORT+month,0,4); if(CollectionUtils.isNotEmpty(userIds)){ List<Integer> userIdList = Lists.newArrayList(); for(String userId : userIds){ userIdList.add(Integer.valueOf(userId)); } FqUserExample fqUserExample = new FqUserExample(); example.createCriteria().andIdIn(userIdList); List<FqUser> fqUsers = fqUserService.selectByExample(fqUserExample); Map<Integer,FqUser> userMap = Maps.newHashMap(); fqUsers.forEach(fqUser -> { userMap.put(fqUser.getId(),fqUser); }); List<UserActiveNumResponse> responses = Lists.newArrayList(); for(int i = 0;i<userIdList.size();i++){ double score = commands.zscore(CommonConstant.FQ_ACTIVE_USER_SORT+month,userIdList.get(i).toString()); if(userMap.get(userIdList.get(i)) == null){ continue; } UserActiveNumResponse userActiveNumResponse = new UserActiveNumResponse(userMap.get(userIdList.get(i)),score,i+1); responses.add(userActiveNumResponse); } CommonConstant.FQ_ACTIVE_USER_LIST = responses; } } catch (Exception e) { logger.error("",e); } Runtime runtime = Runtime.getRuntime(); String memoryInfo ="freeMemory:"+runtime.freeMemory()+",totalMemory:"+runtime.totalMemory(); stopwatch.stop(); long seconds = stopwatch.elapsed(TimeUnit.SECONDS); logger.info("热门文章以及通知以及热门图片更新完毕,耗时{}秒,内存信息:{}",seconds,memoryInfo); }
Example 20
Source File: ProductServiceImpl.java From mall4j with GNU Affero General Public License v3.0 | 4 votes |
@Override @Transactional(rollbackFor = Exception.class) @Caching(evict = { @CacheEvict(cacheNames = "product", key = "#product.prodId"), @CacheEvict(cacheNames = "skuList", key = "#product.prodId") }) public void updateProduct(Product product, Product dbProduct) { productMapper.updateById(product); List<Long> dbSkuIds = dbProduct.getSkuList().stream().map(Sku::getSkuId).collect(Collectors.toList()); // 2019/04/c0244be79909484fb67bc6d5f70cae18.jpg // if (!Objects.equals(dbProduct.getPic(), product.getPic()) && StrUtil.isNotBlank(dbProduct.getPic())) { // // 删除数据库中的商品图片 // attachFileService.deleteFile(dbProduct.getPic()); // } // 将所有该商品的sku标记为已删除状态 skuMapper.deleteByProdId(product.getProdId()); // 接口传入sku列表 List<Sku> skuList = product.getSkuList(); if (CollectionUtil.isEmpty(skuList)) { return; } List<Sku> insertSkuList = new ArrayList<>(); for (Sku sku : skuList) { sku.setIsDelete(0); // 如果数据库中原有sku就更新,否者就插入 if (dbSkuIds.contains(sku.getSkuId())) { skuMapper.updateById(sku); } else { insertSkuList.add(sku); } } // 批量插入sku if (CollectionUtil.isNotEmpty(insertSkuList)) { skuMapper.insertBatch(product.getProdId(), insertSkuList); } //更新分组信息 List<Long> tagList = product.getTagList(); if (CollectionUtil.isNotEmpty(tagList)) { prodTagReferenceMapper.delete(new LambdaQueryWrapper<ProdTagReference>().eq(ProdTagReference::getProdId, product.getProdId())); prodTagReferenceMapper.insertBatch(dbProduct.getShopId(), product.getProdId(), tagList); } }