模块化拆分
This commit is contained in:
@@ -0,0 +1,163 @@
|
||||
package cn.celess.article.controller;
|
||||
|
||||
import cn.celess.article.util.SitemapGenerateUtil;
|
||||
import cn.celess.common.enmu.ResponseEnum;
|
||||
import cn.celess.common.entity.Response;
|
||||
import cn.celess.common.entity.dto.ArticleReq;
|
||||
import cn.celess.common.entity.vo.ArticleModel;
|
||||
import cn.celess.common.service.ArticleService;
|
||||
import cn.celess.user.util.RedisUserUtil;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
/**
|
||||
* @author : xiaohai
|
||||
* @date : 2019/03/28 15:18
|
||||
*/
|
||||
@RestController
|
||||
public class ArticleController {
|
||||
@Autowired
|
||||
ArticleService articleService;
|
||||
@Autowired
|
||||
SitemapGenerateUtil sitemapGenerateUtil;
|
||||
@Autowired
|
||||
RedisUserUtil redisUserUtil;
|
||||
@Value("${spring.profiles.active}")
|
||||
private String activeModel;
|
||||
|
||||
/**
|
||||
* 新建一篇文章
|
||||
*
|
||||
* @param body 请求数据
|
||||
* @return Response
|
||||
*/
|
||||
@PostMapping("/admin/article/create")
|
||||
public Response create(@RequestBody ArticleReq body) {
|
||||
ArticleModel articleModel = articleService.create(body);
|
||||
if ("prod".equals(activeModel)) {
|
||||
sitemapGenerateUtil.createSitemap();
|
||||
}
|
||||
return Response.success(articleModel);
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过文章id 删除一篇文章
|
||||
*
|
||||
* @param articleId 文章id
|
||||
* @return Response
|
||||
*/
|
||||
@DeleteMapping("/admin/article/del")
|
||||
public Response delete(@RequestParam("articleID") long articleId) {
|
||||
boolean delete = articleService.delete(articleId);
|
||||
if ("prod".equals(activeModel)) {
|
||||
sitemapGenerateUtil.createSitemap();
|
||||
}
|
||||
return Response.success(delete);
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新文章
|
||||
*
|
||||
* @param body 请求数据
|
||||
* @return Response
|
||||
*/
|
||||
@PutMapping("/admin/article/update")
|
||||
public Response update(@RequestBody ArticleReq body) {
|
||||
ArticleModel update = articleService.update(body);
|
||||
if ("prod".equals(activeModel)) {
|
||||
sitemapGenerateUtil.createSitemap();
|
||||
}
|
||||
return Response.success(update);
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过id查找一篇文章
|
||||
* 公开 =>返回数据
|
||||
* 不公开
|
||||
* *** =>作者 返回数据
|
||||
* *** =>其他 抛出错误
|
||||
*
|
||||
* @param articleId 文章id
|
||||
* @param is4update 是否是更新
|
||||
* @return Response
|
||||
*/
|
||||
@GetMapping("/article/articleID/{articleID}")
|
||||
public Response retrieveOneById(@PathVariable("articleID") long articleId,
|
||||
@RequestParam(value = "update", defaultValue = "false") boolean is4update,
|
||||
HttpServletRequest request) {
|
||||
ArticleModel article = articleService.retrieveOneById(articleId, is4update);
|
||||
if (article.getOpen()) {
|
||||
return Response.success(article);
|
||||
} else if (article.getAuthor().getId().equals(redisUserUtil.get().getId())) {
|
||||
return Response.success(article);
|
||||
}
|
||||
return Response.response(ResponseEnum.PERMISSION_ERROR, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页获取所有文章状态为开放的的文章
|
||||
*
|
||||
* @param page 页码
|
||||
* @param count 单页数据量
|
||||
* @return Response
|
||||
*/
|
||||
@GetMapping("/articles")
|
||||
public Response articles(@RequestParam(name = "page", defaultValue = "1") int page,
|
||||
@RequestParam(name = "count", defaultValue = "5") int count) {
|
||||
return Response.success(articleService.retrievePageForOpen(count, page));
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页获取所有文章
|
||||
*
|
||||
* @param page 页码
|
||||
* @param count 单页数据量
|
||||
* @return Response
|
||||
*/
|
||||
@GetMapping("/admin/articles")
|
||||
public Response adminArticles(@RequestParam(name = "page", defaultValue = "1") int page,
|
||||
@RequestParam(name = "count", defaultValue = "10") int count,
|
||||
@RequestParam(name = "deleted", required = false) Boolean deleted) {
|
||||
return Response.success(articleService.adminArticles(count, page, deleted));
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过分类获取文章(文章摘要)
|
||||
*
|
||||
* @param name 分类名
|
||||
* @param page 页码
|
||||
* @param count 单页数据量
|
||||
* @return Response
|
||||
*/
|
||||
@GetMapping("/articles/category/{name}")
|
||||
public Response findByCategory(@PathVariable("name") String name,
|
||||
@RequestParam(name = "page", defaultValue = "1") int page,
|
||||
@RequestParam(name = "count", defaultValue = "10") int count) {
|
||||
return Response.success(articleService.findByCategory(name, page, count));
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过标签名获取文章(文章摘要)
|
||||
*
|
||||
* @param name 标签名
|
||||
* @param page 页码
|
||||
* @param count 单页数据量
|
||||
* @return Response
|
||||
*/
|
||||
@GetMapping("/articles/tag/{name}")
|
||||
public Response findByTag(@PathVariable("name") String name,
|
||||
@RequestParam(name = "page", defaultValue = "1") int page,
|
||||
@RequestParam(name = "count", defaultValue = "10") int count) {
|
||||
return Response.success(articleService.findByTag(name, page, count));
|
||||
}
|
||||
|
||||
|
||||
@GetMapping("/createSitemap")
|
||||
public Response createSitemap() {
|
||||
sitemapGenerateUtil.createSitemap();
|
||||
return Response.success(null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,367 @@
|
||||
package cn.celess.article.serviceimpl;
|
||||
|
||||
import cn.celess.common.enmu.ResponseEnum;
|
||||
import cn.celess.common.enmu.RoleEnum;
|
||||
import cn.celess.common.entity.*;
|
||||
import cn.celess.common.entity.dto.ArticleReq;
|
||||
import cn.celess.common.entity.vo.ArticleModel;
|
||||
import cn.celess.common.entity.vo.PageData;
|
||||
import cn.celess.common.exception.MyException;
|
||||
import cn.celess.common.mapper.*;
|
||||
import cn.celess.common.service.ArticleService;
|
||||
import cn.celess.common.service.UserService;
|
||||
import cn.celess.common.util.ModalTrans;
|
||||
import cn.celess.common.util.RegexUtil;
|
||||
import cn.celess.common.util.StringFromHtmlUtil;
|
||||
import cn.celess.user.util.RedisUserUtil;
|
||||
import com.github.pagehelper.PageHelper;
|
||||
import com.github.pagehelper.PageInfo;
|
||||
import com.youbenzi.mdtool.tool.MDTool;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.BeanUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.cache.annotation.Cacheable;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
|
||||
/**
|
||||
* @author : xiaohai
|
||||
* @date : 2019/03/28 15:21
|
||||
*/
|
||||
@Service
|
||||
@Slf4j
|
||||
public class ArticleServiceImpl implements ArticleService {
|
||||
|
||||
@Autowired
|
||||
ArticleMapper articleMapper;
|
||||
|
||||
@Autowired
|
||||
TagMapper tagMapper;
|
||||
@Autowired
|
||||
CategoryMapper categoryMapper;
|
||||
@Autowired
|
||||
CommentMapper commentMapper;
|
||||
@Autowired
|
||||
ArticleTagMapper articleTagMapper;
|
||||
@Autowired
|
||||
UserService userService;
|
||||
@Autowired
|
||||
HttpServletRequest request;
|
||||
@Autowired
|
||||
RedisUserUtil redisUserUtil;
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public ArticleModel create(ArticleReq reqBody) {
|
||||
if (reqBody == null) {
|
||||
throw new MyException(ResponseEnum.PARAMETERS_ERROR);
|
||||
}
|
||||
//数据判断
|
||||
if (reqBody.getTitle() == null || reqBody.getTitle().replaceAll(" ", "").isEmpty()) {
|
||||
throw new MyException(ResponseEnum.PARAMETERS_ERROR);
|
||||
} else if (reqBody.getMdContent() == null || reqBody.getMdContent().replaceAll(" ", "").isEmpty()) {
|
||||
throw new MyException(ResponseEnum.PARAMETERS_ERROR);
|
||||
}
|
||||
//转载 判断链接
|
||||
if (!reqBody.getType()) {
|
||||
if (reqBody.getUrl() == null || reqBody.getUrl().replaceAll(" ", "").isEmpty()) {
|
||||
throw new MyException(ResponseEnum.PARAMETERS_ERROR);
|
||||
} else if (!RegexUtil.urlMatch(reqBody.getUrl())) {
|
||||
throw new MyException(ResponseEnum.PARAMETERS_URL_ERROR);
|
||||
}
|
||||
}
|
||||
if (reqBody.getCategory() == null || reqBody.getCategory().replaceAll(" ", "").isEmpty()) {
|
||||
throw new MyException(ResponseEnum.PARAMETERS_ERROR);
|
||||
}
|
||||
if (reqBody.getTags() == null || reqBody.getTags().length == 0) {
|
||||
throw new MyException(ResponseEnum.PARAMETERS_ERROR);
|
||||
}
|
||||
if (articleMapper.existsByTitle(reqBody.getTitle())) {
|
||||
throw new MyException(ResponseEnum.ARTICLE_HAS_EXIST);
|
||||
}
|
||||
// 查看是否存在已有的分类
|
||||
Category category = categoryMapper.findCategoryByName(reqBody.getCategory());
|
||||
if (category == null) {
|
||||
throw new MyException(ResponseEnum.CATEGORY_NOT_EXIST);
|
||||
}
|
||||
|
||||
// 构建 需要写入数据库的对象数据
|
||||
Article article = new Article();
|
||||
BeanUtils.copyProperties(reqBody, article);
|
||||
|
||||
article.setUser(redisUserUtil.get());
|
||||
|
||||
//markdown->html->summary
|
||||
String str = StringFromHtmlUtil.getString(MDTool.markdown2Html(article.getMdContent()));
|
||||
//获取摘要 摘要长度为255个字符
|
||||
String summary = str.length() > 240 ? str.substring(0, 240) + "......" : str;
|
||||
article.setSummary(summary);
|
||||
|
||||
article.setCategory(category);
|
||||
|
||||
//文章存数据库
|
||||
articleMapper.insert(article);
|
||||
//将标签写入数据库
|
||||
for (String tagName : reqBody.getTags()) {
|
||||
if (tagName.replaceAll(" ", "").length() == 0) {
|
||||
//单个标签只含空格
|
||||
continue;
|
||||
}
|
||||
Tag tag = tagMapper.findTagByName(tagName);
|
||||
if (tag == null) {
|
||||
tag = new Tag();
|
||||
tag.setName(tagName);
|
||||
tagMapper.insert(tag);
|
||||
}
|
||||
ArticleTag articleTag = new ArticleTag(article, tag);
|
||||
articleTagMapper.insert(articleTag);
|
||||
}
|
||||
Article articleFromDb = articleMapper.findArticleById(article.getId());
|
||||
|
||||
ArticleModel articleModel = ModalTrans.article(articleFromDb);
|
||||
articleModel.setPreArticle(ModalTrans.article(articleMapper.getPreArticle(article.getId()), true));
|
||||
return articleModel;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public boolean delete(long articleId) {
|
||||
Article articleForDel = articleMapper.findArticleById(articleId);
|
||||
|
||||
if (articleForDel == null) {
|
||||
//文章不存在
|
||||
throw new MyException(ResponseEnum.ARTICLE_NOT_EXIST);
|
||||
}
|
||||
|
||||
//对访问情况进行判断 非admin 权限不可删除文章
|
||||
User user = redisUserUtil.get();
|
||||
if (!RoleEnum.ADMIN_ROLE.getRoleName().equals(user.getRole())) {
|
||||
throw new MyException(ResponseEnum.PERMISSION_ERROR);
|
||||
}
|
||||
//删除指定文章
|
||||
articleMapper.delete(articleId);
|
||||
|
||||
//articleTagMapper.deleteByArticleId(articleId);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
@Override
|
||||
public ArticleModel update(ArticleReq reqBody) {
|
||||
if (reqBody == null || reqBody.getId() == null) {
|
||||
throw new MyException(ResponseEnum.PARAMETERS_ERROR);
|
||||
}
|
||||
// 查找数据
|
||||
Article article = articleMapper.findArticleById(reqBody.getId());
|
||||
|
||||
//数据判断
|
||||
if (reqBody.getTitle() != null && !reqBody.getTitle().replaceAll(" ", "").isEmpty()) {
|
||||
if (!article.getTitle().equals(reqBody.getTitle()) && articleMapper.existsByTitle(reqBody.getTitle())) {
|
||||
throw new MyException(ResponseEnum.ARTICLE_HAS_EXIST);
|
||||
}
|
||||
article.setTitle(reqBody.getTitle());
|
||||
}
|
||||
if (reqBody.getMdContent() != null && !reqBody.getMdContent().replaceAll(" ", "").isEmpty()) {
|
||||
article.setMdContent(reqBody.getMdContent());
|
||||
}
|
||||
|
||||
//转载 判断链接
|
||||
if (reqBody.getType() != null) {
|
||||
if (!reqBody.getType() && reqBody.getUrl() == null) {
|
||||
throw new MyException(ResponseEnum.PARAMETERS_ERROR);
|
||||
}
|
||||
|
||||
if (!reqBody.getType() && !RegexUtil.urlMatch(reqBody.getUrl())) {
|
||||
throw new MyException(ResponseEnum.PARAMETERS_URL_ERROR);
|
||||
}
|
||||
article.setType(reqBody.getType());
|
||||
article.setUrl(reqBody.getUrl());
|
||||
}
|
||||
if (reqBody.getCategory() != null && !reqBody.getCategory().replaceAll(" ", "").isEmpty()) {
|
||||
Category category = categoryMapper.findCategoryByName(reqBody.getCategory());
|
||||
if (category == null) {
|
||||
category = new Category();
|
||||
category.setName(reqBody.getCategory());
|
||||
categoryMapper.insert(category);
|
||||
}
|
||||
article.setCategory(category);
|
||||
}
|
||||
|
||||
//写入数据库的数据
|
||||
article.setOpen(reqBody.getOpen() == null ? article.getOpen() : reqBody.getOpen());
|
||||
String str = StringFromHtmlUtil.getString(MDTool.markdown2Html(article.getMdContent()));
|
||||
article.setSummary(str.length() > 240 ? str.substring(0, 240) + "......" : str);
|
||||
articleMapper.update(article);
|
||||
|
||||
|
||||
List<ArticleTag> allByArticleId = articleTagMapper.findAllByArticleId(article.getId());
|
||||
List<ArticleTag> updateList = new ArrayList<>();
|
||||
List<ArticleTag> deleteList = new ArrayList<>();
|
||||
|
||||
// 获取要更新 的标签
|
||||
for (String tag : reqBody.getTags()) {
|
||||
boolean contain = allByArticleId.stream().anyMatch(articleTag -> articleTag.getTag().getName().equals(tag));
|
||||
if (!contain) {
|
||||
ArticleTag articleTag = new ArticleTag();
|
||||
articleTag.setArticle(article);
|
||||
Tag tagByName = tagMapper.findTagByName(tag);
|
||||
if (tagByName == null) {
|
||||
tagByName = new Tag(tag);
|
||||
tagMapper.insert(tagByName);
|
||||
}
|
||||
articleTag.setTag(tagByName);
|
||||
updateList.add(articleTag);
|
||||
}
|
||||
}
|
||||
// 获取要删除的标签
|
||||
allByArticleId.forEach(articleTag -> {
|
||||
boolean contain = false;
|
||||
for (String tag : reqBody.getTags()) {
|
||||
if (articleTag.getTag().getName().equals(tag)) {
|
||||
contain = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!contain) {
|
||||
deleteList.add(articleTag);
|
||||
}
|
||||
});
|
||||
|
||||
if (updateList.size() != 0) {
|
||||
updateList.forEach(articleTag -> articleTagMapper.insert(articleTag));
|
||||
}
|
||||
|
||||
if (deleteList.size() != 0) {
|
||||
articleTagMapper.deleteMultiById(deleteList);
|
||||
}
|
||||
|
||||
//更新完成移除
|
||||
request.getSession().removeAttribute("article4update");
|
||||
ArticleModel articleModel = ModalTrans.article(articleMapper.findArticleById(article.getId()));
|
||||
setPreAndNextArticle(articleModel);
|
||||
return articleModel;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Cacheable(value = {"article"}, key = "'retrieveOneById'+#articleId")
|
||||
public ArticleModel retrieveOneById(long articleId, boolean is4update) {
|
||||
Article article = articleMapper.findArticleById(articleId);
|
||||
if (article == null) {
|
||||
throw new MyException(ResponseEnum.ARTICLE_NOT_EXIST);
|
||||
}
|
||||
if (!article.getOpen()) {
|
||||
User user = redisUserUtil.getWithOutExc();
|
||||
if (user == null || "user".equals(user.getRole())) {
|
||||
throw new MyException(ResponseEnum.ARTICLE_NOT_PUBLIC);
|
||||
}
|
||||
}
|
||||
ArticleModel articleModel = ModalTrans.article(article);
|
||||
|
||||
if (is4update) {
|
||||
//因更新而获取文章 不需要增加阅读量
|
||||
request.getSession().setAttribute("article4update", article);
|
||||
return articleModel;
|
||||
}
|
||||
setPreAndNextArticle(articleModel);
|
||||
articleMapper.updateReadingNumber(articleId);
|
||||
return articleModel;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param count 数目
|
||||
* @param page 页面
|
||||
* @return PageInfo
|
||||
*/
|
||||
@Override
|
||||
public PageData<ArticleModel> adminArticles(int count, int page, Boolean deleted) {
|
||||
PageHelper.startPage(page, count);
|
||||
List<Article> articleList = articleMapper.findAll();
|
||||
|
||||
PageData<ArticleModel> pageData = new PageData<>(new PageInfo<>(articleList));
|
||||
|
||||
List<Article> collect;
|
||||
if (deleted != null) {
|
||||
collect = articleList.stream().filter(article -> article.isDeleted() == deleted).collect(Collectors.toList());
|
||||
} else {
|
||||
collect = articleList;
|
||||
}
|
||||
List<ArticleModel> articleModels = collect.stream()
|
||||
.peek(article -> article.setMdContent(null))
|
||||
.map(ModalTrans::article)
|
||||
.collect(Collectors.toList());
|
||||
pageData.setList(articleModels);
|
||||
|
||||
return pageData;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Cacheable(value = {"article"}, key = "'retrievePageForOpen:'+#page+':'+#count")
|
||||
public PageData<ArticleModel> retrievePageForOpen(int count, int page) {
|
||||
PageHelper.startPage(page, count);
|
||||
List<Article> articleList = articleMapper.findAllByOpen(true);
|
||||
PageData<ArticleModel> pageData = new PageData<>(new PageInfo<>(articleList));
|
||||
|
||||
List<ArticleModel> articleModelList = articleList
|
||||
.stream()
|
||||
.map(article -> setPreAndNextArticle(ModalTrans.article(article, true)))
|
||||
.collect(Collectors.toList());
|
||||
pageData.setList(articleModelList);
|
||||
return pageData;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Cacheable(value = {"article"}, key = "'findByCategory:'+#name")
|
||||
public PageData<ArticleModel> findByCategory(String name, int page, int count) {
|
||||
Category category = categoryMapper.findCategoryByName(name);
|
||||
if (category == null) {
|
||||
throw new MyException(ResponseEnum.CATEGORY_NOT_EXIST);
|
||||
}
|
||||
PageHelper.startPage(page, count);
|
||||
List<Article> open = articleMapper.findAllByCategoryIdAndOpen(category.getId());
|
||||
|
||||
List<ArticleModel> modelList = open.stream()
|
||||
.map(article -> ModalTrans.article(article, true))
|
||||
.peek(articleModel -> {
|
||||
articleModel.setNextArticle(null);
|
||||
articleModel.setPreArticle(null);
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
return new PageData<>(new PageInfo<>(open), modelList);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Cacheable(value = {"article"}, key = "'findByTag:'+#name")
|
||||
public PageData<ArticleModel> findByTag(String name, int page, int count) {
|
||||
Tag tag = tagMapper.findTagByName(name);
|
||||
if (tag == null) {
|
||||
throw new MyException(ResponseEnum.TAG_NOT_EXIST);
|
||||
}
|
||||
PageHelper.startPage(page, count);
|
||||
List<ArticleTag> articleByTag = articleTagMapper.findArticleByTagAndOpen(tag.getId());
|
||||
List<ArticleModel> modelList = articleByTag
|
||||
.stream()
|
||||
.map(articleTag -> ModalTrans.article(articleTag.getArticle(), true))
|
||||
.peek(articleModel -> {
|
||||
articleModel.setNextArticle(null);
|
||||
articleModel.setPreArticle(null);
|
||||
}).collect(Collectors.toList());
|
||||
return new PageData<>(new PageInfo<>(articleByTag), modelList);
|
||||
}
|
||||
|
||||
|
||||
private ArticleModel setPreAndNextArticle(ArticleModel articleModel) {
|
||||
if (articleModel == null) {
|
||||
return null;
|
||||
}
|
||||
articleModel.setPreArticle(ModalTrans.article(articleMapper.getPreArticle(articleModel.getId()), true));
|
||||
articleModel.setNextArticle(ModalTrans.article(articleMapper.getNextArticle(articleModel.getId()), true));
|
||||
return articleModel;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package cn.celess.article.util;
|
||||
|
||||
|
||||
import cn.celess.common.entity.Article;
|
||||
import cn.celess.common.mapper.ArticleMapper;
|
||||
import cn.celess.common.util.DateFormatUtil;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.scheduling.annotation.Async;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
import javax.xml.parsers.DocumentBuilder;
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
import javax.xml.parsers.ParserConfigurationException;
|
||||
import javax.xml.transform.OutputKeys;
|
||||
import javax.xml.transform.Transformer;
|
||||
import javax.xml.transform.TransformerException;
|
||||
import javax.xml.transform.TransformerFactory;
|
||||
import javax.xml.transform.dom.DOMSource;
|
||||
import javax.xml.transform.stream.StreamResult;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* @Author: 小海
|
||||
* @Date: 2019/07/30 17:29
|
||||
* @Description:
|
||||
*/
|
||||
@Component
|
||||
public class SitemapGenerateUtil {
|
||||
|
||||
@Autowired
|
||||
ArticleMapper articleMapper;
|
||||
|
||||
@Value("${sitemap.path}")
|
||||
private String path;
|
||||
private Map<String, String> urlList;
|
||||
|
||||
private static DocumentBuilder getDocumentBuilder() {
|
||||
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
|
||||
DocumentBuilder db = null;
|
||||
try {
|
||||
db = dbf.newDocumentBuilder();
|
||||
} catch (ParserConfigurationException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return db;
|
||||
}
|
||||
|
||||
@Async
|
||||
public void createSitemap() {
|
||||
initList();
|
||||
if ("".equals(path) || "classpath".equals(path)) {
|
||||
path = System.getProperty("user.dir") + "/sitemap.xml";
|
||||
}
|
||||
File file = new File(path);
|
||||
try {
|
||||
if (file.exists()) {
|
||||
file.delete();
|
||||
} else {
|
||||
file.createNewFile();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
DocumentBuilder db = getDocumentBuilder();
|
||||
Document document = db.newDocument();
|
||||
document.setXmlVersion("1.0");
|
||||
document.setXmlStandalone(true);
|
||||
Element urlset = document.createElement("urlset");
|
||||
urlset.setAttribute("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9");
|
||||
// 创建url 结点
|
||||
urlList.forEach((s, s2) -> {
|
||||
Element url = document.createElement("url");
|
||||
Element loc = document.createElement("loc");
|
||||
Element lastmod = document.createElement("lastmod");
|
||||
loc.setTextContent(s);
|
||||
lastmod.setTextContent(s2);
|
||||
url.appendChild(loc);
|
||||
url.appendChild(lastmod);
|
||||
urlset.appendChild(url);
|
||||
});
|
||||
document.appendChild(urlset);
|
||||
try {
|
||||
TransformerFactory tff = TransformerFactory.newInstance();
|
||||
Transformer tf = tff.newTransformer();
|
||||
tf.setOutputProperty(OutputKeys.INDENT, "yes");
|
||||
tf.transform(new DOMSource(document), new StreamResult(file));
|
||||
} catch (TransformerException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
private void initList() {
|
||||
urlList = new HashMap<>();
|
||||
urlList.put("https://www.celess.cn", DateFormatUtil.getForXmlDate(new Date()));
|
||||
urlList.put("https://www.celess.cn/links", DateFormatUtil.getForXmlDate(new Date()));
|
||||
urlList.put("https://www.celess.cn/leaveMsg", DateFormatUtil.getForXmlDate(new Date()));
|
||||
List<Article> articles = articleMapper.findAll().stream().filter(article -> article.getOpen() && !article.isDeleted()).collect(Collectors.toList());
|
||||
articles.forEach(article -> {
|
||||
urlList.put("https://www.celess.cn/article/" + article.getId(), DateFormatUtil.getForXmlDate(
|
||||
article.getUpdateDate() == null ? article.getPublishDate() : article.getUpdateDate()));
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user