Java Code Examples for cn.hutool.core.util.StrUtil#isNotEmpty()

The following examples show how to use cn.hutool.core.util.StrUtil#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: NodeIndexController.java    From Jpom with MIT License 6 votes vote down vote up
@RequestMapping(value = "list.html", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
@Feature(method = MethodFeature.LIST)
public String list(String group) {
    List<NodeModel> nodeModels = nodeService.list();
    //
    if (nodeModels != null && StrUtil.isNotEmpty(group)) {
        // 筛选
        List<NodeModel> filterList = nodeModels.stream().filter(nodeModel -> StrUtil.equals(group, nodeModel.getGroup())).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(filterList)) {
            // 如果传入的分组找到了节点,就返回  否则返回全部
            nodeModels = filterList;
        }
    }
    setAttribute("array", nodeModels);
    // 获取所有的ssh 名称
    JSONObject sshName = new JSONObject();
    List<SshModel> sshModels = sshService.list();
    if (sshModels != null) {
        sshModels.forEach(sshModel -> sshName.put(sshModel.getId(), sshModel.getName()));
    }
    setAttribute("sshName", sshName);
    // group
    HashSet<String> allGroup = nodeService.getAllGroup();
    setAttribute("groups", allGroup);
    return "node/list";
}
 
Example 2
Source File: ExcelUtil.java    From v-mock with MIT License 6 votes vote down vote up
/**
 * 获取bean中的属性值
 *
 * @param vo    实体对象
 * @param field 字段
 * @param excel 注解
 * @return 最终的属性值
 * @throws Exception
 */
private Object getTargetValue(T vo, Field field, Excel excel) throws Exception {
    Object o = field.get(vo);
    if (StrUtil.isNotEmpty(excel.targetAttr())) {
        String target = excel.targetAttr();
        if (target.indexOf(StrUtil.DOT) > -1) {
            String[] targets = target.split("[.]");
            for (String name : targets) {
                o = getValue(o, name);
            }
        } else {
            o = getValue(o, target);
        }
    }
    return o;
}
 
Example 3
Source File: BuildListController.java    From Jpom with MIT License 6 votes vote down vote up
@RequestMapping(value = "list_data.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
@Feature(method = MethodFeature.LIST)
public String getMonitorList(String group) {
    List<BuildModelVo> list = buildService.list(BuildModelVo.class);
    if (StrUtil.isNotEmpty(group) && CollUtil.isNotEmpty(list)) {
        List<BuildModelVo> array = new ArrayList<>();
        for (BuildModelVo buildModelVo : list) {
            if (group.equals(buildModelVo.getGroup())) {
                array.add(buildModelVo);
            }
        }
        list = array;
    }
    return JsonMessage.getString(200, "", list);
}
 
Example 4
Source File: HutoolController.java    From mall-learning with Apache License 2.0 6 votes vote down vote up
@ApiOperation("StrUtil使用:字符串工具")
@GetMapping(value = "/strUtil")
public CommonResult strUtil() {
    //判断是否为空字符串
    String str = "test";
    StrUtil.isEmpty(str);
    StrUtil.isNotEmpty(str);
    //去除字符串的前后缀
    StrUtil.removeSuffix("a.jpg", ".jpg");
    StrUtil.removePrefix("a.jpg", "a.");
    //格式化字符串
    String template = "这只是个占位符:{}";
    String str2 = StrUtil.format(template, "我是占位符");
    LOGGER.info("/strUtil format:{}", str2);
    return CommonResult.success(null, "操作成功");
}
 
Example 5
Source File: BaseServerController.java    From Jpom with MIT License 6 votes vote down vote up
/**
 * 处理分页的时间字段
 *
 * @param page    分页
 * @param entity  条件
 * @param colName 字段名称
 */
protected void doPage(Page page, Entity entity, String colName) {
    String time = getParameter("time");
    colName = colName.toUpperCase();
    page.addOrder(new Order(colName, Direction.DESC));
    // 时间
    if (StrUtil.isNotEmpty(time)) {
        String[] val = StrUtil.split(time, "~");
        if (val.length == 2) {
            DateTime startDateTime = DateUtil.parse(val[0], DatePattern.NORM_DATETIME_FORMAT);
            entity.set(colName, ">= " + startDateTime.getTime());

            DateTime endDateTime = DateUtil.parse(val[1], DatePattern.NORM_DATETIME_FORMAT);
            if (startDateTime.equals(endDateTime)) {
                endDateTime = DateUtil.endOfDay(endDateTime);
            }
            // 防止字段重复
            entity.set(colName + " ", "<= " + endDateTime.getTime());
        }
    }
}
 
Example 6
Source File: QueryServiceImpl.java    From microservices-platform with Apache License 2.0 6 votes vote down vote up
/**
 * 拼装逻辑删除的条件
 * @param searchDto 搜索dto
 * @param logicDelDto 逻辑删除dto
 */
private void setLogicDelQueryStr(SearchDto searchDto, LogicDelDto logicDelDto) {
    if (logicDelDto != null
            && StrUtil.isNotEmpty(logicDelDto.getLogicDelField())
            && StrUtil.isNotEmpty(logicDelDto.getLogicNotDelValue())) {
        String result;
        //搜索条件
        String queryStr = searchDto.getQueryStr();
        //拼凑逻辑删除的条件
        String logicStr = logicDelDto.getLogicDelField() + ":" + logicDelDto.getLogicNotDelValue();
        if (StrUtil.isNotEmpty(queryStr)) {
            result = "(" + queryStr + ") AND " + logicStr;
        } else {
            result = logicStr;
        }
        searchDto.setQueryStr(result);
    }
}
 
Example 7
Source File: ProxySession.java    From Jpom with MIT License 6 votes vote down vote up
@Override
public void onMessage(String message) {
    try {
        session.sendMessage(new TextMessage(message));
    } catch (IOException e) {
        DefaultSystemLog.getLog().error("发送消息失败", e);
    }
    try {
        JSONObject jsonObject = JSONObject.parseObject(message);
        String reqId = jsonObject.getString("reqId");
        if (StrUtil.isNotEmpty(reqId)) {
            logController.updateLog(reqId, message);
        }
    } catch (Exception ignored) {
    }
}
 
Example 8
Source File: OutGivingController.java    From Jpom with MIT License 6 votes vote down vote up
@RequestMapping(value = "edit.html", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
@Feature(method = MethodFeature.EDIT)
public String edit(String id) {
    setAttribute("type", "add");
    if (StrUtil.isNotEmpty(id)) {
        OutGivingModel outGivingModel = outGivingServer.getItem(id);
        if (outGivingModel != null) {
            setAttribute("item", outGivingModel);
            setAttribute("type", "edit");
        }
    }
    UserModel userModel = getUser();

    List<NodeModel> nodeModels = nodeService.listAndProject();
    setAttribute("nodeModels", nodeModels);

    //
    String reqId = nodeService.cacheNodeList(nodeModels);
    setAttribute("reqId", reqId);

    JSONArray afterOpt = BaseEnum.toJSONArray(AfterOpt.class);
    setAttribute("afterOpt", afterOpt);
    return "outgiving/edit";
}
 
Example 9
Source File: StartedListener.java    From stone with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 加载主题设置
 */
private void loadActiveTheme() throws TemplateModelException {
    final String themeValue = optionsService.findOneOption(BlogPropertiesEnum.THEME.getProp());
    if (StrUtil.isNotEmpty(themeValue) && !StrUtil.equals(themeValue, null)) {
        BaseController.THEME = themeValue;
    } else {
        //以防万一
        BaseController.THEME = "anatole";
    }
    configuration.setSharedVariable("themeName", BaseController.THEME);
}
 
Example 10
Source File: AbstractProjectCommander.java    From Jpom with MIT License 5 votes vote down vote up
/**
 * 停止
 *
 * @param projectInfoModel 项目
 * @return 结果
 * @throws Exception 异常
 */
public String stop(ProjectInfoModel projectInfoModel, ProjectInfoModel.JavaCopyItem javaCopyItem) throws Exception {
    String tag = javaCopyItem == null ? projectInfoModel.getId() : javaCopyItem.getTagId();
    String token = projectInfoModel.getToken();
    if (StrUtil.isNotEmpty(token)) {
        try {
            HttpRequest httpRequest = HttpUtil.createGet(token)
                    .form("projectId", projectInfoModel.getId());
            if (javaCopyItem != null) {
                httpRequest.form("copyId", javaCopyItem.getId());
            }
            String body = httpRequest.execute().body();
            DefaultSystemLog.getLog().info(projectInfoModel.getName() + ":" + body);
        } catch (Exception e) {
            DefaultSystemLog.getLog().error("WebHooks 调用错误", e);
            return "WebHooks error:" + e.getMessage();
        }
    }
    // 再次查看进程信息
    String result = status(tag);
    //
    int pid = parsePid(result);
    if (pid > 0) {
        // 清空名称缓存
        PID_JPOM_NAME.remove(pid);
        // 端口号缓存
        PID_PORT.remove(pid);
    }
    return result;
}
 
Example 11
Source File: GoodsServiceImpl.java    From supplierShop with MIT License 5 votes vote down vote up
/**
 * 商品列表
 * @param cateId
 * @param page
 * @param limit
 * @param userId
 * @param keywords
 * @param order
 * @return
 */
@Override
public List<GoodsDTO> getList(int cateId, int page, int limit, int userId,
                              String keywords,int order) {

    QueryWrapper<StoreGoods> wrapper = new QueryWrapper<>();

    if(cateId > 0){
        wrapper.eq("cate_id",cateId);
    }
    if(StrUtil.isNotEmpty(keywords)){
        wrapper.like("goods_name",keywords);
    }

    //todo order = 1 推荐  order=2  新品
    switch (order){
        case 1:
            wrapper.eq("is_recommend",1);
            break;
        case 2:
            wrapper.eq("is_new",1);
            break;
    }
    Page<StoreGoods> pageModel = new Page<>(page, limit);

    IPage<StoreGoods> pageList = storeGoodsMapper.selectPage(pageModel,wrapper);

    List<GoodsDTO> list = goodsMapper.toDto(pageList.getRecords());

    for (GoodsDTO goodsDTO : list) {
        goodsDTO.setIsCollect(isCollect(goodsDTO.getGoodsId(),userId));
    }

    return list;
    //return null;
}
 
Example 12
Source File: IndexController.java    From pre with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 登录
 *
 * @param username
 * @param password
 * @return
 */
@RequestMapping(value = "/login")
public R login(String username, String password, HttpServletRequest request) {
    // 社交快速登录
    String token = request.getParameter("token");
    if (StrUtil.isNotEmpty(token)) {
        return R.ok(token);
    }
    return R.ok(userService.login(username, password));
}
 
Example 13
Source File: RequestStatisticsFilter.java    From microservices-platform with Apache License 2.0 5 votes vote down vote up
private String getBrowser(String browser) {
    if (StrUtil.isNotEmpty(browser)) {
        if (browser.contains("CHROME")) {
            return "CHROME";
        } else if (browser.contains("FIREFOX")) {
            return "FIREFOX";
        } else if (browser.contains("SAFARI")) {
            return "SAFARI";
        } else if (browser.contains("EDGE")) {
            return "EDGE";
        }
    }
    return browser;
}
 
Example 14
Source File: LoginLogService.java    From runscore with Apache License 2.0 5 votes vote down vote up
@Transactional(readOnly = true)
public PageResult<LoginLogVO> findLoginLogByPage(LoginLogQueryCondParam param) {
	Specification<LoginLog> spec = new Specification<LoginLog>() {
		/**
		 *
		 */
		private static final long serialVersionUID = 1L;

		public Predicate toPredicate(Root<LoginLog> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
			List<Predicate> predicates = new ArrayList<Predicate>();
			if (StrUtil.isNotEmpty(param.getIpAddr())) {
				predicates.add(builder.equal(root.get("ipAddr"), param.getIpAddr()));
			}
			if (StrUtil.isNotEmpty(param.getUserName())) {
				predicates.add(builder.equal(root.get("userName"), param.getUserName()));
			}
			if (StrUtil.isNotEmpty(param.getState())) {
				predicates.add(builder.equal(root.get("state"), param.getState()));
			}
			if (param.getStartTime() != null) {
				predicates.add(builder.greaterThanOrEqualTo(root.get("loginTime").as(Date.class),
						DateUtil.beginOfDay(param.getStartTime())));
			}
			if (param.getEndTime() != null) {
				predicates.add(builder.lessThanOrEqualTo(root.get("loginTime").as(Date.class),
						DateUtil.endOfDay(param.getEndTime())));
			}
			return predicates.size() > 0 ? builder.and(predicates.toArray(new Predicate[predicates.size()])) : null;
		}
	};
	Page<LoginLog> result = loginLogRepo.findAll(spec,
			PageRequest.of(param.getPageNum() - 1, param.getPageSize(), Sort.by(Sort.Order.desc("loginTime"))));
	PageResult<LoginLogVO> pageResult = new PageResult<>(LoginLogVO.convertFor(result.getContent()),
			param.getPageNum(), param.getPageSize(), result.getTotalElements());
	return pageResult;
}
 
Example 15
Source File: AggregationServiceImpl.java    From microservices-platform with Apache License 2.0 5 votes vote down vote up
/**
 * 2020-03-10 01:30:00 获取时间值:03-10 01:30
 * @return
 */
private String getTimeByDatetimeStr(String datetimeStr) {
    if (StrUtil.isNotEmpty(datetimeStr)) {
        return datetimeStr.substring(5, 16);
    }
    return "";
}
 
Example 16
Source File: UserRoleListController.java    From Jpom with MIT License 5 votes vote down vote up
@RequestMapping(value = "edit.html", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
@Feature(method = MethodFeature.EDIT)
public String edit(String id) {
    if (StrUtil.isNotEmpty(id)) {
        RoleModel item = roleService.getItem(id);
        setAttribute("item", item);
    }
    return "user/role/edit";
}
 
Example 17
Source File: StoreOrderController.java    From yshopmall with Apache License 2.0 4 votes vote down vote up
@ApiOperation(value = "查询订单")
@GetMapping(value = "/yxStoreOrder")
@PreAuthorize("@el.check('admin','YXSTOREORDER_ALL','YXSTOREORDER_SELECT')")
public ResponseEntity getYxStoreOrders(YxStoreOrderQueryCriteria criteria,
                                       Pageable pageable,
                                       @RequestParam(name = "orderStatus") String orderStatus,
                                       @RequestParam(name = "orderType") String orderType) {


    criteria.setShippingType(1);//默认查询所有快递订单
    //订单状态查询
    if (StrUtil.isNotEmpty(orderStatus)) {
        switch (orderStatus) {
            case "0":
                criteria.setIsDel(0);
                criteria.setPaid(0);
                criteria.setStatus(0);
                criteria.setRefundStatus(0);
                break;
            case "1":
                criteria.setIsDel(0);
                criteria.setPaid(1);
                criteria.setStatus(0);
                criteria.setRefundStatus(0);
                break;
            case "2":
                criteria.setIsDel(0);
                criteria.setPaid(1);
                criteria.setStatus(1);
                criteria.setRefundStatus(0);
                break;
            case "3":
                criteria.setIsDel(0);
                criteria.setPaid(1);
                criteria.setStatus(2);
                criteria.setRefundStatus(0);
                break;
            case "4":
                criteria.setIsDel(0);
                criteria.setPaid(1);
                criteria.setStatus(3);
                criteria.setRefundStatus(0);
                break;
            case "-1":
                criteria.setIsDel(0);
                criteria.setPaid(1);
                criteria.setRefundStatus(1);
                break;
            case "-2":
                criteria.setIsDel(0);
                criteria.setPaid(1);
                criteria.setRefundStatus(2);
                break;
            case "-4":
                criteria.setIsDel(1);
                break;
        }
    }
    //订单类型查询
    if (StrUtil.isNotEmpty(orderType)) {
        switch (orderType) {
            case "1":
                criteria.setBargainId(0);
                criteria.setCombinationId(0);
                criteria.setSeckillId(0);
                break;
            case "2":
                criteria.setNewCombinationId(0);
                break;
            case "3":
                criteria.setNewSeckillId(0);
                break;
            case "4":
                criteria.setNewBargainId(0);
                break;
            case "5":
                criteria.setShippingType(2);
                break;
        }
    }


    return new ResponseEntity(yxStoreOrderService.queryAll(criteria, pageable), HttpStatus.OK);
}
 
Example 18
Source File: ExcelUtil.java    From RuoYi with Apache License 2.0 4 votes vote down vote up
/**
 * 对excel表单指定表格索引名转换成list
 *
 * @param sheetName 表格索引名
 * @param input     输入流
 * @return 转换后集合
 */
private List<T> importExcel(String sheetName, InputStream input) {
    this.type = Excel.Type.IMPORT;
    List<T> list = new ArrayList<>();

    try (Workbook workbook = WorkbookFactory.create(input)) {
        this.workbook = workbook;
        Sheet sheet;
        if (StrUtil.isNotEmpty(sheetName)) {
            // 如果指定sheet名,则取指定sheet中的内容.
            sheet = workbook.getSheet(sheetName);
        } else {
            // 如果传入的sheet名不存在则默认指向第1个sheet.
            sheet = workbook.getSheetAt(0);
        }

        if (sheet == null) {
            throw new IOException("文件sheet不存在");
        }

        int rows = sheet.getPhysicalNumberOfRows();

        if (rows > 0) {
            // 定义一个map用于存放excel列的序号和field.
            Map<String, Integer> cellMap = new HashMap<>();
            //获取表头
            Row heard = sheet.getRow(0);
            for (int i = 0; i < heard.getPhysicalNumberOfCells(); i++) {
                Cell cell = heard.getCell(i);
                if (ObjectUtil.isNotNull(cell)) {
                    String value = Convert.toStr(this.getCellValue(heard, i));
                    cellMap.put(value, i);
                } else {
                    cellMap.put(null, i);
                }
            }

            // 有数据时才处理 得到类的所有field.
            Field[] allFields = clazz.getDeclaredFields();
            // 定义一个map用于存放列的序号和field.
            Map<Integer, Field> fieldsMap = new HashMap<>();
            for (Field field : allFields) {
                // 将有注解的field存放到map中.
                Excel attr = field.getAnnotation(Excel.class);
                boolean annotation = attr != null && (attr.type() == Excel.Type.ALL || attr.type() == type);
                if(annotation){
                    // 设置类的私有字段属性可访问.
                    field.setAccessible(true);
                    Integer column = cellMap.get(attr.name());
                    fieldsMap.put(column, field);
                }
            }
            this.getImportData(rows,fieldsMap);
        }
    } catch (InvalidFormatException | IOException | IllegalAccessException | InstantiationException e) {
        log.error(e.getMessage(), e);
    }
    return list;
}
 
Example 19
Source File: OutGivingProjectEditController.java    From Jpom with MIT License 4 votes vote down vote up
/**
 * 处理页面数据
 *
 * @param outGivingModel 分发实体
 * @param edit           是否为编辑模式
 * @return json
 */
private String doData(OutGivingModel outGivingModel, boolean edit) {
    outGivingModel.setName(getParameter("name"));
    if (StrUtil.isEmpty(outGivingModel.getName())) {
        return JsonMessage.getString(405, "分发名称不能为空");
    }
    String reqId = getParameter("reqId");
    List<NodeModel> nodeModelList = nodeService.getNodeModel(reqId);
    if (nodeModelList == null) {
        return JsonMessage.getString(401, "当前页面请求超时");
    }
    //
    String afterOpt = getParameter("afterOpt");
    AfterOpt afterOpt1 = BaseEnum.getEnum(AfterOpt.class, Convert.toInt(afterOpt, 0));
    if (afterOpt1 == null) {
        return JsonMessage.getString(400, "请选择分发后的操作");
    }
    outGivingModel.setAfterOpt(afterOpt1.getCode());
    Object object = getDefData(outGivingModel, edit);
    if (object instanceof String) {
        return object.toString();
    }
    JSONObject defData = (JSONObject) object;
    UserModel userModel = getUser();
    //
    List<OutGivingModel> outGivingModels = outGivingServer.list();
    List<OutGivingNodeProject> outGivingNodeProjects = new ArrayList<>();
    OutGivingNodeProject outGivingNodeProject;
    //
    Iterator<NodeModel> iterator = nodeModelList.iterator();
    Map<NodeModel, JSONObject> cache = new HashMap<>(nodeModelList.size());
    while (iterator.hasNext()) {
        NodeModel nodeModel = iterator.next();
        String add = getParameter("add_" + nodeModel.getId());
        if (!nodeModel.getId().equals(add)) {
            iterator.remove();
            continue;
        }
        // 判断项目是否已经被使用过啦
        if (outGivingModels != null) {
            for (OutGivingModel outGivingModel1 : outGivingModels) {
                if (outGivingModel1.getId().equalsIgnoreCase(outGivingModel.getId())) {
                    continue;
                }
                if (outGivingModel1.checkContains(nodeModel.getId(), outGivingModel.getId())) {
                    return JsonMessage.getString(405, "已经存在相同的分发项目:" + outGivingModel.getId());
                }
            }
        }
        outGivingNodeProject = outGivingModel.getNodeProject(nodeModel.getId(), outGivingModel.getId());
        if (outGivingNodeProject == null) {
            outGivingNodeProject = new OutGivingNodeProject();
        }
        outGivingNodeProject.setNodeId(nodeModel.getId());
        outGivingNodeProject.setProjectId(outGivingModel.getId());
        outGivingNodeProjects.add(outGivingNodeProject);
        // 检查数据
        JSONObject allData = (JSONObject) defData.clone();
        String token = getParameter(StrUtil.format("{}_token", nodeModel.getId()));
        allData.put("token", token);
        String jvm = getParameter(StrUtil.format("{}_jvm", nodeModel.getId()));
        allData.put("jvm", jvm);
        String args = getParameter(StrUtil.format("{}_args", nodeModel.getId()));
        allData.put("args", args);
        // 项目副本
        String javaCopyIds = getParameter(StrUtil.format("{}_javaCopyIds", nodeModel.getId()));
        allData.put("javaCopyIds", javaCopyIds);
        if (StrUtil.isNotEmpty(javaCopyIds)) {
            String[] split = StrUtil.split(javaCopyIds, StrUtil.COMMA);
            for (String copyId : split) {
                String copyJvm = getParameter(StrUtil.format("{}_jvm_{}", nodeModel.getId(), copyId));
                String copyArgs = getParameter(StrUtil.format("{}_args_{}", nodeModel.getId(), copyId));
                allData.put("jvm_" + copyId, copyJvm);
                allData.put("args_" + copyId, copyArgs);
            }
        }
        JsonMessage<String> jsonMessage = sendData(nodeModel, userModel, allData, false);
        if (jsonMessage.getCode() != HttpStatus.HTTP_OK) {
            return JsonMessage.getString(406, nodeModel.getName() + "节点失败:" + jsonMessage.getMsg());
        }
        cache.put(nodeModel, allData);
    }
    // 删除已经删除的项目
    String error = deleteProject(outGivingModel, outGivingNodeProjects, userModel);
    if (error != null) {
        return error;
    }
    outGivingModel.setOutGivingNodeProjectList(outGivingNodeProjects);
    outGivingModel.setTempCacheMap(cache);
    return null;
}
 
Example 20
Source File: AdminController.java    From blog-sharon with Apache License 2.0 4 votes vote down vote up
/**
 * Markdown 导入
 *
 * @param file    file
 * @param request request
 * @return JsonResult
 */
@PostMapping(value = "/tools/markdownImport")
@ResponseBody
public JsonResult markdownImport(@RequestParam("file") MultipartFile file,
                                 HttpServletRequest request,
                                 HttpSession session) throws IOException {
    User user = (User) session.getAttribute(HaloConst.USER_SESSION_KEY);
    String markdown = IoUtil.read(file.getInputStream(), "UTF-8");
    String content = MarkdownUtils.renderMarkdown(markdown);
    Map<String, List<String>> frontMatters = MarkdownUtils.getFrontMatter(markdown);
    Post post = new Post();
    List<String> elementValue = null;
    List<Tag> tags = new ArrayList<>();
    List<Category> categories = new ArrayList<>();
    Tag tag = null;
    Category category = null;
    if (frontMatters.size() > 0) {
        for (String key : frontMatters.keySet()) {
            elementValue = frontMatters.get(key);
            for (String ele : elementValue) {
                if ("title".equals(key)) {
                    post.setPostTitle(ele);
                } else if ("date".equals(key)) {
                    post.setPostDate(DateUtil.parse(ele));
                } else if ("updated".equals(key)) {
                    post.setPostUpdate(DateUtil.parse(ele));
                } else if ("tags".equals(key)) {
                    tag = tagService.findTagByTagName(ele);
                    if (null == tag) {
                        tag = new Tag();
                        tag.setTagName(ele);
                        tag.setTagUrl(ele);
                        tag = tagService.save(tag);
                    }
                    tags.add(tag);
                } else if ("categories".equals(key)) {
                    category = categoryService.findByCateName(ele);
                    if (null == category) {
                        category = new Category();
                        category.setCateName(ele);
                        category.setCateUrl(ele);
                        category.setCateDesc(ele);
                        category = categoryService.save(category);
                    }
                    categories.add(category);
                }
            }
        }
    } else {
        post.setPostDate(new Date());
        post.setPostUpdate(new Date());
        post.setPostTitle(file.getOriginalFilename());
    }
    post.setPostContentMd(markdown);
    post.setPostContent(content);
    post.setPostType(PostTypeEnum.POST_TYPE_POST.getDesc());
    post.setAllowComment(AllowCommentEnum.ALLOW.getCode());
    post.setUser(user);
    post.setTags(tags);
    post.setCategories(categories);
    post.setPostUrl(StrUtil.removeSuffix(file.getOriginalFilename(), ".md"));
    int postSummary = 50;
    if (StrUtil.isNotEmpty(HaloConst.OPTIONS.get(BlogPropertiesEnum.POST_SUMMARY.getProp()))) {
        postSummary = Integer.parseInt(HaloConst.OPTIONS.get(BlogPropertiesEnum.POST_SUMMARY.getProp()));
    }
    String summaryText = StrUtil.cleanBlank(HtmlUtil.cleanHtmlTag(post.getPostContent()));
    if (summaryText.length() > postSummary) {
        String summary = summaryText.substring(0, postSummary);
        post.setPostSummary(summary);
    } else {
        post.setPostSummary(summaryText);
    }
    if (null == post.getPostDate()) {
        post.setPostDate(new Date());
    }
    if (null == post.getPostUpdate()) {
        post.setPostUpdate(new Date());
    }
    postService.save(post);
    return new JsonResult(ResultCodeEnum.SUCCESS.getCode());
}