diff --git a/.gitignore b/.gitignore index e0d65e1..21fcf12 100644 --- a/.gitignore +++ b/.gitignore @@ -4,5 +4,5 @@ target/ # 本地项目的私有文件 -src/main/resources/application-dev.properties +blog-deploy/src/main/resources/application-dev.properties src/main/resources/application-prod.properties diff --git a/blog-article/pom.xml b/blog-article/pom.xml new file mode 100644 index 0000000..9efdded --- /dev/null +++ b/blog-article/pom.xml @@ -0,0 +1,50 @@ + + + + blog + cn.celess + 0.0.1-SNAPSHOT + + 4.0.0 + + blog-article + + + 13 + 13 + + + + + cn.celess + blog-common + ${blog-common.version} + + + + cn.celess + blog-user + ${blog-user.version} + + + + org.springframework.boot + spring-boot-starter-web + + + + + com.youbenzi + MDTool + 1.2.4 + + + net.minidev + json-smart + 2.4.7 + compile + + + \ No newline at end of file diff --git a/src/main/java/cn/celess/blog/controller/ArticleController.java b/blog-article/src/main/java/cn/celess/article/controller/ArticleController.java similarity index 90% rename from src/main/java/cn/celess/blog/controller/ArticleController.java rename to blog-article/src/main/java/cn/celess/article/controller/ArticleController.java index 80fd4cc..f02d51a 100644 --- a/src/main/java/cn/celess/blog/controller/ArticleController.java +++ b/blog-article/src/main/java/cn/celess/article/controller/ArticleController.java @@ -1,163 +1,163 @@ -package cn.celess.blog.controller; - -import cn.celess.blog.enmu.ResponseEnum; -import cn.celess.blog.entity.Response; -import cn.celess.blog.entity.model.ArticleModel; -import cn.celess.blog.entity.request.ArticleReq; -import cn.celess.blog.service.ArticleService; -import cn.celess.blog.util.RedisUserUtil; -import cn.celess.blog.util.SitemapGenerateUtil; -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); - } -} +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); + } +} diff --git a/src/main/java/cn/celess/blog/service/serviceimpl/ArticleServiceImpl.java b/blog-article/src/main/java/cn/celess/article/serviceimpl/ArticleServiceImpl.java similarity index 93% rename from src/main/java/cn/celess/blog/service/serviceimpl/ArticleServiceImpl.java rename to blog-article/src/main/java/cn/celess/article/serviceimpl/ArticleServiceImpl.java index 247c971..db3923b 100644 --- a/src/main/java/cn/celess/blog/service/serviceimpl/ArticleServiceImpl.java +++ b/blog-article/src/main/java/cn/celess/article/serviceimpl/ArticleServiceImpl.java @@ -1,361 +1,367 @@ -package cn.celess.blog.service.serviceimpl; - -import cn.celess.blog.enmu.ResponseEnum; -import cn.celess.blog.enmu.RoleEnum; -import cn.celess.blog.entity.*; -import cn.celess.blog.entity.model.ArticleModel; -import cn.celess.blog.entity.model.PageData; -import cn.celess.blog.entity.request.ArticleReq; -import cn.celess.blog.exception.MyException; -import cn.celess.blog.mapper.*; -import cn.celess.blog.service.ArticleService; -import cn.celess.blog.service.UserService; -import cn.celess.blog.util.ModalTrans; -import cn.celess.blog.util.RedisUserUtil; -import cn.celess.blog.util.RegexUtil; -import cn.celess.blog.util.StringFromHtmlUtil; -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.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 allByArticleId = articleTagMapper.findAllByArticleId(article.getId()); - List updateList = new ArrayList<>(); - List 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 - 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 adminArticles(int count, int page, Boolean deleted) { - PageHelper.startPage(page, count); - List
articleList = articleMapper.findAll(); - - PageData pageData = new PageData<>(new PageInfo<>(articleList)); - - List
collect; - if (deleted != null) { - collect = articleList.stream().filter(article -> article.isDeleted() == deleted).collect(Collectors.toList()); - } else { - collect = articleList; - } - List articleModels = collect.stream() - .peek(article -> article.setMdContent(null)) - .map(ModalTrans::article) - .collect(Collectors.toList()); - pageData.setList(articleModels); - - return pageData; - } - - @Override - public PageData retrievePageForOpen(int count, int page) { - PageHelper.startPage(page, count); - List
articleList = articleMapper.findAllByOpen(true); - PageData pageData = new PageData<>(new PageInfo<>(articleList)); - - List articleModelList = articleList - .stream() - .map(article -> setPreAndNextArticle(ModalTrans.article(article, true))) - .collect(Collectors.toList()); - pageData.setList(articleModelList); - return pageData; - } - - @Override - public PageData 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
open = articleMapper.findAllByCategoryIdAndOpen(category.getId()); - - List 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 - public PageData 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 articleByTag = articleTagMapper.findArticleByTagAndOpen(tag.getId()); - List 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; - } -} +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 allByArticleId = articleTagMapper.findAllByArticleId(article.getId()); + List updateList = new ArrayList<>(); + List 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 adminArticles(int count, int page, Boolean deleted) { + PageHelper.startPage(page, count); + List
articleList = articleMapper.findAll(); + + PageData pageData = new PageData<>(new PageInfo<>(articleList)); + + List
collect; + if (deleted != null) { + collect = articleList.stream().filter(article -> article.isDeleted() == deleted).collect(Collectors.toList()); + } else { + collect = articleList; + } + List 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 retrievePageForOpen(int count, int page) { + PageHelper.startPage(page, count); + List
articleList = articleMapper.findAllByOpen(true); + PageData pageData = new PageData<>(new PageInfo<>(articleList)); + + List 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 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
open = articleMapper.findAllByCategoryIdAndOpen(category.getId()); + + List 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 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 articleByTag = articleTagMapper.findArticleByTagAndOpen(tag.getId()); + List 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; + } +} diff --git a/src/main/java/cn/celess/blog/util/SitemapGenerateUtil.java b/blog-article/src/main/java/cn/celess/article/util/SitemapGenerateUtil.java similarity index 92% rename from src/main/java/cn/celess/blog/util/SitemapGenerateUtil.java rename to blog-article/src/main/java/cn/celess/article/util/SitemapGenerateUtil.java index 27cedaa..7cb826d 100644 --- a/src/main/java/cn/celess/blog/util/SitemapGenerateUtil.java +++ b/blog-article/src/main/java/cn/celess/article/util/SitemapGenerateUtil.java @@ -1,111 +1,113 @@ -package cn.celess.blog.util; - -import cn.celess.blog.entity.Article; -import cn.celess.blog.mapper.ArticleMapper; -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 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
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())); - }); - } - -} - +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 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
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())); + }); + } + +} diff --git a/blog-categorytag/pom.xml b/blog-categorytag/pom.xml new file mode 100644 index 0000000..0cea345 --- /dev/null +++ b/blog-categorytag/pom.xml @@ -0,0 +1,31 @@ + + + + blog + cn.celess + 0.0.1-SNAPSHOT + + 4.0.0 + + blog-categorytag + + + 13 + 13 + + + + cn.celess + blog-common + ${blog-common.version} + + + + org.springframework.boot + spring-boot-starter-web + + + + \ No newline at end of file diff --git a/src/main/java/cn/celess/blog/controller/CategoryController.java b/blog-categorytag/src/main/java/cn/celess/categorytag/controller/CategoryController.java similarity index 89% rename from src/main/java/cn/celess/blog/controller/CategoryController.java rename to blog-categorytag/src/main/java/cn/celess/categorytag/controller/CategoryController.java index 08f2791..6456e10 100644 --- a/src/main/java/cn/celess/blog/controller/CategoryController.java +++ b/blog-categorytag/src/main/java/cn/celess/categorytag/controller/CategoryController.java @@ -1,63 +1,63 @@ -package cn.celess.blog.controller; - -import cn.celess.blog.entity.Response; -import cn.celess.blog.service.CategoryService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.*; - -/** - * @author : xiaohai - * @date : 2019/03/30 20:36 - */ -@RestController -public class CategoryController { - - @Autowired - CategoryService categoryService; - - /** - * 新增一个分类 - * - * @param name 分类名 - * @return Response - */ - @PostMapping("/admin/category/create") - public Response addOne(@RequestParam("name") String name) { - return Response.success(categoryService.create(name)); - } - - /** - * 删除一个分类 - * - * @param id 分类id - * @return Response - */ - @DeleteMapping("/admin/category/del") - public Response deleteOne(@RequestParam("id") long id) { - return Response.success(categoryService.delete(id)); - } - - /** - * 更新一个分类 - * - * @param id 分类id - * @param name 更新后的名字 - * @return Response - */ - @PutMapping("/admin/category/update") - public Response updateOne(@RequestParam("id") Long id, - @RequestParam("name") String name) { - return Response.success(categoryService.update(id, name)); - } - - /** - * 获取所有的分类 - * - * @return Response - */ - @GetMapping("/categories") - public Response getPage(@RequestParam(name = "page", defaultValue = "1") int page, - @RequestParam(name = "count", defaultValue = "1000") int count) { - return Response.success(categoryService.retrievePage(page, count)); - } -} +package cn.celess.categorytag.controller; + +import cn.celess.common.entity.Response; +import cn.celess.common.service.CategoryService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +/** + * @author : xiaohai + * @date : 2019/03/30 20:36 + */ +@RestController +public class CategoryController { + + @Autowired + CategoryService categoryService; + + /** + * 新增一个分类 + * + * @param name 分类名 + * @return Response + */ + @PostMapping("/admin/category/create") + public Response addOne(@RequestParam("name") String name) { + return Response.success(categoryService.create(name)); + } + + /** + * 删除一个分类 + * + * @param id 分类id + * @return Response + */ + @DeleteMapping("/admin/category/del") + public Response deleteOne(@RequestParam("id") long id) { + return Response.success(categoryService.delete(id)); + } + + /** + * 更新一个分类 + * + * @param id 分类id + * @param name 更新后的名字 + * @return Response + */ + @PutMapping("/admin/category/update") + public Response updateOne(@RequestParam("id") Long id, + @RequestParam("name") String name) { + return Response.success(categoryService.update(id, name)); + } + + /** + * 获取所有的分类 + * + * @return Response + */ + @GetMapping("/categories") + public Response getPage(@RequestParam(name = "page", defaultValue = "1") int page, + @RequestParam(name = "count", defaultValue = "1000") int count) { + return Response.success(categoryService.retrievePage(page, count)); + } +} diff --git a/src/main/java/cn/celess/blog/controller/TagController.java b/blog-categorytag/src/main/java/cn/celess/categorytag/controller/TagController.java similarity index 88% rename from src/main/java/cn/celess/blog/controller/TagController.java rename to blog-categorytag/src/main/java/cn/celess/categorytag/controller/TagController.java index b09e0c8..1bef3c6 100644 --- a/src/main/java/cn/celess/blog/controller/TagController.java +++ b/blog-categorytag/src/main/java/cn/celess/categorytag/controller/TagController.java @@ -1,59 +1,59 @@ -package cn.celess.blog.controller; - -import cn.celess.blog.entity.Response; -import cn.celess.blog.entity.model.TagModel; -import cn.celess.blog.service.TagService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.*; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * @author : xiaohai - * @date : 2019/03/30 20:36 - */ -@RestController -public class TagController { - @Autowired - TagService tagService; - - - @PostMapping("/admin/tag/create") - public Response addOne(@RequestParam("name") String name) { - return Response.success(tagService.create(name)); - } - - @DeleteMapping("/admin/tag/del") - public Response delOne(@RequestParam("id") long id) { - return Response.success(tagService.delete(id)); - } - - - @PutMapping("/admin/tag/update") - public Response updateOne(@RequestParam("id") Long id, @RequestParam("name") String name) { - return Response.success(tagService.update(id, name)); - } - - @GetMapping("/tags") - public Response getPage(@RequestParam(required = false, defaultValue = "10", value = "count") int count, - @RequestParam(required = false, defaultValue = "1", value = "page") int page) { - return Response.success(tagService.retrievePage(page, count)); - } - - @GetMapping("/tags/nac") - public Response getTagNameAndCount() { - List> nameAndCount = new ArrayList<>(); - List all = tagService.findAll(); - for (TagModel t : all) { - Map map = new HashMap<>(2); - map.put("name", t.getName()); - map.put("size", t.getArticles().size()); - nameAndCount.add(map); - } - return Response.success(nameAndCount); - } - -} +package cn.celess.categorytag.controller; + +import cn.celess.common.entity.Response; +import cn.celess.common.entity.vo.TagModel; +import cn.celess.common.service.TagService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * @author : xiaohai + * @date : 2019/03/30 20:36 + */ +@RestController +public class TagController { + @Autowired + TagService tagService; + + + @PostMapping("/admin/tag/create") + public Response addOne(@RequestParam("name") String name) { + return Response.success(tagService.create(name)); + } + + @DeleteMapping("/admin/tag/del") + public Response delOne(@RequestParam("id") long id) { + return Response.success(tagService.delete(id)); + } + + + @PutMapping("/admin/tag/update") + public Response updateOne(@RequestParam("id") Long id, @RequestParam("name") String name) { + return Response.success(tagService.update(id, name)); + } + + @GetMapping("/tags") + public Response getPage(@RequestParam(required = false, defaultValue = "10", value = "count") int count, + @RequestParam(required = false, defaultValue = "1", value = "page") int page) { + return Response.success(tagService.retrievePage(page, count)); + } + + @GetMapping("/tags/nac") + public Response getTagNameAndCount() { + List> nameAndCount = new ArrayList<>(); + List all = tagService.findAll(); + for (TagModel t : all) { + Map map = new HashMap<>(2); + map.put("name", t.getName()); + map.put("size", t.getArticles().size()); + nameAndCount.add(map); + } + return Response.success(nameAndCount); + } + +} diff --git a/src/main/java/cn/celess/blog/service/serviceimpl/CategoryServiceImpl.java b/blog-categorytag/src/main/java/cn/celess/categorytag/serviceimpl/CategoryServiceImpl.java similarity index 82% rename from src/main/java/cn/celess/blog/service/serviceimpl/CategoryServiceImpl.java rename to blog-categorytag/src/main/java/cn/celess/categorytag/serviceimpl/CategoryServiceImpl.java index 61849a4..d1d02aa 100644 --- a/src/main/java/cn/celess/blog/service/serviceimpl/CategoryServiceImpl.java +++ b/blog-categorytag/src/main/java/cn/celess/categorytag/serviceimpl/CategoryServiceImpl.java @@ -1,92 +1,92 @@ -package cn.celess.blog.service.serviceimpl; - -import cn.celess.blog.enmu.ResponseEnum; -import cn.celess.blog.entity.Article; -import cn.celess.blog.entity.Category; -import cn.celess.blog.entity.model.ArticleModel; -import cn.celess.blog.entity.model.CategoryModel; -import cn.celess.blog.entity.model.PageData; -import cn.celess.blog.exception.MyException; -import cn.celess.blog.mapper.ArticleMapper; -import cn.celess.blog.mapper.CategoryMapper; -import cn.celess.blog.service.CategoryService; -import cn.celess.blog.util.ModalTrans; -import com.github.pagehelper.PageHelper; -import com.github.pagehelper.PageInfo; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import javax.servlet.http.HttpServletRequest; -import java.util.List; -import java.util.stream.Collectors; - -/** - * @author : xiaohai - * @date : 2019/03/28 22:43 - */ -@Service -public class CategoryServiceImpl implements CategoryService { - @Autowired - CategoryMapper categoryMapper; - @Autowired - HttpServletRequest request; - @Autowired - ArticleMapper articleMapper; - - @Override - public CategoryModel create(String name) { - if (categoryMapper.existsByName(name)) { - throw new MyException(ResponseEnum.CATEGORY_HAS_EXIST); - } - Category category = new Category(); - category.setName(name); - categoryMapper.insert(category); - return ModalTrans.category(category); - } - - @Override - public boolean delete(long id) { - Category category = categoryMapper.findCategoryById(id); - if (category == null) { - throw new MyException(ResponseEnum.CATEGORY_NOT_EXIST); - } - return categoryMapper.delete(id) == 1; - } - - @Override - public CategoryModel update(Long id, String name) { - if (id == null) { - throw new MyException(ResponseEnum.PARAMETERS_ERROR.getCode(), "id不可为空"); - } - Category category = categoryMapper.findCategoryById(id); - category.setName(name); - categoryMapper.update(category); - return ModalTrans.category(category); - } - - @Override - public PageData retrievePage(int page, int count) { - PageHelper.startPage(page, count); - List all = categoryMapper.findAll(); - // 遍历没一个category - List modelList = all - .stream() - .map(ModalTrans::category) - .peek(categoryModel -> { - // 根据category去查article,并赋值给categoryModel - List
allByCategoryId = articleMapper.findAllByCategoryId(categoryModel.getId()); - List articleModelList = allByCategoryId - .stream() - .map(article -> ModalTrans.article(article, true)) - .peek(articleModel -> { - // 去除不必要的字段 - articleModel.setPreArticle(null); - articleModel.setNextArticle(null); - articleModel.setTags(null); - }) - .collect(Collectors.toList()); - categoryModel.setArticles(articleModelList); - }).collect(Collectors.toList()); - return new PageData<>(new PageInfo<>(all), modelList); - } -} +package cn.celess.categorytag.serviceimpl; + +import cn.celess.common.enmu.ResponseEnum; +import cn.celess.common.entity.Article; +import cn.celess.common.entity.Category; +import cn.celess.common.entity.vo.ArticleModel; +import cn.celess.common.entity.vo.CategoryModel; +import cn.celess.common.entity.vo.PageData; +import cn.celess.common.exception.MyException; +import cn.celess.common.mapper.ArticleMapper; +import cn.celess.common.mapper.CategoryMapper; +import cn.celess.common.service.CategoryService; +import cn.celess.common.util.ModalTrans; +import com.github.pagehelper.PageHelper; +import com.github.pagehelper.PageInfo; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import javax.servlet.http.HttpServletRequest; +import java.util.List; +import java.util.stream.Collectors; + +/** + * @author : xiaohai + * @date : 2019/03/28 22:43 + */ +@Service +public class CategoryServiceImpl implements CategoryService { + @Autowired + CategoryMapper categoryMapper; + @Autowired + HttpServletRequest request; + @Autowired + ArticleMapper articleMapper; + + @Override + public CategoryModel create(String name) { + if (categoryMapper.existsByName(name)) { + throw new MyException(ResponseEnum.CATEGORY_HAS_EXIST); + } + Category category = new Category(); + category.setName(name); + categoryMapper.insert(category); + return ModalTrans.category(category); + } + + @Override + public boolean delete(long id) { + Category category = categoryMapper.findCategoryById(id); + if (category == null) { + throw new MyException(ResponseEnum.CATEGORY_NOT_EXIST); + } + return categoryMapper.delete(id) == 1; + } + + @Override + public CategoryModel update(Long id, String name) { + if (id == null) { + throw new MyException(ResponseEnum.PARAMETERS_ERROR.getCode(), "id不可为空"); + } + Category category = categoryMapper.findCategoryById(id); + category.setName(name); + categoryMapper.update(category); + return ModalTrans.category(category); + } + + @Override + public PageData retrievePage(int page, int count) { + PageHelper.startPage(page, count); + List all = categoryMapper.findAll(); + // 遍历没一个category + List modelList = all + .stream() + .map(ModalTrans::category) + .peek(categoryModel -> { + // 根据category去查article,并赋值给categoryModel + List
allByCategoryId = articleMapper.findAllByCategoryId(categoryModel.getId()); + List articleModelList = allByCategoryId + .stream() + .map(article -> ModalTrans.article(article, true)) + .peek(articleModel -> { + // 去除不必要的字段 + articleModel.setPreArticle(null); + articleModel.setNextArticle(null); + articleModel.setTags(null); + }) + .collect(Collectors.toList()); + categoryModel.setArticles(articleModelList); + }).collect(Collectors.toList()); + return new PageData<>(new PageInfo<>(all), modelList); + } +} diff --git a/src/main/java/cn/celess/blog/service/serviceimpl/TagServiceImpl.java b/blog-categorytag/src/main/java/cn/celess/categorytag/serviceimpl/TagServiceImpl.java similarity index 81% rename from src/main/java/cn/celess/blog/service/serviceimpl/TagServiceImpl.java rename to blog-categorytag/src/main/java/cn/celess/categorytag/serviceimpl/TagServiceImpl.java index 8b0d5d0..d699d56 100644 --- a/src/main/java/cn/celess/blog/service/serviceimpl/TagServiceImpl.java +++ b/blog-categorytag/src/main/java/cn/celess/categorytag/serviceimpl/TagServiceImpl.java @@ -1,103 +1,103 @@ -package cn.celess.blog.service.serviceimpl; - -import cn.celess.blog.enmu.ResponseEnum; -import cn.celess.blog.entity.ArticleTag; -import cn.celess.blog.entity.Tag; -import cn.celess.blog.entity.model.ArticleModel; -import cn.celess.blog.entity.model.PageData; -import cn.celess.blog.entity.model.TagModel; -import cn.celess.blog.exception.MyException; -import cn.celess.blog.mapper.ArticleMapper; -import cn.celess.blog.mapper.ArticleTagMapper; -import cn.celess.blog.mapper.TagMapper; -import cn.celess.blog.service.TagService; -import cn.celess.blog.util.ModalTrans; -import com.github.pagehelper.PageHelper; -import com.github.pagehelper.PageInfo; -import org.springframework.beans.factory.annotation.Autowired; -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 22:29 - */ -@Service -public class TagServiceImpl implements TagService { - @Autowired - TagMapper tagMapper; - @Autowired - HttpServletRequest request; - @Autowired - ArticleMapper articleMapper; - @Autowired - ArticleTagMapper articleTagMapper; - - @Override - public TagModel create(String name) { - boolean b = tagMapper.existsByName(name); - if (b) { - throw new MyException(ResponseEnum.TAG_HAS_EXIST); - } - Tag tag = new Tag(); - tag.setName(name); - tagMapper.insert(tag); - return ModalTrans.tag(tag); - } - - @Override - @Transactional(rollbackFor = Exception.class) - public boolean delete(long tagId) { - Tag tag = tagMapper.findTagById(tagId); - if (tag == null) { - throw new MyException(ResponseEnum.TAG_NOT_EXIST); - } - List articleByTag = articleTagMapper.findArticleByTag(tagId); - // 删除文章 - articleByTag.forEach(articleTag -> articleMapper.delete(articleTag.getArticle().getId())); - return tagMapper.delete(tagId) == 1; - } - - - @Override - public TagModel update(Long id, String name) { - if (id == null) { - throw new MyException(ResponseEnum.PARAMETERS_ERROR.getCode(), "缺少ID"); - } - Tag tag = tagMapper.findTagById(id); - tag.setName(name); - tagMapper.update(tag); - return ModalTrans.tag(tag); - - } - - @Override - public PageData retrievePage(int page, int count) { - PageHelper.startPage(page, count); - List tagList = tagMapper.findAll(); - List modelList = new ArrayList<>(); - tagList.forEach(tag -> modelList.add(ModalTrans.tag(tag))); - return new PageData<>(new PageInfo<>(tagList), modelList); - } - - @Override - public List findAll() { - return tagMapper.findAll().stream() - .map(ModalTrans::tag) - .peek(tagModel -> { - List articleByTagAndOpen = articleTagMapper.findArticleByTagAndOpen(tagModel.getId()); - tagModel.setArticles( - articleByTagAndOpen - .stream() - .map(articleTag -> ModalTrans.article(articleTag.getArticle(), true)) - .collect(Collectors.toList()) - ); - }) - .collect(Collectors.toList()); - } -} +package cn.celess.categorytag.serviceimpl; + + +import cn.celess.common.enmu.ResponseEnum; +import cn.celess.common.entity.ArticleTag; +import cn.celess.common.entity.Tag; +import cn.celess.common.entity.vo.PageData; +import cn.celess.common.entity.vo.TagModel; +import cn.celess.common.exception.MyException; +import cn.celess.common.mapper.ArticleMapper; +import cn.celess.common.mapper.ArticleTagMapper; +import cn.celess.common.mapper.TagMapper; +import cn.celess.common.service.TagService; +import cn.celess.common.util.ModalTrans; +import com.github.pagehelper.PageHelper; +import com.github.pagehelper.PageInfo; +import org.springframework.beans.factory.annotation.Autowired; +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 22:29 + */ +@Service +public class TagServiceImpl implements TagService { + @Autowired + TagMapper tagMapper; + @Autowired + HttpServletRequest request; + @Autowired + ArticleMapper articleMapper; + @Autowired + ArticleTagMapper articleTagMapper; + + @Override + public TagModel create(String name) { + boolean b = tagMapper.existsByName(name); + if (b) { + throw new MyException(ResponseEnum.TAG_HAS_EXIST); + } + Tag tag = new Tag(); + tag.setName(name); + tagMapper.insert(tag); + return ModalTrans.tag(tag); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public boolean delete(long tagId) { + Tag tag = tagMapper.findTagById(tagId); + if (tag == null) { + throw new MyException(ResponseEnum.TAG_NOT_EXIST); + } + List articleByTag = articleTagMapper.findArticleByTag(tagId); + // 删除文章 + articleByTag.forEach(articleTag -> articleMapper.delete(articleTag.getArticle().getId())); + return tagMapper.delete(tagId) == 1; + } + + + @Override + public TagModel update(Long id, String name) { + if (id == null) { + throw new MyException(ResponseEnum.PARAMETERS_ERROR.getCode(), "缺少ID"); + } + Tag tag = tagMapper.findTagById(id); + tag.setName(name); + tagMapper.update(tag); + return ModalTrans.tag(tag); + + } + + @Override + public PageData retrievePage(int page, int count) { + PageHelper.startPage(page, count); + List tagList = tagMapper.findAll(); + List modelList = new ArrayList<>(); + tagList.forEach(tag -> modelList.add(ModalTrans.tag(tag))); + return new PageData<>(new PageInfo<>(tagList), modelList); + } + + @Override + public List findAll() { + return tagMapper.findAll().stream() + .map(ModalTrans::tag) + .peek(tagModel -> { + List articleByTagAndOpen = articleTagMapper.findArticleByTagAndOpen(tagModel.getId()); + tagModel.setArticles( + articleByTagAndOpen + .stream() + .map(articleTag -> ModalTrans.article(articleTag.getArticle(), true)) + .collect(Collectors.toList()) + ); + }) + .collect(Collectors.toList()); + } +} diff --git a/blog-comment/pom.xml b/blog-comment/pom.xml new file mode 100644 index 0000000..3c54d57 --- /dev/null +++ b/blog-comment/pom.xml @@ -0,0 +1,38 @@ + + + + blog + cn.celess + 0.0.1-SNAPSHOT + + 4.0.0 + + blog-comment + + + 13 + 13 + + + + cn.celess + blog-common + ${blog-common.version} + + + + cn.celess + blog-user + ${blog-user.version} + + + + + org.springframework.boot + spring-boot-starter-web + + + + \ No newline at end of file diff --git a/src/main/java/cn/celess/blog/controller/CommentController.java b/blog-comment/src/main/java/cn/celess/comment/controller/CommentController.java similarity index 93% rename from src/main/java/cn/celess/blog/controller/CommentController.java rename to blog-comment/src/main/java/cn/celess/comment/controller/CommentController.java index 8841ef3..80103f8 100644 --- a/src/main/java/cn/celess/blog/controller/CommentController.java +++ b/blog-comment/src/main/java/cn/celess/comment/controller/CommentController.java @@ -1,119 +1,119 @@ -package cn.celess.blog.controller; - -import cn.celess.blog.entity.Response; -import cn.celess.blog.entity.request.CommentReq; -import cn.celess.blog.service.CommentService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.*; - - -/** - * @author : xiaohai - * @date : 2019/03/30 20:37 - */ -@RestController -public class CommentController { - @Autowired - CommentService commentService; - - /** - * 新增一条评论数据 - * - * @param reqBody 请求数据 - * @return Response - */ - @PostMapping("/user/comment/create") - public Response addOne(@RequestBody CommentReq reqBody) { - return Response.success(commentService.create(reqBody)); - } - - @DeleteMapping("/user/comment/del") - public Response delete(@RequestParam("id") long id) { - return Response.success(commentService.delete(id)); - } - - @PutMapping("/user/comment/update") - public Response update(@RequestBody CommentReq reqBody) { - return Response.success(commentService.update(reqBody)); - } - - /** - * 获取所有的评论 - * - * @param pagePath pagePath - * @param count 单页数据量 - * @param page 页码 - * @return Response - */ - @GetMapping("/comments/{pagePath}/{pid}") - public Response commentsOfArticle(@PathVariable("pagePath") String pagePath, @PathVariable(value = "pid") long pid, - @RequestParam(value = "count", required = false, defaultValue = "10") int count, - @RequestParam(value = "page", required = false, defaultValue = "1") int page) { - String path = ""; - if (pagePath.contains("article+")) { - path = "article/" + pagePath.split("\\+", 2)[1]; - } else { - path = pagePath; - } - if ("*".equals(pagePath)) { - path = null; - } - return Response.success(commentService.retrievePageByPageAndPid(path, pid, page, count)); - } - - /** - * 通过pid获取数据 - * - * @param pagePath pagePath - * @param count count - * @param page page - * @return Response - */ - @GetMapping("/comment/pagePath/{pagePath}") - public Response retrievePage(@PathVariable("pagePath") String pagePath, - @RequestParam(value = "count", required = false, defaultValue = "10") int count, - @RequestParam(value = "page", required = false, defaultValue = "1") int page) { - String path = ""; - if (pagePath.contains("article+")) { - path = "article/" + pagePath.split("\\+", 2)[1]; - } else { - path = pagePath; - } - if ("*".equals(pagePath)) { - path = null; - } - return Response.success(commentService.retrievePage(path, page, count)); - } - - @GetMapping("/user/comment/pagePath/{pagePath}") - public Response userComment(@PathVariable("pagePath") String pagePath, - @RequestParam(value = "count", required = false, defaultValue = "10") int count, - @RequestParam(value = "page", required = false, defaultValue = "1") int page) { - String path = ""; - if (pagePath.contains("article+")) { - path = "article/" + pagePath.split("\\+", 2)[1]; - } else { - path = pagePath; - } - if ("*".equals(pagePath)) { - path = null; - } - return Response.success(commentService.retrievePageByAuthor(path, page, count)); - } - - @GetMapping("/admin/comment/pagePath/{pagePath}") - public Response adminComment(@PathVariable("pagePath") String pagePath, - @RequestParam(value = "count", required = false, defaultValue = "10") int count, - @RequestParam(value = "page", required = false, defaultValue = "1") int page) { - String path = ""; - if (pagePath.contains("article+")) { - path = "article/" + pagePath.split("\\+", 2)[1]; - } else { - path = pagePath; - } - if ("*".equals(pagePath)) { - path = null; - } - return Response.success(commentService.retrievePageByPage(path, page, count)); - } -} +package cn.celess.comment.controller; + +import cn.celess.common.entity.Response; +import cn.celess.common.entity.dto.CommentReq; +import cn.celess.common.service.CommentService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + + +/** + * @author : xiaohai + * @date : 2019/03/30 20:37 + */ +@RestController +public class CommentController { + @Autowired + CommentService commentService; + + /** + * 新增一条评论数据 + * + * @param reqBody 请求数据 + * @return Response + */ + @PostMapping("/user/comment/create") + public Response addOne(@RequestBody CommentReq reqBody) { + return Response.success(commentService.create(reqBody)); + } + + @DeleteMapping("/user/comment/del") + public Response delete(@RequestParam("id") long id) { + return Response.success(commentService.delete(id)); + } + + @PutMapping("/user/comment/update") + public Response update(@RequestBody CommentReq reqBody) { + return Response.success(commentService.update(reqBody)); + } + + /** + * 获取所有的评论 + * + * @param pagePath pagePath + * @param count 单页数据量 + * @param page 页码 + * @return Response + */ + @GetMapping("/comments/{pagePath}/{pid}") + public Response commentsOfArticle(@PathVariable("pagePath") String pagePath, @PathVariable(value = "pid") long pid, + @RequestParam(value = "count", required = false, defaultValue = "10") int count, + @RequestParam(value = "page", required = false, defaultValue = "1") int page) { + String path = ""; + if (pagePath.contains("article+")) { + path = "article/" + pagePath.split("\\+", 2)[1]; + } else { + path = pagePath; + } + if ("*".equals(pagePath)) { + path = null; + } + return Response.success(commentService.retrievePageByPageAndPid(path, pid, page, count)); + } + + /** + * 通过pid获取数据 + * + * @param pagePath pagePath + * @param count count + * @param page page + * @return Response + */ + @GetMapping("/comment/pagePath/{pagePath}") + public Response retrievePage(@PathVariable("pagePath") String pagePath, + @RequestParam(value = "count", required = false, defaultValue = "10") int count, + @RequestParam(value = "page", required = false, defaultValue = "1") int page) { + String path = ""; + if (pagePath.contains("article+")) { + path = "article/" + pagePath.split("\\+", 2)[1]; + } else { + path = pagePath; + } + if ("*".equals(pagePath)) { + path = null; + } + return Response.success(commentService.retrievePage(path, page, count)); + } + + @GetMapping("/user/comment/pagePath/{pagePath}") + public Response userComment(@PathVariable("pagePath") String pagePath, + @RequestParam(value = "count", required = false, defaultValue = "10") int count, + @RequestParam(value = "page", required = false, defaultValue = "1") int page) { + String path = ""; + if (pagePath.contains("article+")) { + path = "article/" + pagePath.split("\\+", 2)[1]; + } else { + path = pagePath; + } + if ("*".equals(pagePath)) { + path = null; + } + return Response.success(commentService.retrievePageByAuthor(path, page, count)); + } + + @GetMapping("/admin/comment/pagePath/{pagePath}") + public Response adminComment(@PathVariable("pagePath") String pagePath, + @RequestParam(value = "count", required = false, defaultValue = "10") int count, + @RequestParam(value = "page", required = false, defaultValue = "1") int page) { + String path = ""; + if (pagePath.contains("article+")) { + path = "article/" + pagePath.split("\\+", 2)[1]; + } else { + path = pagePath; + } + if ("*".equals(pagePath)) { + path = null; + } + return Response.success(commentService.retrievePageByPage(path, page, count)); + } +} diff --git a/src/main/java/cn/celess/blog/service/serviceimpl/CommentServiceImpl.java b/blog-comment/src/main/java/cn/celess/comment/serviceimpl/CommentServiceImpl.java similarity index 85% rename from src/main/java/cn/celess/blog/service/serviceimpl/CommentServiceImpl.java rename to blog-comment/src/main/java/cn/celess/comment/serviceimpl/CommentServiceImpl.java index b58e706..1ac23d4 100644 --- a/src/main/java/cn/celess/blog/service/serviceimpl/CommentServiceImpl.java +++ b/blog-comment/src/main/java/cn/celess/comment/serviceimpl/CommentServiceImpl.java @@ -1,153 +1,152 @@ -package cn.celess.blog.service.serviceimpl; - -import cn.celess.blog.enmu.CommentStatusEnum; -import cn.celess.blog.enmu.ResponseEnum; -import cn.celess.blog.entity.Comment; -import cn.celess.blog.entity.User; -import cn.celess.blog.entity.model.CommentModel; -import cn.celess.blog.entity.model.PageData; -import cn.celess.blog.entity.request.CommentReq; -import cn.celess.blog.exception.MyException; -import cn.celess.blog.mapper.ArticleMapper; -import cn.celess.blog.mapper.CommentMapper; -import cn.celess.blog.mapper.UserMapper; -import cn.celess.blog.service.CommentService; -import cn.celess.blog.util.ModalTrans; -import cn.celess.blog.util.RedisUserUtil; -import com.github.pagehelper.PageHelper; -import com.github.pagehelper.PageInfo; -import org.springframework.beans.BeanUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import javax.servlet.http.HttpServletRequest; -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Collectors; - -/** - * @author : xiaohai - * @date : 2019/03/29 17:05 - */ -@Service -public class CommentServiceImpl implements CommentService { - @Autowired - CommentMapper commentMapper; - @Autowired - UserMapper userMapper; - @Autowired - ArticleMapper articleMapper; - @Autowired - HttpServletRequest request; - @Autowired - RedisUserUtil redisUserUtil; - - @Override - public CommentModel create(CommentReq reqBody) { - if (reqBody == null) { - throw new MyException(ResponseEnum.PARAMETERS_ERROR); - } - User user = redisUserUtil.get(); - Comment pComment = null; - if (reqBody.getPid() != -1) { - pComment = commentMapper.findCommentById(reqBody.getPid()); - } - //不是一级评论 - if (reqBody.getPid() != -1 && pComment == null) { - //父评论不存在 - throw new MyException(ResponseEnum.PARAMETERS_ERROR); - } - Comment comment = new Comment(); - comment.setFromUser(user); - User userTo = new User(); - userTo.setId(null); - if (reqBody.getToUserId() != -1) { - userTo = userMapper.findById(reqBody.getToUserId()); - comment.setToUser(userTo); - } - comment.setToUser(userTo); - userMapper.findById(reqBody.getToUserId()); - BeanUtils.copyProperties(reqBody, comment); - commentMapper.insert(comment); - return ModalTrans.comment(commentMapper.findCommentById(comment.getId())); - } - - @Override - public boolean delete(long id) { - Comment b = commentMapper.findCommentById(id); - if (b == null) { - throw new MyException(ResponseEnum.COMMENT_NOT_EXIST); - } - if (b.getStatus() == CommentStatusEnum.DELETED.getCode()) { - throw new MyException(ResponseEnum.DATA_IS_DELETED); - } - commentMapper.delete(id); - return true; - } - - @Override - public CommentModel update(CommentReq reqBody) { - if (reqBody.getId() == null) { - throw new MyException(ResponseEnum.PARAMETERS_ERROR.getCode(), "id不可为空"); - } - Comment comment = commentMapper.findCommentById(reqBody.getId()); - if (!comment.getContent().equals(reqBody.getContent())) { - commentMapper.updateContent(reqBody.getContent(), reqBody.getId()); - comment.setContent(reqBody.getContent()); - } - return ModalTrans.comment(comment); - } - - @Override - public PageData retrievePage(String pagePath, int page, int count) { - PageHelper.startPage(page, count); - List list = commentMapper.findAllByPagePathAndPidAndNormal(pagePath, -1); - return pageTrans(list); - } - - @Override - public List retrievePageByPid(long pid) { - List allByPagePath = commentMapper.findAllByPid(pid); - return allByPagePath - .stream() - .filter(comment -> comment.getStatus() != CommentStatusEnum.DELETED.getCode()) - .map(ModalTrans::comment) - .collect(Collectors.toList()); - } - - @Override - public PageData retrievePageByAuthor(String pagePath, int page, int count) { - User user = redisUserUtil.get(); - PageHelper.startPage(page, count); - List list = commentMapper.findAllByPagePathAndFromUser(pagePath, user.getId()); - return pageTrans(list); - } - - @Override - public PageData retrievePageByPageAndPid(String pagePath, long pid, int page, int count) { - PageHelper.startPage(page, count); - List list = commentMapper.findAllByPagePath(pagePath); - return pageTrans(list, true); - } - - @Override - public PageData retrievePageByPage(String pagePath, int page, int count) { - PageHelper.startPage(page, count); - List list = commentMapper.findAllByPagePath(pagePath); - return pageTrans(list, true); - } - - private PageData pageTrans(List commentList) { - return pageTrans(commentList, false); - } - - private PageData pageTrans(List commentList, boolean noResponseList) { - PageInfo p = PageInfo.of(commentList); - List modelList = commentList - .stream() - .map(ModalTrans::comment) - .peek(commentModel -> commentModel.setRespComment(this.retrievePageByPid(commentModel.getId()))) - .collect(Collectors.toList()); - return new PageData<>(p, modelList); - } -} +package cn.celess.comment.serviceimpl; + +import cn.celess.common.enmu.CommentStatusEnum; +import cn.celess.common.enmu.ResponseEnum; +import cn.celess.common.entity.Comment; +import cn.celess.common.entity.User; +import cn.celess.common.entity.dto.CommentReq; +import cn.celess.common.entity.vo.CommentModel; +import cn.celess.common.entity.vo.PageData; +import cn.celess.common.exception.MyException; +import cn.celess.common.mapper.ArticleMapper; +import cn.celess.common.mapper.CommentMapper; +import cn.celess.common.mapper.UserMapper; +import cn.celess.common.service.CommentService; +import cn.celess.common.util.ModalTrans; +import cn.celess.user.util.RedisUserUtil; +import com.github.pagehelper.PageHelper; +import com.github.pagehelper.PageInfo; +import org.springframework.beans.BeanUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import javax.servlet.http.HttpServletRequest; +import java.util.List; +import java.util.stream.Collectors; + +/** + * @author : xiaohai + * @date : 2019/03/29 17:05 + */ +@Service +public class CommentServiceImpl implements CommentService { + @Autowired + CommentMapper commentMapper; + @Autowired + UserMapper userMapper; + @Autowired + ArticleMapper articleMapper; + @Autowired + HttpServletRequest request; + @Autowired + RedisUserUtil redisUserUtil; + + @Override + public CommentModel create(CommentReq reqBody) { + if (reqBody == null) { + throw new MyException(ResponseEnum.PARAMETERS_ERROR); + } + User user = redisUserUtil.get(); + Comment pComment = null; + if (reqBody.getPid() != -1) { + pComment = commentMapper.findCommentById(reqBody.getPid()); + } + //不是一级评论 + if (reqBody.getPid() != -1 && pComment == null) { + //父评论不存在 + throw new MyException(ResponseEnum.PARAMETERS_ERROR); + } + Comment comment = new Comment(); + comment.setFromUser(user); + User userTo = new User(); + userTo.setId(null); + if (reqBody.getToUserId() != -1) { + userTo = userMapper.findById(reqBody.getToUserId()); + comment.setToUser(userTo); + } + comment.setToUser(userTo); + userMapper.findById(reqBody.getToUserId()); + BeanUtils.copyProperties(reqBody, comment); + commentMapper.insert(comment); + return ModalTrans.comment(commentMapper.findCommentById(comment.getId())); + } + + @Override + public boolean delete(long id) { + Comment b = commentMapper.findCommentById(id); + if (b == null) { + throw new MyException(ResponseEnum.COMMENT_NOT_EXIST); + } + if (b.getStatus() == CommentStatusEnum.DELETED.getCode()) { + throw new MyException(ResponseEnum.DATA_IS_DELETED); + } + commentMapper.delete(id); + return true; + } + + @Override + public CommentModel update(CommentReq reqBody) { + if (reqBody.getId() == null) { + throw new MyException(ResponseEnum.PARAMETERS_ERROR.getCode(), "id不可为空"); + } + Comment comment = commentMapper.findCommentById(reqBody.getId()); + if (!comment.getContent().equals(reqBody.getContent())) { + commentMapper.updateContent(reqBody.getContent(), reqBody.getId()); + comment.setContent(reqBody.getContent()); + } + return ModalTrans.comment(comment); + } + + @Override + public PageData retrievePage(String pagePath, int page, int count) { + PageHelper.startPage(page, count); + List list = commentMapper.findAllByPagePathAndPidAndNormal(pagePath, -1); + return pageTrans(list); + } + + @Override + public List retrievePageByPid(long pid) { + List allByPagePath = commentMapper.findAllByPid(pid); + return allByPagePath + .stream() + .filter(comment -> comment.getStatus() != CommentStatusEnum.DELETED.getCode()) + .map(ModalTrans::comment) + .collect(Collectors.toList()); + } + + @Override + public PageData retrievePageByAuthor(String pagePath, int page, int count) { + User user = redisUserUtil.get(); + PageHelper.startPage(page, count); + List list = commentMapper.findAllByPagePathAndFromUser(pagePath, user.getId()); + return pageTrans(list); + } + + @Override + public PageData retrievePageByPageAndPid(String pagePath, long pid, int page, int count) { + PageHelper.startPage(page, count); + List list = commentMapper.findAllByPagePath(pagePath); + return pageTrans(list, true); + } + + @Override + public PageData retrievePageByPage(String pagePath, int page, int count) { + PageHelper.startPage(page, count); + List list = commentMapper.findAllByPagePath(pagePath); + return pageTrans(list, true); + } + + private PageData pageTrans(List commentList) { + return pageTrans(commentList, false); + } + + private PageData pageTrans(List commentList, boolean noResponseList) { + PageInfo p = PageInfo.of(commentList); + List modelList = commentList + .stream() + .map(ModalTrans::comment) + .peek(commentModel -> commentModel.setRespComment(this.retrievePageByPid(commentModel.getId()))) + .collect(Collectors.toList()); + return new PageData<>(p, modelList); + } +} diff --git a/blog-common/pom.xml b/blog-common/pom.xml new file mode 100644 index 0000000..a39ee18 --- /dev/null +++ b/blog-common/pom.xml @@ -0,0 +1,91 @@ + + + + blog + cn.celess + 0.0.1-SNAPSHOT + + 4.0.0 + + blog-common + + + + org.springframework.boot + spring-boot-starter-test + + + + org.springframework.boot + spring-boot-starter-web + + + + mysql + mysql-connector-java + runtime + + + + + com.alibaba + druid + 1.2.6 + + + + + org.mybatis.spring.boot + mybatis-spring-boot-starter + 2.2.0 + + + + + com.github.pagehelper + pagehelper-spring-boot-starter + 1.3.0 + + + + + + org.springframework.boot + spring-boot-starter-mail + + + + com.qiniu + qiniu-java-sdk + [7.2.0, 7.2.99] + + + + + org.springframework.boot + spring-boot-starter-data-redis + + + + net.sourceforge.htmlunit + htmlunit + 2.45.0 + + + + + + com.dyuproject.protostuff + protostuff-core + 1.1.6 + + + com.dyuproject.protostuff + protostuff-runtime + 1.1.6 + + + + diff --git a/blog-common/src/main/java/cn/celess/common/config/MybatisConfig.java b/blog-common/src/main/java/cn/celess/common/config/MybatisConfig.java new file mode 100644 index 0000000..af2ddf1 --- /dev/null +++ b/blog-common/src/main/java/cn/celess/common/config/MybatisConfig.java @@ -0,0 +1,9 @@ +package cn.celess.common.config; + +import org.mybatis.spring.annotation.MapperScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@MapperScan("cn.celess.common.mapper") +public class MybatisConfig { +} diff --git a/src/main/java/cn/celess/blog/enmu/CommentStatusEnum.java b/blog-common/src/main/java/cn/celess/common/enmu/CommentStatusEnum.java similarity index 92% rename from src/main/java/cn/celess/blog/enmu/CommentStatusEnum.java rename to blog-common/src/main/java/cn/celess/common/enmu/CommentStatusEnum.java index 01ccbac..4bea80c 100644 --- a/src/main/java/cn/celess/blog/enmu/CommentStatusEnum.java +++ b/blog-common/src/main/java/cn/celess/common/enmu/CommentStatusEnum.java @@ -1,4 +1,4 @@ -package cn.celess.blog.enmu; +package cn.celess.common.enmu; import lombok.Getter; diff --git a/src/main/java/cn/celess/blog/enmu/ResponseEnum.java b/blog-common/src/main/java/cn/celess/common/enmu/ResponseEnum.java similarity index 96% rename from src/main/java/cn/celess/blog/enmu/ResponseEnum.java rename to blog-common/src/main/java/cn/celess/common/enmu/ResponseEnum.java index 54bea45..728068e 100644 --- a/src/main/java/cn/celess/blog/enmu/ResponseEnum.java +++ b/blog-common/src/main/java/cn/celess/common/enmu/ResponseEnum.java @@ -1,96 +1,96 @@ -package cn.celess.blog.enmu; - -/** - * @author : xiaohai - * @date : 2019/03/28 15:37 - */ -public enum ResponseEnum { - // Response enum - - SUCCESS(0, "成功"), - FAILURE(-1, "失败"), - ERROR(-2, "错误"), - - DATA_IS_DELETED(1000, "数据已被删除"), - - //文章类 - ARTICLE_NOT_EXIST(2010, "文章不存在"), - ARTICLE_HAS_EXIST(2020, "文章已存在"), - ARTICLE_NOT_PUBLIC(2030, "文章暂未公开"), - ARTICLE_NOT_BELONG_YOU(2040, "无权限操作别人的文章"), - - //用户类 - HAVE_NOT_LOG_IN(3010, "还未登录"), - PERMISSION_ERROR(3020, "没有此权限"), - USER_NOT_EXIST(3030, "用户不存在"), - USERNAME_HAS_EXIST(3040, "用户名已存在"), - USERNAME_TOO_SHORT(3050, "用户名太短"), - PASSWORD_TOO_SHORT_OR_LONG(3060, "密码长度过长或者过短"), - LOGIN_FAILURE(3100, "登录失败,用户名/密码不正确"), - USEREMAIL_NULL(3310, "未设置邮箱"), - USEREMAIL_NOT_VERIFY(3320, "邮箱未验证"), - LOGIN_LATER(3500, "错误次数已达5次,请稍后再试"), - PWD_SAME(3601, "新密码与原密码相同"), - PWD_NOT_SAME(3602, "新密码与原密码不相同"), - LOGIN_EXPIRED(3700, "登陆过期"), - LOGOUT(3710, "账户已注销"), - CAN_NOT_USE(3711, "账户不可用"), - PWD_WRONG(3800, "密码不正确"), - - JWT_EXPIRED(3810, "Token过期"), - JWT_MALFORMED(3820, "Token格式不对"), - JWT_SIGNATURE(3830, "Token签名错误"), - JWT_NOT_SUPPORT(3840, "不支持的Token"), - - //标签 - TAG_NOT_EXIST(4010, "标签不存在"), - TAG_HAS_EXIST(4020, "标签已存在"), - - //分类 - CATEGORY_NOT_EXIST(5010, "分类不存在"), - CATEGORY_HAS_EXIST(5020, "分类已存在"), - - //评论/留言 - COMMENT_NOT_EXIST(6010, "评论/留言不存在"), - COMMENT_HAS_EXIST(6020, "评论/留言已存在,请不要重复提交"), - - //webUdpateInfo amd PartnerSite - DATA_NOT_EXIST(7010, "数据不存在"), - DATA_HAS_EXIST(7020, "数据已存在"), - - //其他 - APPLY_LINK_NO_ADD_THIS_SITE(7200, "暂未在您的网站中抓取到本站链接"), - DATA_EXPIRED(7300, "数据过期"), - CANNOT_GET_DATA(7400, "暂无法获取到数据"), - NO_FILE(7500, "未选择文件,请重新选择"), - - - //提交更新之前,没有获取数据/, - DID_NOT_GET_THE_DATA(8020, "非法访问"), - IMG_CODE_TIMEOUT(8100, "验证码已失效"), - IMG_CODE_DIDNOTVERIFY(8200, "请先验证验证码"), - VERIFY_ERROR(8300, "验证失败"), - PARAMETERS_ERROR(8500, "参数错误"), - PARAMETERS_URL_ERROR(8510, "链接格式错误"), - PARAMETERS_EMAIL_ERROR(8520, "邮箱格式错误"), - PARAMETERS_PHONE_ERROR(8530, "手机格式错误"), - PARAMETERS_QQ_ERROR(8540, "QQ格式错误"), - PARAMETERS_PWD_ERROR(8550, "密码格式错误"), - VERIFY_OUT(8400, "已经验证过了"); - private final int code; - private final String msg; - - - ResponseEnum(int code, String msg) { - this.code = code; - this.msg = msg; - } - - public int getCode() { - return code; - } - - public String getMsg() { - return msg; - } -} +package cn.celess.common.enmu; + +/** + * @author : xiaohai + * @date : 2019/03/28 15:37 + */ +public enum ResponseEnum { + // Response enum + + SUCCESS(0, "成功"), + FAILURE(-1, "失败"), + ERROR(-2, "错误"), + + DATA_IS_DELETED(1000, "数据已被删除"), + + //文章类 + ARTICLE_NOT_EXIST(2010, "文章不存在"), + ARTICLE_HAS_EXIST(2020, "文章已存在"), + ARTICLE_NOT_PUBLIC(2030, "文章暂未公开"), + ARTICLE_NOT_BELONG_YOU(2040, "无权限操作别人的文章"), + + //用户类 + HAVE_NOT_LOG_IN(3010, "还未登录"), + PERMISSION_ERROR(3020, "没有此权限"), + USER_NOT_EXIST(3030, "用户不存在"), + USERNAME_HAS_EXIST(3040, "用户名已存在"), + USERNAME_TOO_SHORT(3050, "用户名太短"), + PASSWORD_TOO_SHORT_OR_LONG(3060, "密码长度过长或者过短"), + LOGIN_FAILURE(3100, "登录失败,用户名/密码不正确"), + USEREMAIL_NULL(3310, "未设置邮箱"), + USEREMAIL_NOT_VERIFY(3320, "邮箱未验证"), + LOGIN_LATER(3500, "错误次数已达5次,请稍后再试"), + PWD_SAME(3601, "新密码与原密码相同"), + PWD_NOT_SAME(3602, "新密码与原密码不相同"), + LOGIN_EXPIRED(3700, "登陆过期"), + LOGOUT(3710, "账户已注销"), + CAN_NOT_USE(3711, "账户不可用"), + PWD_WRONG(3800, "密码不正确"), + + JWT_EXPIRED(3810, "Token过期"), + JWT_MALFORMED(3820, "Token格式不对"), + JWT_SIGNATURE(3830, "Token签名错误"), + JWT_NOT_SUPPORT(3840, "不支持的Token"), + + //标签 + TAG_NOT_EXIST(4010, "标签不存在"), + TAG_HAS_EXIST(4020, "标签已存在"), + + //分类 + CATEGORY_NOT_EXIST(5010, "分类不存在"), + CATEGORY_HAS_EXIST(5020, "分类已存在"), + + //评论/留言 + COMMENT_NOT_EXIST(6010, "评论/留言不存在"), + COMMENT_HAS_EXIST(6020, "评论/留言已存在,请不要重复提交"), + + //webUdpateInfo amd PartnerSite + DATA_NOT_EXIST(7010, "数据不存在"), + DATA_HAS_EXIST(7020, "数据已存在"), + + //其他 + APPLY_LINK_NO_ADD_THIS_SITE(7200, "暂未在您的网站中抓取到本站链接"), + DATA_EXPIRED(7300, "数据过期"), + CANNOT_GET_DATA(7400, "暂无法获取到数据"), + NO_FILE(7500, "未选择文件,请重新选择"), + + + //提交更新之前,没有获取数据/, + DID_NOT_GET_THE_DATA(8020, "非法访问"), + IMG_CODE_TIMEOUT(8100, "验证码已失效"), + IMG_CODE_DIDNOTVERIFY(8200, "请先验证验证码"), + VERIFY_ERROR(8300, "验证失败"), + PARAMETERS_ERROR(8500, "参数错误"), + PARAMETERS_URL_ERROR(8510, "链接格式错误"), + PARAMETERS_EMAIL_ERROR(8520, "邮箱格式错误"), + PARAMETERS_PHONE_ERROR(8530, "手机格式错误"), + PARAMETERS_QQ_ERROR(8540, "QQ格式错误"), + PARAMETERS_PWD_ERROR(8550, "密码格式错误"), + VERIFY_OUT(8400, "已经验证过了"); + private final int code; + private final String msg; + + + ResponseEnum(int code, String msg) { + this.code = code; + this.msg = msg; + } + + public int getCode() { + return code; + } + + public String getMsg() { + return msg; + } +} diff --git a/src/main/java/cn/celess/blog/enmu/RoleEnum.java b/blog-common/src/main/java/cn/celess/common/enmu/RoleEnum.java similarity index 91% rename from src/main/java/cn/celess/blog/enmu/RoleEnum.java rename to blog-common/src/main/java/cn/celess/common/enmu/RoleEnum.java index 8f399f2..d64d7c0 100644 --- a/src/main/java/cn/celess/blog/enmu/RoleEnum.java +++ b/blog-common/src/main/java/cn/celess/common/enmu/RoleEnum.java @@ -1,4 +1,4 @@ -package cn.celess.blog.enmu; +package cn.celess.common.enmu; import lombok.Getter; diff --git a/src/main/java/cn/celess/blog/enmu/UserAccountStatusEnum.java b/blog-common/src/main/java/cn/celess/common/enmu/UserAccountStatusEnum.java similarity index 98% rename from src/main/java/cn/celess/blog/enmu/UserAccountStatusEnum.java rename to blog-common/src/main/java/cn/celess/common/enmu/UserAccountStatusEnum.java index 31973e9..95250d3 100644 --- a/src/main/java/cn/celess/blog/enmu/UserAccountStatusEnum.java +++ b/blog-common/src/main/java/cn/celess/common/enmu/UserAccountStatusEnum.java @@ -1,4 +1,4 @@ -package cn.celess.blog.enmu; +package cn.celess.common.enmu; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; diff --git a/src/main/java/cn/celess/blog/entity/Article.java b/blog-common/src/main/java/cn/celess/common/entity/Article.java similarity index 88% rename from src/main/java/cn/celess/blog/entity/Article.java rename to blog-common/src/main/java/cn/celess/common/entity/Article.java index e3f3e47..6b04551 100644 --- a/src/main/java/cn/celess/blog/entity/Article.java +++ b/blog-common/src/main/java/cn/celess/common/entity/Article.java @@ -1,63 +1,64 @@ -package cn.celess.blog.entity; - -import lombok.Data; - -import java.util.Date; -import java.util.List; - -/** - * @author : xiaohai - * @date : 2019/03/28 14:51 - */ -@Data -public class Article { - private Long id; - - /** - * 标题 - */ - private String title; - - /** - * 摘要 - */ - private String summary; - - /** - * Markdown正文 - */ - private String mdContent; - - /** - * 文章类型 true(1)为原创 false(0)为转载 - */ - private Boolean type; - - /** - * 若为转载 则为转载文章的url - */ - private String url = null; - - private Date publishDate; - - private Date updateDate = null; - - private Long readingNumber; - - /** - * 文章的状态 true:公开 false:不公开 - */ - private Boolean open; - - private Category category; - - private List tags; - - private Integer likeCount; - - private Integer dislikeCount; - - private User user; - - private boolean deleted = false; -} +package cn.celess.common.entity; + +import lombok.Data; + +import java.io.Serializable; +import java.util.Date; +import java.util.List; + +/** + * @author : xiaohai + * @date : 2019/03/28 14:51 + */ +@Data +public class Article implements Serializable { + private Long id; + + /** + * 标题 + */ + private String title; + + /** + * 摘要 + */ + private String summary; + + /** + * Markdown正文 + */ + private String mdContent; + + /** + * 文章类型 true(1)为原创 false(0)为转载 + */ + private Boolean type; + + /** + * 若为转载 则为转载文章的url + */ + private String url = null; + + private Date publishDate; + + private Date updateDate = null; + + private Long readingNumber; + + /** + * 文章的状态 true:公开 false:不公开 + */ + private Boolean open; + + private Category category; + + private List tags; + + private Integer likeCount; + + private Integer dislikeCount; + + private User user; + + private boolean deleted = false; +} diff --git a/src/main/java/cn/celess/blog/entity/ArticleTag.java b/blog-common/src/main/java/cn/celess/common/entity/ArticleTag.java similarity index 78% rename from src/main/java/cn/celess/blog/entity/ArticleTag.java rename to blog-common/src/main/java/cn/celess/common/entity/ArticleTag.java index 6ba2184..d16da59 100644 --- a/src/main/java/cn/celess/blog/entity/ArticleTag.java +++ b/blog-common/src/main/java/cn/celess/common/entity/ArticleTag.java @@ -1,9 +1,11 @@ -package cn.celess.blog.entity; +package cn.celess.common.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; +import java.io.Serializable; + /** * @Author: 小海 * @Date: 2020-05-24 14:52 @@ -12,7 +14,7 @@ import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor -public class ArticleTag { +public class ArticleTag implements Serializable { private Long id; private Article article; diff --git a/src/main/java/cn/celess/blog/entity/Category.java b/blog-common/src/main/java/cn/celess/common/entity/Category.java similarity index 58% rename from src/main/java/cn/celess/blog/entity/Category.java rename to blog-common/src/main/java/cn/celess/common/entity/Category.java index 815f7aa..bb3405a 100644 --- a/src/main/java/cn/celess/blog/entity/Category.java +++ b/blog-common/src/main/java/cn/celess/common/entity/Category.java @@ -1,13 +1,15 @@ -package cn.celess.blog.entity; +package cn.celess.common.entity; import lombok.NoArgsConstructor; +import java.io.Serializable; + /** * @author : xiaohai * @date : 2019/03/28 22:18 */ @NoArgsConstructor -public class Category extends TagCategory { +public class Category extends TagCategory implements Serializable { public Category(String name) { super.setName(name); } diff --git a/src/main/java/cn/celess/blog/entity/Comment.java b/blog-common/src/main/java/cn/celess/common/entity/Comment.java similarity index 78% rename from src/main/java/cn/celess/blog/entity/Comment.java rename to blog-common/src/main/java/cn/celess/common/entity/Comment.java index 0651111..8cd059a 100644 --- a/src/main/java/cn/celess/blog/entity/Comment.java +++ b/blog-common/src/main/java/cn/celess/common/entity/Comment.java @@ -1,34 +1,35 @@ -package cn.celess.blog.entity; - -import lombok.Data; - -import java.util.Date; - -/** - * @author : xiaohai - * @date : 2019/03/29 16:47 - */ - -@Data -public class Comment { - - private Long id; - - private int status; - - private String pagePath; - - private String content; - - private Date date; - - private User fromUser; - - private User toUser; - /** - * 评论的父ID - */ - private Long pid; - - // private boolean delete; -} +package cn.celess.common.entity; + +import lombok.Data; + +import java.io.Serializable; +import java.util.Date; + +/** + * @author : xiaohai + * @date : 2019/03/29 16:47 + */ + +@Data +public class Comment implements Serializable { + + private Long id; + + private int status; + + private String pagePath; + + private String content; + + private Date date; + + private User fromUser; + + private User toUser; + /** + * 评论的父ID + */ + private Long pid; + + // private boolean delete; +} diff --git a/src/main/java/cn/celess/blog/entity/PartnerSite.java b/blog-common/src/main/java/cn/celess/common/entity/PartnerSite.java similarity index 82% rename from src/main/java/cn/celess/blog/entity/PartnerSite.java rename to blog-common/src/main/java/cn/celess/common/entity/PartnerSite.java index 87a26e2..48ad50f 100644 --- a/src/main/java/cn/celess/blog/entity/PartnerSite.java +++ b/blog-common/src/main/java/cn/celess/common/entity/PartnerSite.java @@ -1,40 +1,42 @@ -package cn.celess.blog.entity; - -import lombok.Data; - -/** - * 友链 - * - * @author : xiaohai - * @date : 2019/05/12 11:33 - */ -@Data -public class PartnerSite { - - private Long id; - - private String name; - - private String url; - - private Boolean open; - - private String iconPath; - - private String desc; - - private Boolean delete = false; - - private String email; - - private Boolean notification = true; - - public PartnerSite() { - } - - public PartnerSite(String name, String url, Boolean open) { - this.name = name; - this.url = url; - this.open = open; - } -} +package cn.celess.common.entity; + +import lombok.Data; + +import java.io.Serializable; + +/** + * 友链 + * + * @author : xiaohai + * @date : 2019/05/12 11:33 + */ +@Data +public class PartnerSite implements Serializable { + + private Long id; + + private String name; + + private String url; + + private Boolean open; + + private String iconPath; + + private String desc; + + private Boolean delete = false; + + private String email; + + private Boolean notification = true; + + public PartnerSite() { + } + + public PartnerSite(String name, String url, Boolean open) { + this.name = name; + this.url = url; + this.open = open; + } +} diff --git a/src/main/java/cn/celess/blog/entity/Response.java b/blog-common/src/main/java/cn/celess/common/entity/Response.java similarity index 91% rename from src/main/java/cn/celess/blog/entity/Response.java rename to blog-common/src/main/java/cn/celess/common/entity/Response.java index eec624c..3cad8ea 100644 --- a/src/main/java/cn/celess/blog/entity/Response.java +++ b/blog-common/src/main/java/cn/celess/common/entity/Response.java @@ -1,65 +1,65 @@ -package cn.celess.blog.entity; - -import cn.celess.blog.enmu.ResponseEnum; -import com.fasterxml.jackson.databind.ObjectMapper; -import lombok.Data; -import lombok.SneakyThrows; - -import java.io.Serializable; - -/** - * @author : xiaohai - * @date : 2019/03/28 15:24 - */ -@Data -public class Response implements Serializable { - private int code; - private String msg; - private T result; - - public Response() { - } - - public Response(int code, String msg, T result) { - this.code = code; - this.msg = msg; - this.result = result; - } - - /** - * 成功相应 - * - * @param result 结果 - * @return Response - */ - public static Response success(T result) { - return new Response(ResponseEnum.SUCCESS.getCode(), ResponseEnum.SUCCESS.getMsg(), result); - } - - /** - * 失败的响应 - * - * @param result 结果 - * @return Response - */ - public static Response failure(String result) { - return new Response(ResponseEnum.FAILURE.getCode(), ResponseEnum.FAILURE.getMsg(), result); - } - - /** - * 其他的响应 - * - * @param r 枚举常量 - * @param result 结果 - * @return Response - */ - public static Response response(ResponseEnum r, T result) { - return new Response(r.getCode(), r.getMsg(), result); - } - - @SneakyThrows - @Override - public String toString() { - return new ObjectMapper().writeValueAsString(this); - } -} +package cn.celess.common.entity; + +import cn.celess.common.enmu.ResponseEnum; +import com.fasterxml.jackson.databind.ObjectMapper; +import lombok.Data; +import lombok.SneakyThrows; + +import java.io.Serializable; + +/** + * @author : xiaohai + * @date : 2019/03/28 15:24 + */ +@Data +public class Response implements Serializable { + private int code; + private String msg; + private T result; + + public Response() { + } + + public Response(int code, String msg, T result) { + this.code = code; + this.msg = msg; + this.result = result; + } + + /** + * 成功相应 + * + * @param result 结果 + * @return Response + */ + public static Response success(T result) { + return new Response(ResponseEnum.SUCCESS.getCode(), ResponseEnum.SUCCESS.getMsg(), result); + } + + /** + * 失败的响应 + * + * @param result 结果 + * @return Response + */ + public static Response failure(String result) { + return new Response(ResponseEnum.FAILURE.getCode(), ResponseEnum.FAILURE.getMsg(), result); + } + + /** + * 其他的响应 + * + * @param r 枚举常量 + * @param result 结果 + * @return Response + */ + public static Response response(ResponseEnum r, T result) { + return new Response(r.getCode(), r.getMsg(), result); + } + + @SneakyThrows + @Override + public String toString() { + return new ObjectMapper().writeValueAsString(this); + } +} diff --git a/src/main/java/cn/celess/blog/entity/Tag.java b/blog-common/src/main/java/cn/celess/common/entity/Tag.java similarity index 58% rename from src/main/java/cn/celess/blog/entity/Tag.java rename to blog-common/src/main/java/cn/celess/common/entity/Tag.java index e120cd0..1875d4e 100644 --- a/src/main/java/cn/celess/blog/entity/Tag.java +++ b/blog-common/src/main/java/cn/celess/common/entity/Tag.java @@ -1,13 +1,15 @@ -package cn.celess.blog.entity; +package cn.celess.common.entity; import lombok.NoArgsConstructor; +import java.io.Serializable; + /** * @author : xiaohai * @date : 2019/03/28 22:19 */ @NoArgsConstructor -public class Tag extends TagCategory { +public class Tag extends TagCategory implements Serializable { public Tag(String name) { super.setName(name); diff --git a/src/main/java/cn/celess/blog/entity/TagCategory.java b/blog-common/src/main/java/cn/celess/common/entity/TagCategory.java similarity index 65% rename from src/main/java/cn/celess/blog/entity/TagCategory.java rename to blog-common/src/main/java/cn/celess/common/entity/TagCategory.java index 78ec3ed..2222f87 100644 --- a/src/main/java/cn/celess/blog/entity/TagCategory.java +++ b/blog-common/src/main/java/cn/celess/common/entity/TagCategory.java @@ -1,14 +1,16 @@ -package cn.celess.blog.entity; +package cn.celess.common.entity; import lombok.Data; +import java.io.Serializable; + /** * @Author: 小海 * @Date: 2020-05-24 14:03 * @Desc: */ @Data -public class TagCategory { +public class TagCategory implements Serializable { private Long id; private String name; diff --git a/src/main/java/cn/celess/blog/entity/User.java b/blog-common/src/main/java/cn/celess/common/entity/User.java similarity index 87% rename from src/main/java/cn/celess/blog/entity/User.java rename to blog-common/src/main/java/cn/celess/common/entity/User.java index f912025..741564e 100644 --- a/src/main/java/cn/celess/blog/entity/User.java +++ b/blog-common/src/main/java/cn/celess/common/entity/User.java @@ -1,53 +1,54 @@ -package cn.celess.blog.entity; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import lombok.Data; -import lombok.NoArgsConstructor; - -import java.util.Date; - -/** - * @author : xiaohai - * @date : 2019/03/28 14:52 - */ -@Data -@NoArgsConstructor -public class User { - private Long id; - - /** - * 邮箱 - */ - private String email; - - /** - * 密码 - */ - @JsonIgnore - private String pwd; - - /** - * 昵称 - */ - private String displayName; - - private Boolean emailStatus = false; - - /** - * 头像地址 - */ - private String avatarImgUrl; - - private String desc; - - private Date recentlyLandedDate; - - private String role = "user"; - - private int status; - - public User(String email, String pwd) { - this.email = email; - this.pwd = pwd; - } -} +package cn.celess.common.entity; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.io.Serializable; +import java.util.Date; + +/** + * @author : xiaohai + * @date : 2019/03/28 14:52 + */ +@Data +@NoArgsConstructor +public class User implements Serializable { + private Long id; + + /** + * 邮箱 + */ + private String email; + + /** + * 密码 + */ + @JsonIgnore + private String pwd; + + /** + * 昵称 + */ + private String displayName; + + private Boolean emailStatus = false; + + /** + * 头像地址 + */ + private String avatarImgUrl; + + private String desc; + + private Date recentlyLandedDate; + + private String role = "user"; + + private int status; + + public User(String email, String pwd) { + this.email = email; + this.pwd = pwd; + } +} diff --git a/src/main/java/cn/celess/blog/entity/Visitor.java b/blog-common/src/main/java/cn/celess/common/entity/Visitor.java similarity index 78% rename from src/main/java/cn/celess/blog/entity/Visitor.java rename to blog-common/src/main/java/cn/celess/common/entity/Visitor.java index 5767cf1..01eb14d 100644 --- a/src/main/java/cn/celess/blog/entity/Visitor.java +++ b/blog-common/src/main/java/cn/celess/common/entity/Visitor.java @@ -1,28 +1,29 @@ -package cn.celess.blog.entity; - -import lombok.Data; - -import java.util.Date; - -/** - * @author : xiaohai - * @date : 2019/04/02 22:14 - */ -@Data -public class Visitor { - - private long id; - private String ip; - private Date date; - private String ua; - private boolean delete; - - public Visitor(String ip, Date date, String ua) { - this.ip = ip; - this.date = date; - this.ua = ua; - } - - public Visitor() { - } -} +package cn.celess.common.entity; + +import lombok.Data; + +import java.io.Serializable; +import java.util.Date; + +/** + * @author : xiaohai + * @date : 2019/04/02 22:14 + */ +@Data +public class Visitor implements Serializable { + + private long id; + private String ip; + private Date date; + private String ua; + private boolean delete; + + public Visitor(String ip, Date date, String ua) { + this.ip = ip; + this.date = date; + this.ua = ua; + } + + public Visitor() { + } +} diff --git a/src/main/java/cn/celess/blog/entity/WebUpdate.java b/blog-common/src/main/java/cn/celess/common/entity/WebUpdate.java similarity index 75% rename from src/main/java/cn/celess/blog/entity/WebUpdate.java rename to blog-common/src/main/java/cn/celess/common/entity/WebUpdate.java index 4e2a99e..54814ad 100644 --- a/src/main/java/cn/celess/blog/entity/WebUpdate.java +++ b/blog-common/src/main/java/cn/celess/common/entity/WebUpdate.java @@ -1,28 +1,29 @@ -package cn.celess.blog.entity; - -import lombok.Data; - -import java.util.Date; - -/** - * @author : xiaohai - * @date : 2019/05/12 11:29 - */ -@Data -public class WebUpdate { - - private long id; - - private String updateInfo; - - private Date updateTime; - - private boolean delete; - - public WebUpdate() { - } - - public WebUpdate(String updateInfo) { - this.updateInfo = updateInfo; - } -} +package cn.celess.common.entity; + +import lombok.Data; + +import java.io.Serializable; +import java.util.Date; + +/** + * @author : xiaohai + * @date : 2019/05/12 11:29 + */ +@Data +public class WebUpdate implements Serializable { + + private long id; + + private String updateInfo; + + private Date updateTime; + + private boolean delete; + + public WebUpdate() { + } + + public WebUpdate(String updateInfo) { + this.updateInfo = updateInfo; + } +} diff --git a/src/main/java/cn/celess/blog/entity/request/ArticleReq.java b/blog-common/src/main/java/cn/celess/common/entity/dto/ArticleReq.java similarity index 72% rename from src/main/java/cn/celess/blog/entity/request/ArticleReq.java rename to blog-common/src/main/java/cn/celess/common/entity/dto/ArticleReq.java index e1312b4..d4c9ee7 100644 --- a/src/main/java/cn/celess/blog/entity/request/ArticleReq.java +++ b/blog-common/src/main/java/cn/celess/common/entity/dto/ArticleReq.java @@ -1,19 +1,21 @@ -package cn.celess.blog.entity.request; - -import lombok.Data; - -/** - * @author : xiaohai - * @date : 2019/06/01 22:46 - */ -@Data -public class ArticleReq { - private Long id; - private String title; - private String mdContent; - private String[] tags; - private Boolean type; - private String url; - private String category; - private Boolean open = true; -} +package cn.celess.common.entity.dto; + +import lombok.Data; + +import java.io.Serializable; + +/** + * @author : xiaohai + * @date : 2019/06/01 22:46 + */ +@Data +public class ArticleReq implements Serializable { + private Long id; + private String title; + private String mdContent; + private String[] tags; + private Boolean type; + private String url; + private String category; + private Boolean open = true; +} diff --git a/src/main/java/cn/celess/blog/entity/request/CommentReq.java b/blog-common/src/main/java/cn/celess/common/entity/dto/CommentReq.java similarity index 65% rename from src/main/java/cn/celess/blog/entity/request/CommentReq.java rename to blog-common/src/main/java/cn/celess/common/entity/dto/CommentReq.java index c322326..e730acc 100644 --- a/src/main/java/cn/celess/blog/entity/request/CommentReq.java +++ b/blog-common/src/main/java/cn/celess/common/entity/dto/CommentReq.java @@ -1,16 +1,18 @@ -package cn.celess.blog.entity.request; - -import lombok.Data; - -/** - * @author : xiaohai - * @date : 2019/06/02 10:35 - */ -@Data -public class CommentReq { - private Long id; - private String content; - private long pid = -1; - private String pagePath; - private long toUserId = -1; -} +package cn.celess.common.entity.dto; + +import lombok.Data; + +import java.io.Serializable; + +/** + * @author : xiaohai + * @date : 2019/06/02 10:35 + */ +@Data +public class CommentReq implements Serializable { + private Long id; + private String content; + private long pid = -1; + private String pagePath; + private long toUserId = -1; +} diff --git a/src/main/java/cn/celess/blog/entity/request/LinkApplyReq.java b/blog-common/src/main/java/cn/celess/common/entity/dto/LinkApplyReq.java similarity index 67% rename from src/main/java/cn/celess/blog/entity/request/LinkApplyReq.java rename to blog-common/src/main/java/cn/celess/common/entity/dto/LinkApplyReq.java index 910332b..cfca015 100644 --- a/src/main/java/cn/celess/blog/entity/request/LinkApplyReq.java +++ b/blog-common/src/main/java/cn/celess/common/entity/dto/LinkApplyReq.java @@ -1,13 +1,15 @@ -package cn.celess.blog.entity.request; +package cn.celess.common.entity.dto; import lombok.Data; +import java.io.Serializable; + /** * @author : xiaohai * @date : 2020/07/31 20:50 */ @Data -public class LinkApplyReq { +public class LinkApplyReq implements Serializable { private String name; private String email; private String url; diff --git a/src/main/java/cn/celess/blog/entity/request/LinkReq.java b/blog-common/src/main/java/cn/celess/common/entity/dto/LinkReq.java similarity index 67% rename from src/main/java/cn/celess/blog/entity/request/LinkReq.java rename to blog-common/src/main/java/cn/celess/common/entity/dto/LinkReq.java index e7ed027..aa2b05b 100644 --- a/src/main/java/cn/celess/blog/entity/request/LinkReq.java +++ b/blog-common/src/main/java/cn/celess/common/entity/dto/LinkReq.java @@ -1,17 +1,19 @@ -package cn.celess.blog.entity.request; - -import lombok.Data; - -/** - * @author : xiaohai - * @date : 2019/06/02 11:40 - */ -@Data -public class LinkReq { - private long id; - private String name; - private String url; - private String iconPath; - private String desc; - private boolean open; -} +package cn.celess.common.entity.dto; + +import lombok.Data; + +import java.io.Serializable; + +/** + * @author : xiaohai + * @date : 2019/06/02 11:40 + */ +@Data +public class LinkReq implements Serializable { + private long id; + private String name; + private String url; + private String iconPath; + private String desc; + private boolean open; +} diff --git a/src/main/java/cn/celess/blog/entity/request/LoginReq.java b/blog-common/src/main/java/cn/celess/common/entity/dto/LoginReq.java similarity index 74% rename from src/main/java/cn/celess/blog/entity/request/LoginReq.java rename to blog-common/src/main/java/cn/celess/common/entity/dto/LoginReq.java index 0ea98c1..efef7ea 100644 --- a/src/main/java/cn/celess/blog/entity/request/LoginReq.java +++ b/blog-common/src/main/java/cn/celess/common/entity/dto/LoginReq.java @@ -1,23 +1,25 @@ -package cn.celess.blog.entity.request; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * @author : xiaohai - * @date : 2019/06/01 22:47 - */ -@Data -@NoArgsConstructor -@AllArgsConstructor -public class LoginReq { - private String email; - private String password; - /** - * isRememberMe默认为false - */ - private Boolean isRememberMe = false; - -} - +package cn.celess.common.entity.dto; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.io.Serializable; + +/** + * @author : xiaohai + * @date : 2019/06/01 22:47 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class LoginReq implements Serializable { + private String email; + private String password; + /** + * isRememberMe默认为false + */ + private Boolean isRememberMe = false; + +} + diff --git a/src/main/java/cn/celess/blog/entity/request/UserReq.java b/blog-common/src/main/java/cn/celess/common/entity/dto/UserReq.java similarity index 72% rename from src/main/java/cn/celess/blog/entity/request/UserReq.java rename to blog-common/src/main/java/cn/celess/common/entity/dto/UserReq.java index 5bbad0b..5eae376 100644 --- a/src/main/java/cn/celess/blog/entity/request/UserReq.java +++ b/blog-common/src/main/java/cn/celess/common/entity/dto/UserReq.java @@ -1,26 +1,28 @@ -package cn.celess.blog.entity.request; - -import lombok.Data; - -/** - * @Author: 小海 - * @Date: 2019/09/06 13:33 - * @Description: - */ -@Data -public class UserReq { - private Long id; - - private String email; - - private String pwd; - - private String displayName; - - private Boolean emailStatus; - - private String desc; - - private String role; - -} +package cn.celess.common.entity.dto; + +import lombok.Data; + +import java.io.Serializable; + +/** + * @Author: 小海 + * @Date: 2019/09/06 13:33 + * @Description: + */ +@Data +public class UserReq implements Serializable { + private Long id; + + private String email; + + private String pwd; + + private String displayName; + + private Boolean emailStatus; + + private String desc; + + private String role; + +} diff --git a/src/main/java/cn/celess/blog/entity/model/ArticleModel.java b/blog-common/src/main/java/cn/celess/common/entity/vo/ArticleModel.java similarity index 86% rename from src/main/java/cn/celess/blog/entity/model/ArticleModel.java rename to blog-common/src/main/java/cn/celess/common/entity/vo/ArticleModel.java index ef74da9..2f54c60 100644 --- a/src/main/java/cn/celess/blog/entity/model/ArticleModel.java +++ b/blog-common/src/main/java/cn/celess/common/entity/vo/ArticleModel.java @@ -1,87 +1,88 @@ -package cn.celess.blog.entity.model; - -import cn.celess.blog.entity.Tag; -import lombok.Getter; -import lombok.Setter; - -import java.util.List; - -/** - * @author : xiaohai - * @date : 2019/04/23 12:02 - */ -@Getter -@Setter -public class ArticleModel { - private Long id; - - /** - * 标题 - */ - private String title; - - /** - * 摘要 - */ - private String summary; - - /** - * Markdown正文 - */ - private String mdContent; - - /** - * 文章类型 true(1)为原创 false(0)为转载 - */ - private Boolean original; - - /** - * 若为转载 则为转载文章的url - */ - private String url; - - /** - * 发布时间 - */ - private String publishDateFormat; - - /** - * 更新时间 - */ - private String updateDateFormat; - - /** - * 分类 - */ - private String category; - - /** - * 标签 - */ - private List tags; - - /** - * 作者 - */ - private UserModel author; - - private ArticleModel preArticle; - - private ArticleModel nextArticle; - - /** - * 阅读数 - */ - private Long readingNumber; - - private Integer likeCount; - - private Integer dislikeCount; - - /** - * 文章的状态 true:公开 false:不公开 - */ - private Boolean open; - - private boolean deleted; -} +package cn.celess.common.entity.vo; + +import cn.celess.common.entity.Tag; +import lombok.Getter; +import lombok.Setter; + +import java.io.Serializable; +import java.util.List; + +/** + * @author : xiaohai + * @date : 2019/04/23 12:02 + */ +@Getter +@Setter +public class ArticleModel implements Serializable { + private Long id; + + /** + * 标题 + */ + private String title; + + /** + * 摘要 + */ + private String summary; + + /** + * Markdown正文 + */ + private String mdContent; + + /** + * 文章类型 true(1)为原创 false(0)为转载 + */ + private Boolean original; + + /** + * 若为转载 则为转载文章的url + */ + private String url; + + /** + * 发布时间 + */ + private String publishDateFormat; + + /** + * 更新时间 + */ + private String updateDateFormat; + + /** + * 分类 + */ + private String category; + + /** + * 标签 + */ + private List tags; + + /** + * 作者 + */ + private UserModel author; + + private ArticleModel preArticle; + + private ArticleModel nextArticle; + + /** + * 阅读数 + */ + private Long readingNumber; + + private Integer likeCount; + + private Integer dislikeCount; + + /** + * 文章的状态 true:公开 false:不公开 + */ + private Boolean open; + + private boolean deleted; +} diff --git a/src/main/java/cn/celess/blog/entity/model/CategoryModel.java b/blog-common/src/main/java/cn/celess/common/entity/vo/CategoryModel.java similarity index 74% rename from src/main/java/cn/celess/blog/entity/model/CategoryModel.java rename to blog-common/src/main/java/cn/celess/common/entity/vo/CategoryModel.java index 1af5bd4..21ae276 100644 --- a/src/main/java/cn/celess/blog/entity/model/CategoryModel.java +++ b/blog-common/src/main/java/cn/celess/common/entity/vo/CategoryModel.java @@ -1,9 +1,10 @@ -package cn.celess.blog.entity.model; +package cn.celess.common.entity.vo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; +import java.io.Serializable; import java.util.List; /** @@ -14,7 +15,7 @@ import java.util.List; @Data @NoArgsConstructor @AllArgsConstructor -public class CategoryModel { +public class CategoryModel implements Serializable { private Long id; private String name; diff --git a/src/main/java/cn/celess/blog/entity/model/CommentModel.java b/blog-common/src/main/java/cn/celess/common/entity/vo/CommentModel.java similarity index 82% rename from src/main/java/cn/celess/blog/entity/model/CommentModel.java rename to blog-common/src/main/java/cn/celess/common/entity/vo/CommentModel.java index ad9de7b..03bc402 100644 --- a/src/main/java/cn/celess/blog/entity/model/CommentModel.java +++ b/blog-common/src/main/java/cn/celess/common/entity/vo/CommentModel.java @@ -1,44 +1,45 @@ -package cn.celess.blog.entity.model; - -import lombok.Getter; -import lombok.Setter; - -import java.util.List; - -/** - * @author : xiaohai - * @date : 2019/04/22 21:50 - */ -@Setter -@Getter -public class CommentModel { - private long id; - - private UserModel fromUser; - - private UserModel toUser; - - /** - * 内容 - */ - private String content; - - /** - * 文章标题 - */ - private String pagePath; - - /** - * 发布日期 - */ - private String date; - - /** - * 评论的父ID - */ - private Long pid; - - private List respComment; - - private int status; -} +package cn.celess.common.entity.vo; + +import lombok.Getter; +import lombok.Setter; + +import java.io.Serializable; +import java.util.List; + +/** + * @author : xiaohai + * @date : 2019/04/22 21:50 + */ +@Setter +@Getter +public class CommentModel implements Serializable { + private long id; + + private UserModel fromUser; + + private UserModel toUser; + + /** + * 内容 + */ + private String content; + + /** + * 文章标题 + */ + private String pagePath; + + /** + * 发布日期 + */ + private String date; + + /** + * 评论的父ID + */ + private Long pid; + + private List respComment; + + private int status; +} diff --git a/src/main/java/cn/celess/blog/entity/model/PageData.java b/blog-common/src/main/java/cn/celess/common/entity/vo/PageData.java similarity index 85% rename from src/main/java/cn/celess/blog/entity/model/PageData.java rename to blog-common/src/main/java/cn/celess/common/entity/vo/PageData.java index 5e75273..f3a08f3 100644 --- a/src/main/java/cn/celess/blog/entity/model/PageData.java +++ b/blog-common/src/main/java/cn/celess/common/entity/vo/PageData.java @@ -1,10 +1,11 @@ -package cn.celess.blog.entity.model; +package cn.celess.common.entity.vo; import com.github.pagehelper.PageInfo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; +import java.io.Serializable; import java.util.List; /** @@ -15,7 +16,7 @@ import java.util.List; @Data @AllArgsConstructor @NoArgsConstructor -public class PageData { +public class PageData implements Serializable { private List list; diff --git a/src/main/java/cn/celess/blog/entity/model/QiniuResponse.java b/blog-common/src/main/java/cn/celess/common/entity/vo/QiniuResponse.java similarity index 56% rename from src/main/java/cn/celess/blog/entity/model/QiniuResponse.java rename to blog-common/src/main/java/cn/celess/common/entity/vo/QiniuResponse.java index 2048f14..1a7a696 100644 --- a/src/main/java/cn/celess/blog/entity/model/QiniuResponse.java +++ b/blog-common/src/main/java/cn/celess/common/entity/vo/QiniuResponse.java @@ -1,13 +1,15 @@ -package cn.celess.blog.entity.model; - - -/** - * @author : xiaohai - * @date : 2019/04/21 22:43 - */ -public class QiniuResponse { - public String key; - public String hash; - public String bucket; - public long fsize; -} +package cn.celess.common.entity.vo; + + +import java.io.Serializable; + +/** + * @author : xiaohai + * @date : 2019/04/21 22:43 + */ +public class QiniuResponse implements Serializable { + public String key; + public String hash; + public String bucket; + public long fsize; +} diff --git a/src/main/java/cn/celess/blog/entity/model/TagModel.java b/blog-common/src/main/java/cn/celess/common/entity/vo/TagModel.java similarity index 75% rename from src/main/java/cn/celess/blog/entity/model/TagModel.java rename to blog-common/src/main/java/cn/celess/common/entity/vo/TagModel.java index c3d7265..8f556fe 100644 --- a/src/main/java/cn/celess/blog/entity/model/TagModel.java +++ b/blog-common/src/main/java/cn/celess/common/entity/vo/TagModel.java @@ -1,9 +1,10 @@ -package cn.celess.blog.entity.model; +package cn.celess.common.entity.vo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; +import java.io.Serializable; import java.util.List; /** @@ -14,7 +15,7 @@ import java.util.List; @Data @NoArgsConstructor @AllArgsConstructor -public class TagModel { +public class TagModel implements Serializable { private Long id; private String name; diff --git a/src/main/java/cn/celess/blog/entity/model/UserModel.java b/blog-common/src/main/java/cn/celess/common/entity/vo/UserModel.java similarity index 76% rename from src/main/java/cn/celess/blog/entity/model/UserModel.java rename to blog-common/src/main/java/cn/celess/common/entity/vo/UserModel.java index cc925fd..52cb692 100644 --- a/src/main/java/cn/celess/blog/entity/model/UserModel.java +++ b/blog-common/src/main/java/cn/celess/common/entity/vo/UserModel.java @@ -1,43 +1,45 @@ -package cn.celess.blog.entity.model; - -import cn.celess.blog.enmu.UserAccountStatusEnum; -import lombok.Getter; -import lombok.Setter; - -/** - * @author : xiaohai - * @date : 2019/04/22 23:13 - */ -@Getter -@Setter -public class UserModel { - - private Long id; - - /** - * 邮箱 - */ - private String email; - - /** - * 昵称 - */ - private String displayName; - - private Boolean emailStatus = false; - - /** - * 头像地址 - */ - private String avatarImgUrl; - - private String desc; - - private String recentlyLandedDate; - - private String role = "user"; - - private String token; - - private UserAccountStatusEnum status; -} +package cn.celess.common.entity.vo; + +import cn.celess.common.enmu.UserAccountStatusEnum; +import lombok.Getter; +import lombok.Setter; + +import java.io.Serializable; + +/** + * @author : xiaohai + * @date : 2019/04/22 23:13 + */ +@Getter +@Setter +public class UserModel implements Serializable { + + private Long id; + + /** + * 邮箱 + */ + private String email; + + /** + * 昵称 + */ + private String displayName; + + private Boolean emailStatus = false; + + /** + * 头像地址 + */ + private String avatarImgUrl; + + private String desc; + + private String recentlyLandedDate; + + private String role = "user"; + + private String token; + + private UserAccountStatusEnum status; +} diff --git a/src/main/java/cn/celess/blog/entity/model/VisitorModel.java b/blog-common/src/main/java/cn/celess/common/entity/vo/VisitorModel.java similarity index 70% rename from src/main/java/cn/celess/blog/entity/model/VisitorModel.java rename to blog-common/src/main/java/cn/celess/common/entity/vo/VisitorModel.java index 6afd55c..578ae02 100644 --- a/src/main/java/cn/celess/blog/entity/model/VisitorModel.java +++ b/blog-common/src/main/java/cn/celess/common/entity/vo/VisitorModel.java @@ -1,24 +1,26 @@ -package cn.celess.blog.entity.model; - -import lombok.Data; - -/** - * @author : xiaohai - * @date : 2019/05/05 16:05 - */ -@Data -public class VisitorModel { - private long id; - - private String ip; - - private String date; - - private String browserName; - - private String browserVersion; - - private String OSName; - - private String location; -} +package cn.celess.common.entity.vo; + +import lombok.Data; + +import java.io.Serializable; + +/** + * @author : xiaohai + * @date : 2019/05/05 16:05 + */ +@Data +public class VisitorModel implements Serializable { + private long id; + + private String ip; + + private String date; + + private String browserName; + + private String browserVersion; + + private String OSName; + + private String location; +} diff --git a/src/main/java/cn/celess/blog/entity/model/WebUpdateModel.java b/blog-common/src/main/java/cn/celess/common/entity/vo/WebUpdateModel.java similarity index 76% rename from src/main/java/cn/celess/blog/entity/model/WebUpdateModel.java rename to blog-common/src/main/java/cn/celess/common/entity/vo/WebUpdateModel.java index 15aacb8..0f05b15 100644 --- a/src/main/java/cn/celess/blog/entity/model/WebUpdateModel.java +++ b/blog-common/src/main/java/cn/celess/common/entity/vo/WebUpdateModel.java @@ -1,26 +1,28 @@ -package cn.celess.blog.entity.model; - -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * @author : xiaohai - * @date : 2019/05/12 11:32 - */ -@Data -@NoArgsConstructor -public class WebUpdateModel { - private long id; - - private String info; - - private String time; - - public WebUpdateModel(long id, String info, String time) { - this.id = id; - this.info = info; - this.time = time; - } - - private boolean deleted; -} +package cn.celess.common.entity.vo; + +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.io.Serializable; + +/** + * @author : xiaohai + * @date : 2019/05/12 11:32 + */ +@Data +@NoArgsConstructor +public class WebUpdateModel implements Serializable { + private long id; + + private String info; + + private String time; + + public WebUpdateModel(long id, String info, String time) { + this.id = id; + this.info = info; + this.time = time; + } + + private boolean deleted; +} diff --git a/src/main/java/cn/celess/blog/exception/ExceptionHandle.java b/blog-common/src/main/java/cn/celess/common/exception/ExceptionHandle.java similarity index 93% rename from src/main/java/cn/celess/blog/exception/ExceptionHandle.java rename to blog-common/src/main/java/cn/celess/common/exception/ExceptionHandle.java index 0b85dd8..23961ea 100644 --- a/src/main/java/cn/celess/blog/exception/ExceptionHandle.java +++ b/blog-common/src/main/java/cn/celess/common/exception/ExceptionHandle.java @@ -1,100 +1,101 @@ -package cn.celess.blog.exception; - -import cn.celess.blog.enmu.ResponseEnum; -import cn.celess.blog.entity.Response; -import cn.celess.blog.service.MailService; -import cn.celess.blog.util.DateFormatUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.mail.SimpleMailMessage; -import org.springframework.validation.BindException; -import org.springframework.web.HttpRequestMethodNotSupportedException; -import org.springframework.web.bind.MissingServletRequestParameterException; -import org.springframework.web.bind.annotation.ControllerAdvice; -import org.springframework.web.bind.annotation.ExceptionHandler; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; - -import javax.servlet.http.HttpServletRequest; - -/** - * @author : xiaohai - * @date : 2019/03/28 17:02 - */ - -@ControllerAdvice -public class ExceptionHandle { - public static final Logger logger = LoggerFactory.getLogger(ExceptionHandle.class); - @Autowired - MailService mailService; - @Autowired - HttpServletRequest request; - @Value("${spring.profiles.active}") - private String activeModel; - - @ExceptionHandler(value = Exception.class) - @ResponseBody - public Response handle(Exception e) { - //自定义错误 - if (e instanceof MyException) { - MyException exception = (MyException) e; - logger.debug("返回了自定义的exception,[code={},msg={},result={}]", exception.getCode(), e.getMessage(), exception.getResult()); - return new Response(exception.getCode(), e.getMessage(), exception.getResult()); - } - //请求路径不支持该方法 - if (e instanceof HttpRequestMethodNotSupportedException) { - logger.debug("遇到请求路径与请求方法不匹配的请求,[msg={},path:{},method:{}]", e.getMessage(), request.getRequestURL(), request.getMethod()); - return new Response(ResponseEnum.ERROR.getCode(), e.getMessage(), null); - } - //数据输入类型不匹配 - if (e instanceof MethodArgumentTypeMismatchException) { - logger.debug("输入类型不匹配,[msg={}]", e.getMessage()); - return new Response(ResponseEnum.PARAMETERS_ERROR.getCode(), "数据输入有问题,请修改后再访问", null); - } - //数据验证失败 - if (e instanceof BindException) { - logger.debug("数据验证失败,[msg={}]", e.getMessage()); - return new Response(ResponseEnum.PARAMETERS_ERROR.getCode(), "数据输入有问题,请修改", null); - } - //数据输入不完整 - if (e instanceof MissingServletRequestParameterException) { - logger.debug("数据输入不完整,[msg={}]", e.getMessage()); - return new Response(ResponseEnum.PARAMETERS_ERROR.getCode(), "数据输入不完整,请检查", null); - } - - // 发送错误信息到邮箱 - if ("prod".equals(activeModel)) { - logger.debug("有一个未捕获的bug,已发送到邮箱"); - sendMessage(e); - } - e.printStackTrace(); - return new Response(ResponseEnum.ERROR.getCode(), "服务器出现错误,已记录", null); - } - - /** - * 发送错误信息 - * - * @param e 错误 - */ - private void sendMessage(Exception e) { - SimpleMailMessage simpleMailMessage = new SimpleMailMessage(); - simpleMailMessage.setTo("a@celess.cn"); - simpleMailMessage.setSubject("服务器出现了错误"); - StringBuilder msg = new StringBuilder(); - String queryString = request.getQueryString(); - msg.append("requirePath:\n").append(request.getRequestURL().toString()); - if (queryString != null) { - msg.append("?").append(queryString); - } - msg.append("\n\n\n"); - msg.append("msg:\n").append(e.getMessage()).append("\n\n\n"); - msg.append("date:\n").append(DateFormatUtil.getNow()).append("\n\n\n"); - msg.append("from:\n").append(request.getHeader("User-Agent")).append("\n\n\n"); - msg.append("ip:\n").append(request.getRemoteAddr()).append("\n\n\n"); - simpleMailMessage.setText(msg.toString()); - mailService.AsyncSend(simpleMailMessage); - } - -} +package cn.celess.common.exception; + +import cn.celess.common.enmu.ResponseEnum; +import cn.celess.common.entity.Response; +import cn.celess.common.service.MailService; +import cn.celess.common.util.DateFormatUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.mail.SimpleMailMessage; +import org.springframework.validation.BindException; +import org.springframework.web.HttpRequestMethodNotSupportedException; +import org.springframework.web.bind.MissingServletRequestParameterException; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; + +import javax.annotation.Resource; +import javax.servlet.http.HttpServletRequest; + +/** + * @author : xiaohai + * @date : 2019/03/28 17:02 + */ + +@ControllerAdvice +public class ExceptionHandle { + public static final Logger logger = LoggerFactory.getLogger(ExceptionHandle.class); + @Resource + MailService mailService; + @Autowired + HttpServletRequest request; + @Value("${spring.profiles.active}") + private String activeModel; + + @ExceptionHandler(value = Exception.class) + @ResponseBody + public Response handle(Exception e) { + //自定义错误 + if (e instanceof MyException) { + MyException exception = (MyException) e; + logger.debug("返回了自定义的exception,[code={},msg={},result={}]", exception.getCode(), e.getMessage(), exception.getResult()); + return new Response(exception.getCode(), e.getMessage(), exception.getResult()); + } + //请求路径不支持该方法 + if (e instanceof HttpRequestMethodNotSupportedException) { + logger.debug("遇到请求路径与请求方法不匹配的请求,[msg={},path:{},method:{}]", e.getMessage(), request.getRequestURL(), request.getMethod()); + return new Response(ResponseEnum.ERROR.getCode(), e.getMessage(), null); + } + //数据输入类型不匹配 + if (e instanceof MethodArgumentTypeMismatchException) { + logger.debug("输入类型不匹配,[msg={}]", e.getMessage()); + return new Response(ResponseEnum.PARAMETERS_ERROR.getCode(), "数据输入有问题,请修改后再访问", null); + } + //数据验证失败 + if (e instanceof BindException) { + logger.debug("数据验证失败,[msg={}]", e.getMessage()); + return new Response(ResponseEnum.PARAMETERS_ERROR.getCode(), "数据输入有问题,请修改", null); + } + //数据输入不完整 + if (e instanceof MissingServletRequestParameterException) { + logger.debug("数据输入不完整,[msg={}]", e.getMessage()); + return new Response(ResponseEnum.PARAMETERS_ERROR.getCode(), "数据输入不完整,请检查", null); + } + + // 发送错误信息到邮箱 + if ("prod".equals(activeModel)) { + logger.debug("有一个未捕获的bug,已发送到邮箱"); + sendMessage(e); + } + e.printStackTrace(); + return new Response(ResponseEnum.ERROR.getCode(), "服务器出现错误,已记录", null); + } + + /** + * 发送错误信息 + * + * @param e 错误 + */ + private void sendMessage(Exception e) { + SimpleMailMessage simpleMailMessage = new SimpleMailMessage(); + simpleMailMessage.setTo("a@celess.cn"); + simpleMailMessage.setSubject("服务器出现了错误"); + StringBuilder msg = new StringBuilder(); + String queryString = request.getQueryString(); + msg.append("requirePath:\n").append(request.getRequestURL().toString()); + if (queryString != null) { + msg.append("?").append(queryString); + } + msg.append("\n\n\n"); + msg.append("msg:\n").append(e.getMessage()).append("\n\n\n"); + msg.append("date:\n").append(DateFormatUtil.getNow()).append("\n\n\n"); + msg.append("from:\n").append(request.getHeader("User-Agent")).append("\n\n\n"); + msg.append("ip:\n").append(request.getRemoteAddr()).append("\n\n\n"); + simpleMailMessage.setText(msg.toString()); + mailService.AsyncSend(simpleMailMessage); + } + +} diff --git a/src/main/java/cn/celess/blog/exception/MyException.java b/blog-common/src/main/java/cn/celess/common/exception/MyException.java similarity index 87% rename from src/main/java/cn/celess/blog/exception/MyException.java rename to blog-common/src/main/java/cn/celess/common/exception/MyException.java index a681356..2df7428 100644 --- a/src/main/java/cn/celess/blog/exception/MyException.java +++ b/blog-common/src/main/java/cn/celess/common/exception/MyException.java @@ -1,41 +1,41 @@ -package cn.celess.blog.exception; - -import cn.celess.blog.enmu.ResponseEnum; -import lombok.Data; - -/** - * @author : xiaohai - * @date : 2019/03/28 16:56 - */ -@Data -public class MyException extends RuntimeException { - private int code; - private Object result; - - public MyException(int code, String msg) { - super(msg); - this.code = code; - } - - public MyException(ResponseEnum e) { - super(e.getMsg()); - this.code = e.getCode(); - } - - public MyException(ResponseEnum e, Object result) { - super(e.getMsg()); - this.code = e.getCode(); - this.result = result; - } - - public MyException(ResponseEnum e, String msg) { - super(msg + e.getMsg()); - this.code = e.getCode(); - } - - public MyException(ResponseEnum e, String msg, Object result) { - super(e.getMsg()); - this.code = e.getCode(); - this.result = result; - } -} +package cn.celess.common.exception; + +import cn.celess.common.enmu.ResponseEnum; +import lombok.Data; + +/** + * @author : xiaohai + * @date : 2019/03/28 16:56 + */ +@Data +public class MyException extends RuntimeException { + private int code; + private Object result; + + public MyException(int code, String msg) { + super(msg); + this.code = code; + } + + public MyException(ResponseEnum e) { + super(e.getMsg()); + this.code = e.getCode(); + } + + public MyException(ResponseEnum e, Object result) { + super(e.getMsg()); + this.code = e.getCode(); + this.result = result; + } + + public MyException(ResponseEnum e, String msg) { + super(msg + e.getMsg()); + this.code = e.getCode(); + } + + public MyException(ResponseEnum e, String msg, Object result) { + super(e.getMsg()); + this.code = e.getCode(); + this.result = result; + } +} diff --git a/src/main/java/cn/celess/blog/mapper/ArticleMapper.java b/blog-common/src/main/java/cn/celess/common/mapper/ArticleMapper.java similarity index 76% rename from src/main/java/cn/celess/blog/mapper/ArticleMapper.java rename to blog-common/src/main/java/cn/celess/common/mapper/ArticleMapper.java index 26e0881..10926ce 100644 --- a/src/main/java/cn/celess/blog/mapper/ArticleMapper.java +++ b/blog-common/src/main/java/cn/celess/common/mapper/ArticleMapper.java @@ -1,52 +1,55 @@ -package cn.celess.blog.mapper; - -import cn.celess.blog.entity.Article; -import org.apache.ibatis.annotations.Mapper; -import org.springframework.stereotype.Repository; - -import java.util.List; - -/** - * @Author: 小海 - * @Date: 2019/06/27 20:43 - * @Description: - */ -@Mapper -@Repository -public interface ArticleMapper { - - int insert(Article a); - - int delete(long id); - - int update(Article a); - - Article getLastestArticle(); - - Article findArticleById(long id); - - boolean existsByTitle(String title); - - boolean isDeletedById(long id); - - List
findAllByAuthorId(long authorId); - - List
findAllByOpen(boolean isOpen); - - String getTitleById(long id); - - List
findAllByCategoryId(long id); - - List
findAllByCategoryIdAndOpen(long id); - - List
findAll(); - - Article getPreArticle(Long id); - - Article getNextArticle(Long id); - - int updateReadingNumber(long id); - - long count(); - -} +package cn.celess.common.mapper; + +import cn.celess.common.entity.Article; +import org.apache.ibatis.annotations.Mapper; +import org.springframework.cache.annotation.Cacheable; +import org.springframework.stereotype.Repository; + +import java.util.List; + +/** + * @Author: 小海 + * @Date: 2019/06/27 20:43 + * @Description: + */ +@Mapper +@Repository +public interface ArticleMapper { + + int insert(Article a); + + int delete(long id); + + int update(Article a); + + Article getLastestArticle(); + + Article findArticleById(long id); + + boolean existsByTitle(String title); + + boolean isDeletedById(long id); + + List
findAllByAuthorId(long authorId); + + List
findAllByOpen(boolean isOpen); + + String getTitleById(long id); + + List
findAllByCategoryId(long id); + + List
findAllByCategoryIdAndOpen(long id); + + List
findAll(); + + @Cacheable(value = {"articleDao"}, key = "'getPreArticle:'+#id") + Article getPreArticle(Long id); + + @Cacheable(value = {"articleDao"}, key = "'getNextArticle:'+#id") + Article getNextArticle(Long id); + + int updateReadingNumber(long id); + + long count(); + +} diff --git a/src/main/java/cn/celess/blog/mapper/ArticleTagMapper.java b/blog-common/src/main/java/cn/celess/common/mapper/ArticleTagMapper.java similarity index 86% rename from src/main/java/cn/celess/blog/mapper/ArticleTagMapper.java rename to blog-common/src/main/java/cn/celess/common/mapper/ArticleTagMapper.java index 5620e8f..a794ea9 100644 --- a/src/main/java/cn/celess/blog/mapper/ArticleTagMapper.java +++ b/blog-common/src/main/java/cn/celess/common/mapper/ArticleTagMapper.java @@ -1,7 +1,7 @@ -package cn.celess.blog.mapper; +package cn.celess.common.mapper; -import cn.celess.blog.entity.ArticleTag; -import cn.celess.blog.entity.Tag; +import cn.celess.common.entity.ArticleTag; +import cn.celess.common.entity.Tag; import org.apache.ibatis.annotations.Mapper; import org.springframework.stereotype.Repository; diff --git a/src/main/java/cn/celess/blog/mapper/CategoryMapper.java b/blog-common/src/main/java/cn/celess/common/mapper/CategoryMapper.java similarity index 85% rename from src/main/java/cn/celess/blog/mapper/CategoryMapper.java rename to blog-common/src/main/java/cn/celess/common/mapper/CategoryMapper.java index 2fc9017..09999e0 100644 --- a/src/main/java/cn/celess/blog/mapper/CategoryMapper.java +++ b/blog-common/src/main/java/cn/celess/common/mapper/CategoryMapper.java @@ -1,42 +1,42 @@ -package cn.celess.blog.mapper; - -import cn.celess.blog.entity.Category; -import org.apache.ibatis.annotations.Mapper; -import org.springframework.stereotype.Repository; - -import java.util.List; - -/** - * @Author: 小海 - * @Date: 2019/06/30 12:56 - * @Description: - */ -@Mapper -@Repository -public interface CategoryMapper { - int insert(Category c); - - int delete(long id); - - int update(Category c); - - boolean existsByName(String name); - - boolean existsById(long id); - - Category findCategoryByName(String name); - - Category findCategoryById(long id); - - List findAll(); - - List getAllName(); - - String getNameById(long id); - - Long getIdByName(String name); - - Category getLastestCategory(); - - long count(); -} +package cn.celess.common.mapper; + +import cn.celess.common.entity.Category; +import org.apache.ibatis.annotations.Mapper; +import org.springframework.stereotype.Repository; + +import java.util.List; + +/** + * @Author: 小海 + * @Date: 2019/06/30 12:56 + * @Description: + */ +@Mapper +@Repository +public interface CategoryMapper { + int insert(Category c); + + int delete(long id); + + int update(Category c); + + boolean existsByName(String name); + + boolean existsById(long id); + + Category findCategoryByName(String name); + + Category findCategoryById(long id); + + List findAll(); + + List getAllName(); + + String getNameById(long id); + + Long getIdByName(String name); + + Category getLastestCategory(); + + long count(); +} diff --git a/src/main/java/cn/celess/blog/mapper/CommentMapper.java b/blog-common/src/main/java/cn/celess/common/mapper/CommentMapper.java similarity index 88% rename from src/main/java/cn/celess/blog/mapper/CommentMapper.java rename to blog-common/src/main/java/cn/celess/common/mapper/CommentMapper.java index 84af53a..0efa7b8 100644 --- a/src/main/java/cn/celess/blog/mapper/CommentMapper.java +++ b/blog-common/src/main/java/cn/celess/common/mapper/CommentMapper.java @@ -1,44 +1,44 @@ -package cn.celess.blog.mapper; - -import cn.celess.blog.entity.Comment; -import org.apache.ibatis.annotations.Mapper; -import org.springframework.stereotype.Repository; - -import java.util.List; - -/** - * @Author: 小海 - * @Date: 2019/06/30 16:19 - * @Description: - */ -@Mapper -@Repository -public interface CommentMapper { - int insert(Comment c); - - int updateContent(String content, long id); - - int delete(long id); - - int deleteByPagePath(String pagePath); - - boolean existsById(long id); - - Comment findCommentById(long id); - - Comment getLastestComment(); - - List findAllByFromUser(long id); - - List findAllByPid(long pid); - - List findAllByPagePath(String pagePath); - - List findAllByPagePathAndFromUser(String pagePath, long userId); - - List findAllByPagePathAndPidAndNormal(String pagePath, long pid); - - long countByPagePath(String pagePath); - - long count(); -} +package cn.celess.common.mapper; + +import cn.celess.common.entity.Comment; +import org.apache.ibatis.annotations.Mapper; +import org.springframework.stereotype.Repository; + +import java.util.List; + +/** + * @Author: 小海 + * @Date: 2019/06/30 16:19 + * @Description: + */ +@Mapper +@Repository +public interface CommentMapper { + int insert(Comment c); + + int updateContent(String content, long id); + + int delete(long id); + + int deleteByPagePath(String pagePath); + + boolean existsById(long id); + + Comment findCommentById(long id); + + Comment getLastestComment(); + + List findAllByFromUser(long id); + + List findAllByPid(long pid); + + List findAllByPagePath(String pagePath); + + List findAllByPagePathAndFromUser(String pagePath, long userId); + + List findAllByPagePathAndPidAndNormal(String pagePath, long pid); + + long countByPagePath(String pagePath); + + long count(); +} diff --git a/src/main/java/cn/celess/blog/mapper/PartnerMapper.java b/blog-common/src/main/java/cn/celess/common/mapper/PartnerMapper.java similarity index 85% rename from src/main/java/cn/celess/blog/mapper/PartnerMapper.java rename to blog-common/src/main/java/cn/celess/common/mapper/PartnerMapper.java index c1c2de6..cbde173 100644 --- a/src/main/java/cn/celess/blog/mapper/PartnerMapper.java +++ b/blog-common/src/main/java/cn/celess/common/mapper/PartnerMapper.java @@ -1,41 +1,41 @@ -package cn.celess.blog.mapper; - -import cn.celess.blog.entity.PartnerSite; -import org.apache.ibatis.annotations.Mapper; -import org.springframework.stereotype.Repository; - -import java.util.List; - -/** - * @Author: 小海 - * @Date: 2019/07/03 00:22 - * @Description: - */ -@Mapper -@Repository -public interface PartnerMapper { - int insert(PartnerSite site); - - int delete(long id); - - int update(PartnerSite site); - - boolean existsById(long id); - - boolean existsByName(String name); - - boolean existsByUrl(String url); - - PartnerSite findById(long id); - - PartnerSite findByName(String name); - - PartnerSite findByUrl(String url); - - PartnerSite getLastest(); - - List findAll(); - - List findAll(Boolean deleted); - -} +package cn.celess.common.mapper; + +import cn.celess.common.entity.PartnerSite; +import org.apache.ibatis.annotations.Mapper; +import org.springframework.stereotype.Repository; + +import java.util.List; + +/** + * @Author: 小海 + * @Date: 2019/07/03 00:22 + * @Description: + */ +@Mapper +@Repository +public interface PartnerMapper { + int insert(PartnerSite site); + + int delete(long id); + + int update(PartnerSite site); + + boolean existsById(long id); + + boolean existsByName(String name); + + boolean existsByUrl(String url); + + PartnerSite findById(long id); + + PartnerSite findByName(String name); + + PartnerSite findByUrl(String url); + + PartnerSite getLastest(); + + List findAll(); + + List findAll(Boolean deleted); + +} diff --git a/src/main/java/cn/celess/blog/mapper/TagMapper.java b/blog-common/src/main/java/cn/celess/common/mapper/TagMapper.java similarity index 83% rename from src/main/java/cn/celess/blog/mapper/TagMapper.java rename to blog-common/src/main/java/cn/celess/common/mapper/TagMapper.java index ed479c9..61766ca 100644 --- a/src/main/java/cn/celess/blog/mapper/TagMapper.java +++ b/blog-common/src/main/java/cn/celess/common/mapper/TagMapper.java @@ -1,34 +1,34 @@ -package cn.celess.blog.mapper; - -import cn.celess.blog.entity.Tag; -import org.apache.ibatis.annotations.Mapper; -import org.springframework.stereotype.Repository; - -import java.util.List; - -/** - * @Author: 小海 - * @Date: 2019/06/29 22:00 - * @Description: - */ -@Mapper -@Repository -public interface TagMapper { - int insert(Tag tag); - - int update(Tag tag); - - int delete(long id); - - Tag findTagById(long id); - - Tag findTagByName(String name); - - Boolean existsByName(String name); - - Tag getLastestTag(); - - List findAll(); - - long count(); -} +package cn.celess.common.mapper; + +import cn.celess.common.entity.Tag; +import org.apache.ibatis.annotations.Mapper; +import org.springframework.stereotype.Repository; + +import java.util.List; + +/** + * @Author: 小海 + * @Date: 2019/06/29 22:00 + * @Description: + */ +@Mapper +@Repository +public interface TagMapper { + int insert(Tag tag); + + int update(Tag tag); + + int delete(long id); + + Tag findTagById(long id); + + Tag findTagByName(String name); + + Boolean existsByName(String name); + + Tag getLastestTag(); + + List findAll(); + + long count(); +} diff --git a/src/main/java/cn/celess/blog/mapper/UserMapper.java b/blog-common/src/main/java/cn/celess/common/mapper/UserMapper.java similarity index 89% rename from src/main/java/cn/celess/blog/mapper/UserMapper.java rename to blog-common/src/main/java/cn/celess/common/mapper/UserMapper.java index 8f80077..9c9c3be 100644 --- a/src/main/java/cn/celess/blog/mapper/UserMapper.java +++ b/blog-common/src/main/java/cn/celess/common/mapper/UserMapper.java @@ -1,61 +1,61 @@ -package cn.celess.blog.mapper; - -import cn.celess.blog.entity.User; -import org.apache.ibatis.annotations.Mapper; -import org.springframework.stereotype.Repository; - -import java.util.List; - -/** - * @Author: 小海 - * @Date: 2019/07/03 00:23 - * @Description: - */ -@Mapper -@Repository -public interface UserMapper { - - int addUser(User user); - - int updateInfo(String desc, String displayName, long id); - - int updateAvatarImgUrl(String avatarImgUrl, long id); - - int updateLoginTime(String email); - - int updateEmailStatus(String email, boolean status); - - int updatePwd(String email, String pwd); - - String getPwd(String email); - - boolean existsByEmail(String email); - - User findByEmail(String email); - - User findById(long id); - - String getAvatarImgUrlById(long id); - - String getEmail(long id); - - String getDisPlayName(long id); - - String getRoleByEmail(String email); - - String getRoleById(long id); - - long count(); - - int delete(long id); - - int lock(long id); - - int setUserRole(Long id, String role); - - List findAll(Integer status); - - List findAll(); - - int update(User user); -} +package cn.celess.common.mapper; + +import cn.celess.common.entity.User; +import org.apache.ibatis.annotations.Mapper; +import org.springframework.stereotype.Repository; + +import java.util.List; + +/** + * @Author: 小海 + * @Date: 2019/07/03 00:23 + * @Description: + */ +@Mapper +@Repository +public interface UserMapper { + + int addUser(User user); + + int updateInfo(String desc, String displayName, long id); + + int updateAvatarImgUrl(String avatarImgUrl, long id); + + int updateLoginTime(String email); + + int updateEmailStatus(String email, boolean status); + + int updatePwd(String email, String pwd); + + String getPwd(String email); + + boolean existsByEmail(String email); + + User findByEmail(String email); + + User findById(long id); + + String getAvatarImgUrlById(long id); + + String getEmail(long id); + + String getDisPlayName(long id); + + String getRoleByEmail(String email); + + String getRoleById(long id); + + long count(); + + int delete(long id); + + int lock(long id); + + int setUserRole(Long id, String role); + + List findAll(Integer status); + + List findAll(); + + int update(User user); +} diff --git a/src/main/java/cn/celess/blog/mapper/VisitorMapper.java b/blog-common/src/main/java/cn/celess/common/mapper/VisitorMapper.java similarity index 80% rename from src/main/java/cn/celess/blog/mapper/VisitorMapper.java rename to blog-common/src/main/java/cn/celess/common/mapper/VisitorMapper.java index e47a661..1b60360 100644 --- a/src/main/java/cn/celess/blog/mapper/VisitorMapper.java +++ b/blog-common/src/main/java/cn/celess/common/mapper/VisitorMapper.java @@ -1,26 +1,26 @@ -package cn.celess.blog.mapper; - -import cn.celess.blog.entity.Visitor; -import org.apache.ibatis.annotations.Mapper; -import org.springframework.stereotype.Repository; - -import java.util.List; - -/** - * @Author: 小海 - * @Date: 2019/07/03 00:23 - * @Description: - */ -@Repository -@Mapper -public interface VisitorMapper { - int insert(Visitor visitor); - - int delete(long id); - - List findAll(); - - List findAllNotDeleted(); - - long count(); -} +package cn.celess.common.mapper; + +import cn.celess.common.entity.Visitor; +import org.apache.ibatis.annotations.Mapper; +import org.springframework.stereotype.Repository; + +import java.util.List; + +/** + * @Author: 小海 + * @Date: 2019/07/03 00:23 + * @Description: + */ +@Repository +@Mapper +public interface VisitorMapper { + int insert(Visitor visitor); + + int delete(long id); + + List findAll(); + + List findAllNotDeleted(); + + long count(); +} diff --git a/src/main/java/cn/celess/blog/mapper/WebUpdateInfoMapper.java b/blog-common/src/main/java/cn/celess/common/mapper/WebUpdateInfoMapper.java similarity index 83% rename from src/main/java/cn/celess/blog/mapper/WebUpdateInfoMapper.java rename to blog-common/src/main/java/cn/celess/common/mapper/WebUpdateInfoMapper.java index 9d57283..49cf306 100644 --- a/src/main/java/cn/celess/blog/mapper/WebUpdateInfoMapper.java +++ b/blog-common/src/main/java/cn/celess/common/mapper/WebUpdateInfoMapper.java @@ -1,32 +1,32 @@ -package cn.celess.blog.mapper; - -import cn.celess.blog.entity.WebUpdate; -import org.apache.ibatis.annotations.Mapper; -import org.springframework.stereotype.Repository; - -import java.util.List; - -/** - * @Author: 小海 - * @Date: 2019/07/03 00:24 - * @Description: - */ -@Mapper -@Repository -public interface WebUpdateInfoMapper { - int insert(WebUpdate webUpdate); - - int delete(long id); - - int update(long id, String info); - - boolean existsById(long id); - - WebUpdate findById(long id); - - List findAll(); - - List findAllNotDeleted(); - - WebUpdate getLastestOne(); -} +package cn.celess.common.mapper; + +import cn.celess.common.entity.WebUpdate; +import org.apache.ibatis.annotations.Mapper; +import org.springframework.stereotype.Repository; + +import java.util.List; + +/** + * @Author: 小海 + * @Date: 2019/07/03 00:24 + * @Description: + */ +@Mapper +@Repository +public interface WebUpdateInfoMapper { + int insert(WebUpdate webUpdate); + + int delete(long id); + + int update(long id, String info); + + boolean existsById(long id); + + WebUpdate findById(long id); + + List findAll(); + + List findAllNotDeleted(); + + WebUpdate getLastestOne(); +} diff --git a/src/main/java/cn/celess/blog/service/ArticleService.java b/blog-common/src/main/java/cn/celess/common/service/ArticleService.java similarity index 87% rename from src/main/java/cn/celess/blog/service/ArticleService.java rename to blog-common/src/main/java/cn/celess/common/service/ArticleService.java index f74b875..64ff920 100644 --- a/src/main/java/cn/celess/blog/service/ArticleService.java +++ b/blog-common/src/main/java/cn/celess/common/service/ArticleService.java @@ -1,85 +1,85 @@ -package cn.celess.blog.service; - -import cn.celess.blog.entity.model.ArticleModel; -import cn.celess.blog.entity.model.PageData; -import cn.celess.blog.entity.request.ArticleReq; -import org.springframework.stereotype.Service; - - -/** - * @author : xiaohai - * @date : 2019/03/28 15:20 - */ -@Service -public interface ArticleService { - /** - * 新增一篇文章 - * - * @param reqBody 请求文章的数据 - * @return 文章数据 - */ - ArticleModel create(ArticleReq reqBody); - - /** - * 删除一篇文章 - * - * @param articleID 文章id - * @return 删除状态 true:删除成功 false:失败 - */ - boolean delete(long articleID); - - /** - * 更新一篇文章 - * - * @param reqBody 请求数据 - * @return 文章数据 - */ - ArticleModel update(ArticleReq reqBody); - - /** - * 获取一篇文章的数据 - * - * @param articleId 文章id - * @param is4update 是否是因文章更新而请求数据 - * @return 文章数据 - */ - ArticleModel retrieveOneById(long articleId, boolean is4update); - - /** - * 管理员 获取分页数据 - * - * @param count 单页数据量 - * @param page 数据页 - * @return 分页数据 - */ - PageData adminArticles(int count, int page, Boolean deleted); - - /** - * 获取文章状态为开放的文章 - * - * @param count 单页数据量 - * @param page 数据页 - * @return 分页数据 - */ - PageData retrievePageForOpen(int count, int page); - - /** - * 根据分类名获取文章数据 - * - * @param name 分类名 - * @param count 单页数据量 - * @param page 数据页 - * @return 分页数据 - */ - PageData findByCategory(String name, int page, int count); - - /** - * 根据标签名获取文章数据 - * - * @param name 标签名 - * @param count 单页数据量 - * @param page 数据页 - * @return 分页数据 - */ - PageData findByTag(String name, int page, int count); -} +package cn.celess.common.service; + +import cn.celess.common.entity.dto.ArticleReq; +import cn.celess.common.entity.vo.ArticleModel; +import cn.celess.common.entity.vo.PageData; +import org.springframework.stereotype.Service; + + +/** + * @author : xiaohai + * @date : 2019/03/28 15:20 + */ +@Service +public interface ArticleService { + /** + * 新增一篇文章 + * + * @param reqBody 请求文章的数据 + * @return 文章数据 + */ + ArticleModel create(ArticleReq reqBody); + + /** + * 删除一篇文章 + * + * @param articleID 文章id + * @return 删除状态 true:删除成功 false:失败 + */ + boolean delete(long articleID); + + /** + * 更新一篇文章 + * + * @param reqBody 请求数据 + * @return 文章数据 + */ + ArticleModel update(ArticleReq reqBody); + + /** + * 获取一篇文章的数据 + * + * @param articleId 文章id + * @param is4update 是否是因文章更新而请求数据 + * @return 文章数据 + */ + ArticleModel retrieveOneById(long articleId, boolean is4update); + + /** + * 管理员 获取分页数据 + * + * @param count 单页数据量 + * @param page 数据页 + * @return 分页数据 + */ + PageData adminArticles(int count, int page, Boolean deleted); + + /** + * 获取文章状态为开放的文章 + * + * @param count 单页数据量 + * @param page 数据页 + * @return 分页数据 + */ + PageData retrievePageForOpen(int count, int page); + + /** + * 根据分类名获取文章数据 + * + * @param name 分类名 + * @param count 单页数据量 + * @param page 数据页 + * @return 分页数据 + */ + PageData findByCategory(String name, int page, int count); + + /** + * 根据标签名获取文章数据 + * + * @param name 标签名 + * @param count 单页数据量 + * @param page 数据页 + * @return 分页数据 + */ + PageData findByTag(String name, int page, int count); +} diff --git a/src/main/java/cn/celess/blog/service/CategoryService.java b/blog-common/src/main/java/cn/celess/common/service/CategoryService.java similarity index 82% rename from src/main/java/cn/celess/blog/service/CategoryService.java rename to blog-common/src/main/java/cn/celess/common/service/CategoryService.java index 6f29cbb..4e4c687 100644 --- a/src/main/java/cn/celess/blog/service/CategoryService.java +++ b/blog-common/src/main/java/cn/celess/common/service/CategoryService.java @@ -1,45 +1,45 @@ -package cn.celess.blog.service; - -import cn.celess.blog.entity.model.CategoryModel; -import cn.celess.blog.entity.model.PageData; -import org.springframework.stereotype.Service; - -/** - * @author : xiaohai - * @date : 2019/03/28 22:42 - */ -@Service -public interface CategoryService { - /** - * 增加一个分类 - * - * @param name 分类名 - * @return 所增加的分类数据 - */ - CategoryModel create(String name); - - /** - * 通过id删除分类 - * - * @param id 分类id - * @return 删除状态 - */ - boolean delete(long id); - - /** - * 编辑分类的名字 - * - * @param id 分类id - * @param name 分类名字 - * @return 更新后的分类的数据 - */ - CategoryModel update(Long id, String name); - - /** - * 获取全部的分类数据 - * - * @return 全部的分类数据 - */ - PageData retrievePage(int page, int count); - -} +package cn.celess.common.service; + +import cn.celess.common.entity.vo.CategoryModel; +import cn.celess.common.entity.vo.PageData; +import org.springframework.stereotype.Service; + +/** + * @author : xiaohai + * @date : 2019/03/28 22:42 + */ +@Service +public interface CategoryService { + /** + * 增加一个分类 + * + * @param name 分类名 + * @return 所增加的分类数据 + */ + CategoryModel create(String name); + + /** + * 通过id删除分类 + * + * @param id 分类id + * @return 删除状态 + */ + boolean delete(long id); + + /** + * 编辑分类的名字 + * + * @param id 分类id + * @param name 分类名字 + * @return 更新后的分类的数据 + */ + CategoryModel update(Long id, String name); + + /** + * 获取全部的分类数据 + * + * @return 全部的分类数据 + */ + PageData retrievePage(int page, int count); + +} diff --git a/src/main/java/cn/celess/blog/service/CommentService.java b/blog-common/src/main/java/cn/celess/common/service/CommentService.java similarity index 87% rename from src/main/java/cn/celess/blog/service/CommentService.java rename to blog-common/src/main/java/cn/celess/common/service/CommentService.java index 71879f6..43331b8 100644 --- a/src/main/java/cn/celess/blog/service/CommentService.java +++ b/blog-common/src/main/java/cn/celess/common/service/CommentService.java @@ -1,91 +1,92 @@ -package cn.celess.blog.service; - -import cn.celess.blog.entity.model.CommentModel; -import cn.celess.blog.entity.model.PageData; -import cn.celess.blog.entity.request.CommentReq; -import org.springframework.stereotype.Service; - -import java.util.List; - -/** - * @author : xiaohai - * @date : 2019/03/29 16:58 - */ -@Service -public interface CommentService { - /** - * 新增数据 - * - * @param reqBody 请求数据体 - * @return 增加的comment数据 - */ - CommentModel create(CommentReq reqBody); - - /** - * 删除数据 - * - * @param id comment的id - * @return 删除状态 - */ - boolean delete(long id); - - /** - * 更新数据 - * - * @param reqBody comment请求体 - * @return 更新后的数据 - */ - CommentModel update(CommentReq reqBody); - - /** - * 分页获取数据 - * - * @param pagePath pagePath - * @param count 单页数据量 - * @param page 数据页 - * @return 分页数据 - */ - PageData retrievePage(String pagePath, int page, int count); - - /** - * 通过pid获取数据 - * - * @param pid 父id - * @return 分页数据 - */ - List retrievePageByPid(long pid); - - - /** - * 根据评论者获取数据 - * - * @param pagePath pagePath - * @param count 单页数据量 - * @param page 数据页 - * @return 分页数据 - */ - PageData retrievePageByAuthor(String pagePath, int page, int count); - - - /** - * 根据数据的type和pid获取数据 - * - * @param pagePath pagePath - * @param pid 父id - * @param count 单页数据量 - * @param page 数据页 - * @return 分页数据 - */ - PageData retrievePageByPageAndPid(String pagePath, long pid, int page, int count); - - /** - * 根据type获取数据 - * - * @param pagePath pagePath - * @param count 单页数据量 - * @param page 数据页 - * @return 分页数据 - */ - PageData retrievePageByPage(String pagePath, int page, int count); - -} +package cn.celess.common.service; + + +import cn.celess.common.entity.dto.CommentReq; +import cn.celess.common.entity.vo.CommentModel; +import cn.celess.common.entity.vo.PageData; +import org.springframework.stereotype.Service; + +import java.util.List; + +/** + * @author : xiaohai + * @date : 2019/03/29 16:58 + */ +@Service +public interface CommentService { + /** + * 新增数据 + * + * @param reqBody 请求数据体 + * @return 增加的comment数据 + */ + CommentModel create(CommentReq reqBody); + + /** + * 删除数据 + * + * @param id comment的id + * @return 删除状态 + */ + boolean delete(long id); + + /** + * 更新数据 + * + * @param reqBody comment请求体 + * @return 更新后的数据 + */ + CommentModel update(CommentReq reqBody); + + /** + * 分页获取数据 + * + * @param pagePath pagePath + * @param count 单页数据量 + * @param page 数据页 + * @return 分页数据 + */ + PageData retrievePage(String pagePath, int page, int count); + + /** + * 通过pid获取数据 + * + * @param pid 父id + * @return 分页数据 + */ + List retrievePageByPid(long pid); + + + /** + * 根据评论者获取数据 + * + * @param pagePath pagePath + * @param count 单页数据量 + * @param page 数据页 + * @return 分页数据 + */ + PageData retrievePageByAuthor(String pagePath, int page, int count); + + + /** + * 根据数据的type和pid获取数据 + * + * @param pagePath pagePath + * @param pid 父id + * @param count 单页数据量 + * @param page 数据页 + * @return 分页数据 + */ + PageData retrievePageByPageAndPid(String pagePath, long pid, int page, int count); + + /** + * 根据type获取数据 + * + * @param pagePath pagePath + * @param count 单页数据量 + * @param page 数据页 + * @return 分页数据 + */ + PageData retrievePageByPage(String pagePath, int page, int count); + +} diff --git a/src/main/java/cn/celess/blog/service/CountService.java b/blog-common/src/main/java/cn/celess/common/service/CountService.java similarity index 90% rename from src/main/java/cn/celess/blog/service/CountService.java rename to blog-common/src/main/java/cn/celess/common/service/CountService.java index 7267ece..e010e6c 100644 --- a/src/main/java/cn/celess/blog/service/CountService.java +++ b/blog-common/src/main/java/cn/celess/common/service/CountService.java @@ -1,59 +1,59 @@ -package cn.celess.blog.service; - -import org.springframework.stereotype.Service; - -/** - * @author : xiaohai - * @date : 2019/04/02 22:04 - */ -@Service -public interface CountService { - /** - * 获取评论的数据量 - * - * @return 评论的数据量 - */ - long getCommentCount(); - - /** - * 获取文章的篇数 - * - * @return 文章的篇数 - */ - long getArticleCount(); - - /** - * 获取分类数量 - * - * @return 分类数量 - */ - long getCategoriesCount(); - - /** - * 获取标签数量 - * - * @return 标签数量 - */ - long getTagsCount(); - - /** - * 获取用户量 - * - * @return 用户量 - */ - long getUserCount(); - - /** - * 获取总访问量 - * - * @return 总访问量 - */ - long getVisitorCount(); - - /** - * 获取日访问量 - * - * @return 日访问量 - */ - long getDayVisitCount(); -} +package cn.celess.common.service; + +import org.springframework.stereotype.Service; + +/** + * @author : xiaohai + * @date : 2019/04/02 22:04 + */ +@Service +public interface CountService { + /** + * 获取评论的数据量 + * + * @return 评论的数据量 + */ + long getCommentCount(); + + /** + * 获取文章的篇数 + * + * @return 文章的篇数 + */ + long getArticleCount(); + + /** + * 获取分类数量 + * + * @return 分类数量 + */ + long getCategoriesCount(); + + /** + * 获取标签数量 + * + * @return 标签数量 + */ + long getTagsCount(); + + /** + * 获取用户量 + * + * @return 用户量 + */ + long getUserCount(); + + /** + * 获取总访问量 + * + * @return 总访问量 + */ + long getVisitorCount(); + + /** + * 获取日访问量 + * + * @return 日访问量 + */ + long getDayVisitCount(); +} diff --git a/src/main/java/cn/celess/blog/service/MailService.java b/blog-common/src/main/java/cn/celess/common/service/MailService.java similarity index 90% rename from src/main/java/cn/celess/blog/service/MailService.java rename to blog-common/src/main/java/cn/celess/common/service/MailService.java index 61d8e35..2bb70bb 100644 --- a/src/main/java/cn/celess/blog/service/MailService.java +++ b/blog-common/src/main/java/cn/celess/common/service/MailService.java @@ -1,27 +1,27 @@ -package cn.celess.blog.service; - -import org.springframework.mail.SimpleMailMessage; -import org.springframework.stereotype.Service; - -/** - * @author : xiaohai - * @date : 2019/04/22 14:25 - */ -@Service -public interface MailService { - /** - * 异步发生邮件 - * - * @param message SimpleMailMessage对象 - * @return // - */ - Boolean AsyncSend(SimpleMailMessage message); - - /** - * 同步发送邮件 - * - * @param message SimpleMailMessage对象 - * @return 发送状态 - */ - Boolean send(SimpleMailMessage message); -} +package cn.celess.common.service; + +import org.springframework.mail.SimpleMailMessage; +import org.springframework.stereotype.Service; + +/** + * @author : xiaohai + * @date : 2019/04/22 14:25 + */ +@Service +public interface MailService { + /** + * 异步发生邮件 + * + * @param message SimpleMailMessage对象 + * @return // + */ + Boolean AsyncSend(SimpleMailMessage message); + + /** + * 同步发送邮件 + * + * @param message SimpleMailMessage对象 + * @return 发送状态 + */ + Boolean send(SimpleMailMessage message); +} diff --git a/src/main/java/cn/celess/blog/service/PartnerSiteService.java b/blog-common/src/main/java/cn/celess/common/service/PartnerSiteService.java similarity index 81% rename from src/main/java/cn/celess/blog/service/PartnerSiteService.java rename to blog-common/src/main/java/cn/celess/common/service/PartnerSiteService.java index a0b4f69..6557b59 100644 --- a/src/main/java/cn/celess/blog/service/PartnerSiteService.java +++ b/blog-common/src/main/java/cn/celess/common/service/PartnerSiteService.java @@ -1,72 +1,72 @@ -package cn.celess.blog.service; - -import cn.celess.blog.entity.PartnerSite; -import cn.celess.blog.entity.model.PageData; -import cn.celess.blog.entity.request.LinkApplyReq; -import cn.celess.blog.entity.request.LinkReq; -import org.springframework.stereotype.Service; - -import java.util.List; - -/** - * @author : xiaohai - * @date : 2019/05/12 11:42 - */ -@Service -public interface PartnerSiteService { - /** - * 新增数据 - * - * @param reqBody 数据请求体 - * @return 新增数据 - */ - PartnerSite create(LinkReq reqBody); - - /** - * 删除数据 - * - * @param id 数据id - * @return 删除状态 - */ - Boolean del(long id); - - /** - * 更新数据 - * - * @param reqBody 数据请求体 - * @return 更新后的数据 - */ - PartnerSite update(LinkReq reqBody); - - /** - * 分页获取数据 - * - * @param count 单页数据量 - * @param page 数据页 - * @return 分页数据 - */ - PageData partnerSitePages(int page, int count, Boolean deleted); - - /** - * 获取全部数据 - * - * @return 全部友链数据 - */ - List findAll(); - - /** - * 申请友链 - * - * @param linkApplyReq linkApplyReq - * @return linkApplyReq - */ - PartnerSite apply(LinkApplyReq linkApplyReq); - - /** - * 重写申请友链 - * - * @param key key - * @return msg - */ - String reapply(String key); -} +package cn.celess.common.service; + +import cn.celess.common.entity.PartnerSite; +import cn.celess.common.entity.dto.LinkApplyReq; +import cn.celess.common.entity.dto.LinkReq; +import cn.celess.common.entity.vo.PageData; +import org.springframework.stereotype.Service; + +import java.util.List; + +/** + * @author : xiaohai + * @date : 2019/05/12 11:42 + */ +@Service +public interface PartnerSiteService { + /** + * 新增数据 + * + * @param reqBody 数据请求体 + * @return 新增数据 + */ + PartnerSite create(LinkReq reqBody); + + /** + * 删除数据 + * + * @param id 数据id + * @return 删除状态 + */ + Boolean del(long id); + + /** + * 更新数据 + * + * @param reqBody 数据请求体 + * @return 更新后的数据 + */ + PartnerSite update(LinkReq reqBody); + + /** + * 分页获取数据 + * + * @param count 单页数据量 + * @param page 数据页 + * @return 分页数据 + */ + PageData partnerSitePages(int page, int count, Boolean deleted); + + /** + * 获取全部数据 + * + * @return 全部友链数据 + */ + List findAll(); + + /** + * 申请友链 + * + * @param linkApplyReq linkApplyReq + * @return linkApplyReq + */ + PartnerSite apply(LinkApplyReq linkApplyReq); + + /** + * 重写申请友链 + * + * @param key key + * @return msg + */ + String reapply(String key); +} diff --git a/src/main/java/cn/celess/blog/service/QiniuService.java b/blog-common/src/main/java/cn/celess/common/service/QiniuService.java similarity index 82% rename from src/main/java/cn/celess/blog/service/QiniuService.java rename to blog-common/src/main/java/cn/celess/common/service/QiniuService.java index 32bdc2a..827ff01 100644 --- a/src/main/java/cn/celess/blog/service/QiniuService.java +++ b/blog-common/src/main/java/cn/celess/common/service/QiniuService.java @@ -1,31 +1,31 @@ -package cn.celess.blog.service; - -import cn.celess.blog.entity.model.QiniuResponse; -import com.qiniu.storage.model.FileInfo; -import org.springframework.stereotype.Service; - -import java.io.InputStream; - -/** - * @author : xiaohai - * @date : 2019/04/25 18:15 - */ -@Service -public interface QiniuService { - /** - * 上传文件 - * - * @param is InputStream流 - * @param fileName 文件名 - * @return 响应数据 - */ - QiniuResponse uploadFile(InputStream is, String fileName); - - /** - * 获取文件列表 - * - * @return 文件列表 - */ - FileInfo[] getFileList(); - -} +package cn.celess.common.service; + +import cn.celess.common.entity.vo.QiniuResponse; +import com.qiniu.storage.model.FileInfo; +import org.springframework.stereotype.Service; + +import java.io.InputStream; + +/** + * @author : xiaohai + * @date : 2019/04/25 18:15 + */ +@Service +public interface QiniuService { + /** + * 上传文件 + * + * @param is InputStream流 + * @param fileName 文件名 + * @return 响应数据 + */ + QiniuResponse uploadFile(InputStream is, String fileName); + + /** + * 获取文件列表 + * + * @return 文件列表 + */ + FileInfo[] getFileList(); + +} diff --git a/src/main/java/cn/celess/blog/service/TagService.java b/blog-common/src/main/java/cn/celess/common/service/TagService.java similarity index 84% rename from src/main/java/cn/celess/blog/service/TagService.java rename to blog-common/src/main/java/cn/celess/common/service/TagService.java index 69090bb..c63c84e 100644 --- a/src/main/java/cn/celess/blog/service/TagService.java +++ b/blog-common/src/main/java/cn/celess/common/service/TagService.java @@ -1,56 +1,56 @@ -package cn.celess.blog.service; - -import cn.celess.blog.entity.model.PageData; -import cn.celess.blog.entity.model.TagModel; -import org.springframework.stereotype.Service; - -import java.util.List; - -/** - * @author : xiaohai - * @date : 2019/03/28 22:23 - */ -@Service -public interface TagService { - /** - * 新增数据 - * - * @param name 标签名 - * @return 新增后的数据 - */ - TagModel create(String name); - - /** - * 删除数据 - * - * @param tagId 标签id - * @return 删除状态 - */ - boolean delete(long tagId); - - /** - * 更新数据 - * - * @param id 标签id - * @param name 改名的name值 - * @return 更新后的数据 - */ - TagModel update(Long id, String name); - - /** - * 分页获取标签数据 - * - * @param count 单页数据量 - * @param page 数据页 - * @return 分页数据 - */ - PageData retrievePage(int page, int count); - - /** - * 获取全部标签数据 - * - * @return 标签数据列表 - */ - List findAll(); - -} +package cn.celess.common.service; + +import cn.celess.common.entity.vo.PageData; +import cn.celess.common.entity.vo.TagModel; +import org.springframework.stereotype.Service; + +import java.util.List; + +/** + * @author : xiaohai + * @date : 2019/03/28 22:23 + */ +@Service +public interface TagService { + /** + * 新增数据 + * + * @param name 标签名 + * @return 新增后的数据 + */ + TagModel create(String name); + + /** + * 删除数据 + * + * @param tagId 标签id + * @return 删除状态 + */ + boolean delete(long tagId); + + /** + * 更新数据 + * + * @param id 标签id + * @param name 改名的name值 + * @return 更新后的数据 + */ + TagModel update(Long id, String name); + + /** + * 分页获取标签数据 + * + * @param count 单页数据量 + * @param page 数据页 + * @return 分页数据 + */ + PageData retrievePage(int page, int count); + + /** + * 获取全部标签数据 + * + * @return 标签数据列表 + */ + List findAll(); + +} diff --git a/src/main/java/cn/celess/blog/service/UserService.java b/blog-common/src/main/java/cn/celess/common/service/UserService.java similarity index 89% rename from src/main/java/cn/celess/blog/service/UserService.java rename to blog-common/src/main/java/cn/celess/common/service/UserService.java index e34d231..e18d929 100644 --- a/src/main/java/cn/celess/blog/service/UserService.java +++ b/blog-common/src/main/java/cn/celess/common/service/UserService.java @@ -1,159 +1,159 @@ -package cn.celess.blog.service; - -import cn.celess.blog.entity.model.PageData; -import cn.celess.blog.entity.model.UserModel; -import cn.celess.blog.entity.request.LoginReq; -import cn.celess.blog.entity.request.UserReq; -import org.springframework.stereotype.Service; - -import java.io.InputStream; - -/** - * @author : xiaohai - * @date : 2019/03/30 18:40 - */ -@Service -public interface UserService { - /** - * 注册 - * - * @param email 邮箱 - * @param password 密码 - * @return 注册状态 - */ - Boolean registration(String email, String password); - - /** - * 登录 - * - * @param loginReq 请求数据 - * @return 用户数据 - */ - UserModel login(LoginReq loginReq); - - /** - * 注销登录 - * - * @return ** - */ - Object logout(); - - /** - * 更新用户数据 - * - * @param desc 用户描述 - * @param displayName 显示昵称 - * @return 用户数据 - */ - UserModel update(String desc, String displayName); - - /** - * 更新头像 - * - * @param is 头像文件的输入流 - * @param mime 文件的mime - * @return 响应数据 - */ - Object updateUserAavatarImg(InputStream is, String mime); - - /** - * 获取session中存储的用户资料 - * - * @return 用户资料 - */ - UserModel getUserInfoBySession(); - - /** - * 获取用户的角色 - * - * @param email 用户的邮箱 - * @return role - */ - String getUserRoleByEmail(String email); - - /** - * 获取邮箱是否注册过 - * - * @param email 用户邮箱 - * @return 注册状态 - */ - boolean isExistOfEmail(String email); - - /** - * 发送重置密码邮件 - * - * @param email 用户邮箱 - * @return 发送状态 - */ - Object sendResetPwdEmail(String email); - - /** - * 发送验证邮箱邮件 - * - * @param email 用户邮箱 - * @return 发送状态 - */ - Object sendVerifyEmail(String email); - - /** - * 验证邮箱 - * - * @param verifyId 验证码 - * @param email 邮箱 - * @return 验证状态 - */ - Object verifyEmail(String verifyId, String email); - - /** - * 重置密码 - * - * @param verifyId 验证码 - * @param email 邮箱 - * @param pwd 新密码 - * @return 修改状态 - */ - Object reSetPwd(String verifyId, String email, String pwd); - - /** - * 删除用户 - * - * @param id 用户id的数组 - * @return 对应id 的删除状态 - */ - Object deleteUser(Integer[] id); - - /** - * 获取用户列表 - * - * @param count 单页数据量 - * @param page 数据页 - * @return 分页数据 - */ - PageData getUserList(Integer page, Integer count, Integer status); - - /** - * 更改用户信息 - * - * @param user 用户数据 - * @return 用户信息 - */ - UserModel adminUpdate(UserReq user); - - /** - * 获取电子邮件的存在状态 - * - * @param email email - * @return true:存在 false:不存在 - */ - boolean getStatusOfEmail(String email); - - /** - * 设置密码 - * - * @param pwd pwd - * @param newPwd newPwd - * @param confirmPwd confirmPwd - * @return UserModel - */ - UserModel setPwd(String pwd, String newPwd, String confirmPwd); -} +package cn.celess.common.service; + +import cn.celess.common.entity.dto.LoginReq; +import cn.celess.common.entity.dto.UserReq; +import cn.celess.common.entity.vo.PageData; +import cn.celess.common.entity.vo.UserModel; +import org.springframework.stereotype.Service; + +import java.io.InputStream; + +/** + * @author : xiaohai + * @date : 2019/03/30 18:40 + */ +@Service +public interface UserService { + /** + * 注册 + * + * @param email 邮箱 + * @param password 密码 + * @return 注册状态 + */ + Boolean registration(String email, String password); + + /** + * 登录 + * + * @param loginReq 请求数据 + * @return 用户数据 + */ + UserModel login(LoginReq loginReq); + + /** + * 注销登录 + * + * @return ** + */ + Object logout(); + + /** + * 更新用户数据 + * + * @param desc 用户描述 + * @param displayName 显示昵称 + * @return 用户数据 + */ + UserModel update(String desc, String displayName); + + /** + * 更新头像 + * + * @param is 头像文件的输入流 + * @param mime 文件的mime + * @return 响应数据 + */ + Object updateUserAavatarImg(InputStream is, String mime); + + /** + * 获取session中存储的用户资料 + * + * @return 用户资料 + */ + UserModel getUserInfoBySession(); + + /** + * 获取用户的角色 + * + * @param email 用户的邮箱 + * @return role + */ + String getUserRoleByEmail(String email); + + /** + * 获取邮箱是否注册过 + * + * @param email 用户邮箱 + * @return 注册状态 + */ + boolean isExistOfEmail(String email); + + /** + * 发送重置密码邮件 + * + * @param email 用户邮箱 + * @return 发送状态 + */ + Object sendResetPwdEmail(String email); + + /** + * 发送验证邮箱邮件 + * + * @param email 用户邮箱 + * @return 发送状态 + */ + Object sendVerifyEmail(String email); + + /** + * 验证邮箱 + * + * @param verifyId 验证码 + * @param email 邮箱 + * @return 验证状态 + */ + Object verifyEmail(String verifyId, String email); + + /** + * 重置密码 + * + * @param verifyId 验证码 + * @param email 邮箱 + * @param pwd 新密码 + * @return 修改状态 + */ + Object reSetPwd(String verifyId, String email, String pwd); + + /** + * 删除用户 + * + * @param id 用户id的数组 + * @return 对应id 的删除状态 + */ + Object deleteUser(Integer[] id); + + /** + * 获取用户列表 + * + * @param count 单页数据量 + * @param page 数据页 + * @return 分页数据 + */ + PageData getUserList(Integer page, Integer count, Integer status); + + /** + * 更改用户信息 + * + * @param user 用户数据 + * @return 用户信息 + */ + UserModel adminUpdate(UserReq user); + + /** + * 获取电子邮件的存在状态 + * + * @param email email + * @return true:存在 false:不存在 + */ + boolean getStatusOfEmail(String email); + + /** + * 设置密码 + * + * @param pwd pwd + * @param newPwd newPwd + * @param confirmPwd confirmPwd + * @return UserModel + */ + UserModel setPwd(String pwd, String newPwd, String confirmPwd); +} diff --git a/src/main/java/cn/celess/blog/service/VisitorService.java b/blog-common/src/main/java/cn/celess/common/service/VisitorService.java similarity index 84% rename from src/main/java/cn/celess/blog/service/VisitorService.java rename to blog-common/src/main/java/cn/celess/common/service/VisitorService.java index 1da235d..395d212 100644 --- a/src/main/java/cn/celess/blog/service/VisitorService.java +++ b/blog-common/src/main/java/cn/celess/common/service/VisitorService.java @@ -1,40 +1,40 @@ -package cn.celess.blog.service; - -import cn.celess.blog.entity.model.PageData; -import cn.celess.blog.entity.model.VisitorModel; -import org.springframework.stereotype.Service; - -import javax.servlet.http.HttpServletRequest; - -/** - * @author : xiaohai - * @date : 2019/04/02 23:03 - */ -@Service -public interface VisitorService { - /** - * 分页获取访客数据 - * - * @param count 单页数据量 - * @param page 数据页 - * @param showLocation 是否显示位置信息 开启改选项数据响应超慢 - * @return 分页数据 - */ - PageData visitorPage(int page, int count, boolean showLocation); - - /** - * 新增访客 - * - * @param request HttpServletRequest - * @return 返回状态 null: 访客信息已记录、爬虫 - */ - VisitorModel addVisitor(HttpServletRequest request); - - /** - * 获取位置信息 - * - * @param ip ip地址 - * @return 位置信息 - */ - String location(String ip); -} +package cn.celess.common.service; + +import cn.celess.common.entity.vo.PageData; +import cn.celess.common.entity.vo.VisitorModel; +import org.springframework.stereotype.Service; + +import javax.servlet.http.HttpServletRequest; + +/** + * @author : xiaohai + * @date : 2019/04/02 23:03 + */ +@Service +public interface VisitorService { + /** + * 分页获取访客数据 + * + * @param count 单页数据量 + * @param page 数据页 + * @param showLocation 是否显示位置信息 开启改选项数据响应超慢 + * @return 分页数据 + */ + PageData visitorPage(int page, int count, boolean showLocation); + + /** + * 新增访客 + * + * @param request HttpServletRequest + * @return 返回状态 null: 访客信息已记录、爬虫 + */ + VisitorModel addVisitor(HttpServletRequest request); + + /** + * 获取位置信息 + * + * @param ip ip地址 + * @return 位置信息 + */ + String location(String ip); +} diff --git a/src/main/java/cn/celess/blog/service/WebUpdateInfoService.java b/blog-common/src/main/java/cn/celess/common/service/WebUpdateInfoService.java similarity index 85% rename from src/main/java/cn/celess/blog/service/WebUpdateInfoService.java rename to blog-common/src/main/java/cn/celess/common/service/WebUpdateInfoService.java index 3973598..c684232 100644 --- a/src/main/java/cn/celess/blog/service/WebUpdateInfoService.java +++ b/blog-common/src/main/java/cn/celess/common/service/WebUpdateInfoService.java @@ -1,63 +1,64 @@ -package cn.celess.blog.service; - -import cn.celess.blog.entity.model.PageData; -import cn.celess.blog.entity.model.WebUpdateModel; -import org.springframework.stereotype.Service; - -import java.util.List; -import java.util.Map; - -/** - * @author : xiaohai - * @date : 2019/05/12 11:42 - */ -@Service -public interface WebUpdateInfoService { - /** - * 新增记录 - * - * @param info 更新内容 - * @return 创建状态 - */ - WebUpdateModel create(String info); - - /** - * 删除数据 - * - * @param id 数据id - * @return 删除状态 - */ - Boolean del(long id); - - /** - * 更新数据 - * - * @param id 数据id - * @param info 新内容 - * @return 数据 - */ - WebUpdateModel update(long id, String info); - - /** - * 分页获取更新记录 - * - * @param count 单页数据量 - * @param page 数据页 - * @return 分页数据 - */ - PageData pages(int count, int page); - - /** - * 获取全部的更新记录 - * - * @return 更新记录 - */ - List findAll(); - - /** - * 获取最后更新时间 - * - * @return - */ - Map getLastestUpdateTime(); -} +package cn.celess.common.service; + + +import cn.celess.common.entity.vo.PageData; +import cn.celess.common.entity.vo.WebUpdateModel; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Map; + +/** + * @author : xiaohai + * @date : 2019/05/12 11:42 + */ +@Service +public interface WebUpdateInfoService { + /** + * 新增记录 + * + * @param info 更新内容 + * @return 创建状态 + */ + WebUpdateModel create(String info); + + /** + * 删除数据 + * + * @param id 数据id + * @return 删除状态 + */ + Boolean del(long id); + + /** + * 更新数据 + * + * @param id 数据id + * @param info 新内容 + * @return 数据 + */ + WebUpdateModel update(long id, String info); + + /** + * 分页获取更新记录 + * + * @param count 单页数据量 + * @param page 数据页 + * @return 分页数据 + */ + PageData pages(int count, int page); + + /** + * 获取全部的更新记录 + * + * @return 更新记录 + */ + List findAll(); + + /** + * 获取最后更新时间 + * + * @return + */ + Map getLastestUpdateTime(); +} diff --git a/src/main/java/cn/celess/blog/util/DateFormatUtil.java b/blog-common/src/main/java/cn/celess/common/util/DateFormatUtil.java similarity index 94% rename from src/main/java/cn/celess/blog/util/DateFormatUtil.java rename to blog-common/src/main/java/cn/celess/common/util/DateFormatUtil.java index 9ca8279..0027e57 100644 --- a/src/main/java/cn/celess/blog/util/DateFormatUtil.java +++ b/blog-common/src/main/java/cn/celess/common/util/DateFormatUtil.java @@ -1,42 +1,42 @@ -package cn.celess.blog.util; - -import javax.xml.datatype.DatatypeConfigurationException; -import javax.xml.datatype.DatatypeFactory; -import javax.xml.datatype.XMLGregorianCalendar; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.GregorianCalendar; - -/** - * @author : xiaohai - * @date : 2019/03/28 17:22 - */ -public class DateFormatUtil { - public static String get(Date date) { - if (date == null) { - return null; - } - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - return sdf.format(date); - } - - public static String getForXmlDate(Date date) { - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZZ"); - GregorianCalendar gc = new GregorianCalendar(); - String dateString = sdf.format(date); - try { - gc.setTime(sdf.parse(dateString)); - XMLGregorianCalendar date2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(gc); - return date2.toString(); - } catch (DatatypeConfigurationException | ParseException e) { - e.printStackTrace(); - return null; - } - } - - - public static String getNow() { - return get(new Date()); - } -} +package cn.celess.common.util; + +import javax.xml.datatype.DatatypeConfigurationException; +import javax.xml.datatype.DatatypeFactory; +import javax.xml.datatype.XMLGregorianCalendar; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.GregorianCalendar; + +/** + * @author : xiaohai + * @date : 2019/03/28 17:22 + */ +public class DateFormatUtil { + public static String get(Date date) { + if (date == null) { + return null; + } + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + return sdf.format(date); + } + + public static String getForXmlDate(Date date) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZZ"); + GregorianCalendar gc = new GregorianCalendar(); + String dateString = sdf.format(date); + try { + gc.setTime(sdf.parse(dateString)); + XMLGregorianCalendar date2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(gc); + return date2.toString(); + } catch (DatatypeConfigurationException | ParseException e) { + e.printStackTrace(); + return null; + } + } + + + public static String getNow() { + return get(new Date()); + } +} diff --git a/src/main/java/cn/celess/blog/util/HttpUtil.java b/blog-common/src/main/java/cn/celess/common/util/HttpUtil.java similarity index 60% rename from src/main/java/cn/celess/blog/util/HttpUtil.java rename to blog-common/src/main/java/cn/celess/common/util/HttpUtil.java index a720f38..08ca2e5 100644 --- a/src/main/java/cn/celess/blog/util/HttpUtil.java +++ b/blog-common/src/main/java/cn/celess/common/util/HttpUtil.java @@ -1,15 +1,13 @@ -package cn.celess.blog.util; +package cn.celess.common.util; + import com.gargoylesoftware.htmlunit.BrowserVersion; import com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController; +import com.gargoylesoftware.htmlunit.Page; import com.gargoylesoftware.htmlunit.WebClient; import com.gargoylesoftware.htmlunit.html.HtmlPage; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; import java.io.IOException; -import java.util.Objects; /** * @Author: 小海 @@ -17,15 +15,20 @@ import java.util.Objects; * @Desc: */ public class HttpUtil { - private static final OkHttpClient CLIENT = new OkHttpClient(); - public static String get(String urlStr) { - Request request = new Request.Builder() - .url(urlStr) - .get() - .build(); - try (Response response = CLIENT.newCall(request).execute()) { - return Objects.requireNonNull(response.body()).string(); + try (final WebClient webClient = new WebClient(BrowserVersion.CHROME)) { + webClient.getOptions().setCssEnabled(false); + webClient.getOptions().setJavaScriptEnabled(false); + webClient.getOptions().setThrowExceptionOnFailingStatusCode(false); + webClient.getOptions().setThrowExceptionOnScriptError(false); + webClient.getOptions().setDownloadImages(false); + webClient.getOptions().setActiveXNative(false); + webClient.setAjaxController(new NicelyResynchronizingAjaxController()); + Page clientPage = webClient.getPage(urlStr); + if (clientPage.isHtmlPage()) { + return clientPage.toString(); + } + return null; } catch (IOException e) { return null; } @@ -33,7 +36,7 @@ public class HttpUtil { public static String getAfterRendering(String url) { - try (final WebClient webClient = new WebClient(BrowserVersion.CHROME)) { + try (final WebClient webClient = new WebClient(BrowserVersion.BEST_SUPPORTED)) { webClient.getOptions().setCssEnabled(false); webClient.getOptions().setJavaScriptEnabled(true); webClient.getOptions().setThrowExceptionOnFailingStatusCode(false); diff --git a/src/main/java/cn/celess/blog/util/MD5Util.java b/blog-common/src/main/java/cn/celess/common/util/MD5Util.java similarity index 86% rename from src/main/java/cn/celess/blog/util/MD5Util.java rename to blog-common/src/main/java/cn/celess/common/util/MD5Util.java index 2d7f82a..a712883 100644 --- a/src/main/java/cn/celess/blog/util/MD5Util.java +++ b/blog-common/src/main/java/cn/celess/common/util/MD5Util.java @@ -1,14 +1,14 @@ -package cn.celess.blog.util; - -import org.springframework.util.DigestUtils; - -/** - * @author : xiaohai - * @date : 2019/03/30 18:56 - */ -public class MD5Util { - public static String getMD5(String str) { - String md5 = DigestUtils.md5DigestAsHex(str.getBytes()); - return md5; - } -} +package cn.celess.common.util; + +import org.springframework.util.DigestUtils; + +/** + * @author : xiaohai + * @date : 2019/03/30 18:56 + */ +public class MD5Util { + public static String getMD5(String str) { + String md5 = DigestUtils.md5DigestAsHex(str.getBytes()); + return md5; + } +} diff --git a/src/main/java/cn/celess/blog/util/ModalTrans.java b/blog-common/src/main/java/cn/celess/common/util/ModalTrans.java similarity index 95% rename from src/main/java/cn/celess/blog/util/ModalTrans.java rename to blog-common/src/main/java/cn/celess/common/util/ModalTrans.java index 348b8f7..339f671 100644 --- a/src/main/java/cn/celess/blog/util/ModalTrans.java +++ b/blog-common/src/main/java/cn/celess/common/util/ModalTrans.java @@ -1,8 +1,9 @@ -package cn.celess.blog.util; +package cn.celess.common.util; -import cn.celess.blog.enmu.UserAccountStatusEnum; -import cn.celess.blog.entity.*; -import cn.celess.blog.entity.model.*; + +import cn.celess.common.enmu.UserAccountStatusEnum; +import cn.celess.common.entity.*; +import cn.celess.common.entity.vo.*; import org.springframework.beans.BeanUtils; /** diff --git a/src/main/java/cn/celess/blog/util/ProtoStuffSerializerUtil.java b/blog-common/src/main/java/cn/celess/common/util/ProtoStuffSerializerUtil.java similarity index 96% rename from src/main/java/cn/celess/blog/util/ProtoStuffSerializerUtil.java rename to blog-common/src/main/java/cn/celess/common/util/ProtoStuffSerializerUtil.java index ec3d805..93291cd 100644 --- a/src/main/java/cn/celess/blog/util/ProtoStuffSerializerUtil.java +++ b/blog-common/src/main/java/cn/celess/common/util/ProtoStuffSerializerUtil.java @@ -1,126 +1,126 @@ -package cn.celess.blog.util; - - -import com.dyuproject.protostuff.LinkedBuffer; -import com.dyuproject.protostuff.ProtostuffIOUtil; -import com.dyuproject.protostuff.Schema; -import com.dyuproject.protostuff.runtime.RuntimeSchema; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.List; - -/** - * ProtoStuffSerializerUtil - * - * @author Sirius - * @date 2019-1-8 - */ -public class ProtoStuffSerializerUtil { - /** - * 序列化对象 - * - * @param obj - * @return - */ - public static byte[] serialize(T obj) { - if (obj == null) { - throw new RuntimeException("序列化对象(" + obj + ")!"); - } - @SuppressWarnings("unchecked") - Schema schema = (Schema) RuntimeSchema.getSchema(obj.getClass()); - LinkedBuffer buffer = LinkedBuffer.allocate(1024 * 1024); - byte[] protostuff = null; - try { - protostuff = ProtostuffIOUtil.toByteArray(obj, schema, buffer); - } catch (Exception e) { - throw new RuntimeException("序列化(" + obj.getClass() + ")对象(" + obj + ")发生异常!", e); - } finally { - buffer.clear(); - } - return protostuff; - } - - /** - * 反序列化对象 - * - * @param paramArrayOfByte - * @param targetClass - * @return - */ - public static T deserialize(byte[] paramArrayOfByte, Class targetClass) { - if (paramArrayOfByte == null || paramArrayOfByte.length == 0) { - throw new RuntimeException("反序列化对象发生异常,byte序列为空!"); - } - T instance = null; - try { - instance = targetClass.newInstance(); - } catch (InstantiationException e1) { - throw new RuntimeException("反序列化过程中依据类型创建对象失败!", e1); - } catch (IllegalAccessException e2) { - throw new RuntimeException("反序列化过程中依据类型创建对象失败!", e2); - } - Schema schema = RuntimeSchema.getSchema(targetClass); - ProtostuffIOUtil.mergeFrom(paramArrayOfByte, instance, schema); - return instance; - } - - /** - * 序列化列表 - * - * @param objList - * @return - */ - public static byte[] serializeList(List objList) { - if (objList == null || objList.isEmpty()) { - throw new RuntimeException("序列化对象列表(" + objList + ")参数异常!"); - } - @SuppressWarnings("unchecked") - Schema schema = (Schema) RuntimeSchema.getSchema(objList.get(0).getClass()); - LinkedBuffer buffer = LinkedBuffer.allocate(1024 * 1024); - byte[] protostuff = null; - ByteArrayOutputStream bos = null; - try { - bos = new ByteArrayOutputStream(); - ProtostuffIOUtil.writeListTo(bos, objList, schema, buffer); - protostuff = bos.toByteArray(); - } catch (Exception e) { - throw new RuntimeException("序列化对象列表(" + objList + ")发生异常!", e); - } finally { - buffer.clear(); - try { - if (bos != null) { - bos.close(); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - - return protostuff; - } - - /** - * 反序列化列表 - * - * @param paramArrayOfByte - * @param targetClass - * @return - */ - public static List deserializeList(byte[] paramArrayOfByte, Class targetClass) { - if (paramArrayOfByte == null || paramArrayOfByte.length == 0) { - throw new RuntimeException("反序列化对象发生异常,byte序列为空!"); - } - - Schema schema = RuntimeSchema.getSchema(targetClass); - List result = null; - try { - result = ProtostuffIOUtil.parseListFrom(new ByteArrayInputStream(paramArrayOfByte), schema); - } catch (IOException e) { - throw new RuntimeException("反序列化对象列表发生异常!", e); - } - return result; - } - -} +package cn.celess.common.util; + + +import com.dyuproject.protostuff.LinkedBuffer; +import com.dyuproject.protostuff.ProtostuffIOUtil; +import com.dyuproject.protostuff.Schema; +import com.dyuproject.protostuff.runtime.RuntimeSchema; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.List; + +/** + * ProtoStuffSerializerUtil + * + * @author Sirius + * @date 2019-1-8 + */ +public class ProtoStuffSerializerUtil { + /** + * 序列化对象 + * + * @param obj + * @return + */ + public static byte[] serialize(T obj) { + if (obj == null) { + throw new RuntimeException("序列化对象(" + obj + ")!"); + } + @SuppressWarnings("unchecked") + Schema schema = (Schema) RuntimeSchema.getSchema(obj.getClass()); + LinkedBuffer buffer = LinkedBuffer.allocate(1024 * 1024); + byte[] protostuff = null; + try { + protostuff = ProtostuffIOUtil.toByteArray(obj, schema, buffer); + } catch (Exception e) { + throw new RuntimeException("序列化(" + obj.getClass() + ")对象(" + obj + ")发生异常!", e); + } finally { + buffer.clear(); + } + return protostuff; + } + + /** + * 反序列化对象 + * + * @param paramArrayOfByte + * @param targetClass + * @return + */ + public static T deserialize(byte[] paramArrayOfByte, Class targetClass) { + if (paramArrayOfByte == null || paramArrayOfByte.length == 0) { + throw new RuntimeException("反序列化对象发生异常,byte序列为空!"); + } + T instance = null; + try { + instance = targetClass.newInstance(); + } catch (InstantiationException e1) { + throw new RuntimeException("反序列化过程中依据类型创建对象失败!", e1); + } catch (IllegalAccessException e2) { + throw new RuntimeException("反序列化过程中依据类型创建对象失败!", e2); + } + Schema schema = RuntimeSchema.getSchema(targetClass); + ProtostuffIOUtil.mergeFrom(paramArrayOfByte, instance, schema); + return instance; + } + + /** + * 序列化列表 + * + * @param objList + * @return + */ + public static byte[] serializeList(List objList) { + if (objList == null || objList.isEmpty()) { + throw new RuntimeException("序列化对象列表(" + objList + ")参数异常!"); + } + @SuppressWarnings("unchecked") + Schema schema = (Schema) RuntimeSchema.getSchema(objList.get(0).getClass()); + LinkedBuffer buffer = LinkedBuffer.allocate(1024 * 1024); + byte[] protostuff = null; + ByteArrayOutputStream bos = null; + try { + bos = new ByteArrayOutputStream(); + ProtostuffIOUtil.writeListTo(bos, objList, schema, buffer); + protostuff = bos.toByteArray(); + } catch (Exception e) { + throw new RuntimeException("序列化对象列表(" + objList + ")发生异常!", e); + } finally { + buffer.clear(); + try { + if (bos != null) { + bos.close(); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + + return protostuff; + } + + /** + * 反序列化列表 + * + * @param paramArrayOfByte + * @param targetClass + * @return + */ + public static List deserializeList(byte[] paramArrayOfByte, Class targetClass) { + if (paramArrayOfByte == null || paramArrayOfByte.length == 0) { + throw new RuntimeException("反序列化对象发生异常,byte序列为空!"); + } + + Schema schema = RuntimeSchema.getSchema(targetClass); + List result = null; + try { + result = ProtostuffIOUtil.parseListFrom(new ByteArrayInputStream(paramArrayOfByte), schema); + } catch (IOException e) { + throw new RuntimeException("反序列化对象列表发生异常!", e); + } + return result; + } + +} diff --git a/src/main/java/cn/celess/blog/util/RedisUtil.java b/blog-common/src/main/java/cn/celess/common/util/RedisUtil.java similarity index 95% rename from src/main/java/cn/celess/blog/util/RedisUtil.java rename to blog-common/src/main/java/cn/celess/common/util/RedisUtil.java index d50a55c..eeac53b 100644 --- a/src/main/java/cn/celess/blog/util/RedisUtil.java +++ b/blog-common/src/main/java/cn/celess/common/util/RedisUtil.java @@ -1,1381 +1,1378 @@ -package cn.celess.blog.util; - - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.dao.DataAccessException; -import org.springframework.data.redis.connection.DataType; -import org.springframework.data.redis.connection.RedisConnection; -import org.springframework.data.redis.core.Cursor; -import org.springframework.data.redis.core.RedisCallback; -import org.springframework.data.redis.core.ScanOptions; -import org.springframework.data.redis.core.StringRedisTemplate; -import org.springframework.data.redis.core.ZSetOperations.TypedTuple; -import org.springframework.stereotype.Component; - -import java.util.*; -import java.util.Map.Entry; -import java.util.concurrent.TimeUnit; - -/** - * Redis工具类 - * - * @author WangFan - * @version 1.1 (GitHub文档: https://github.com/whvcse/RedisUtil ) - * @date 2018-02-24 下午03:09:50 - */ - -@Component -public class RedisUtil { - @Autowired - private StringRedisTemplate redisTemplate; - - public StringRedisTemplate getRedisTemplate() { - return this.redisTemplate; - } - - public void setRedisTemplate(StringRedisTemplate redisTemplate) { - this.redisTemplate = redisTemplate; - } - - /** -------------------key相关操作--------------------- */ - - /** - * 删除key - * - * @param key - */ - public void delete(String key) { - redisTemplate.delete(key); - } - - /** - * 批量删除key - * - * @param keys - */ - public void delete(Collection keys) { - redisTemplate.delete(keys); - } - - /** - * 序列化key - * - * @param key - * @return - */ - public byte[] dump(String key) { - return redisTemplate.dump(key); - } - - /** - * 是否存在key - * - * @param key - * @return - */ - public Boolean hasKey(String key) { - return redisTemplate.hasKey(key); - } - - /** - * 设置过期时间 - * - * @param key - * @param timeout - * @param unit - * @return - */ - public Boolean expire(String key, long timeout, TimeUnit unit) { - return redisTemplate.expire(key, timeout, unit); - } - - /** - * 设置过期时间 - * - * @param key - * @param date - * @return - */ - public Boolean expireAt(String key, Date date) { - return redisTemplate.expireAt(key, date); - } - - /** - * 查找匹配的key - * - * @param pattern - * @return - */ - public Set keys(String pattern) { - return redisTemplate.keys(pattern); - } - - /** - * 将当前数据库的 key 移动到给定的数据库 db 当中 - * - * @param key - * @param dbIndex - * @return - */ - public Boolean move(String key, int dbIndex) { - return redisTemplate.move(key, dbIndex); - } - - /** - * 移除 key 的过期时间,key 将持久保持 - * - * @param key - * @return - */ - public Boolean persist(String key) { - return redisTemplate.persist(key); - } - - /** - * 返回 key 的剩余的过期时间 - * - * @param key - * @param unit - * @return - */ - public Long getExpire(String key, TimeUnit unit) { - return redisTemplate.getExpire(key, unit); - } - - /** - * 返回 key 的剩余的过期时间 - * - * @param key - * @return - */ - public Long getExpire(String key) { - return redisTemplate.getExpire(key); - } - - /** - * 从当前数据库中随机返回一个 key - * - * @return - */ - public String randomKey() { - return redisTemplate.randomKey(); - } - - /** - * 修改 key 的名称 - * - * @param oldKey - * @param newKey - */ - public void rename(String oldKey, String newKey) { - redisTemplate.rename(oldKey, newKey); - } - - /** - * 仅当 newkey 不存在时,将 oldKey 改名为 newkey - * - * @param oldKey - * @param newKey - * @return - */ - public Boolean renameIfAbsent(String oldKey, String newKey) { - return redisTemplate.renameIfAbsent(oldKey, newKey); - } - - /** - * 返回 key 所储存的值的类型 - * - * @param key - * @return - */ - public DataType type(String key) { - return redisTemplate.type(key); - } - - /** -------------------string相关操作--------------------- */ - - /** - * 设置指定 key 的值 - * - * @param key - * @param value - */ - public void set(String key, String value) { - redisTemplate.opsForValue().set(key, value); - } - - /** - * 获取指定 key 的值 - * - * @param key - * @return - */ - public String get(String key) { - return redisTemplate.opsForValue().get(key); - } - - /** - * 返回 key 中字符串值的子字符 - * - * @param key - * @param start - * @param end - * @return - */ - public String getRange(String key, long start, long end) { - return redisTemplate.opsForValue().get(key, start, end); - } - - /** - * 将给定 key 的值设为 value ,并返回 key 的旧值(old value) - * - * @param key - * @param value - * @return - */ - public String getAndSet(String key, String value) { - return redisTemplate.opsForValue().getAndSet(key, value); - } - - /** - * 对 key 所储存的字符串值,获取指定偏移量上的位(bit) - * - * @param key - * @param offset - * @return - */ - public Boolean getBit(String key, long offset) { - return redisTemplate.opsForValue().getBit(key, offset); - } - - /** - * 批量获取 - * - * @param keys - * @return - */ - public List multiGet(Collection keys) { - return redisTemplate.opsForValue().multiGet(keys); - } - - /** - * 设置ASCII码, 字符串'a'的ASCII码是97, 转为二进制是'01100001', 此方法是将二进制第offset位值变为value - * - * @param key - * @param offset 位置 - * @param value 值,true为1, false为0 - * @return - */ - public boolean setBit(String key, long offset, boolean value) { - return redisTemplate.opsForValue().setBit(key, offset, value); - } - - /** - * 将值 value 关联到 key ,并将 key 的过期时间设为 timeout - * - * @param key - * @param value - * @param timeout 过期时间 - * @param unit 时间单位, 天:TimeUnit.DAYS 小时:TimeUnit.HOURS 分钟:TimeUnit.MINUTES - * 秒:TimeUnit.SECONDS 毫秒:TimeUnit.MILLISECONDS - */ - public void setEx(String key, String value, long timeout, TimeUnit unit) { - redisTemplate.opsForValue().set(key, value, timeout, unit); - } - - /** - * 只有在 key 不存在时设置 key 的值 - * - * @param key - * @param value - * @return 之前已经存在返回false, 不存在返回true - */ - public boolean setIfAbsent(String key, String value) { - return redisTemplate.opsForValue().setIfAbsent(key, value); - } - - /** - * 用 value 参数覆写给定 key 所储存的字符串值,从偏移量 offset 开始 - * - * @param key - * @param value - * @param offset 从指定位置开始覆写 - */ - public void setRange(String key, String value, long offset) { - redisTemplate.opsForValue().set(key, value, offset); - } - - /** - * 获取字符串的长度 - * - * @param key - * @return - */ - public Long size(String key) { - return redisTemplate.opsForValue().size(key); - } - - /** - * 批量添加 - * - * @param maps - */ - public void multiSet(Map maps) { - redisTemplate.opsForValue().multiSet(maps); - } - - /** - * 同时设置一个或多个 key-value 对,当且仅当所有给定 key 都不存在 - * - * @param maps - * @return 之前已经存在返回false, 不存在返回true - */ - public boolean multiSetIfAbsent(Map maps) { - return redisTemplate.opsForValue().multiSetIfAbsent(maps); - } - - /** - * 增加(自增长), 负数则为自减 - * - * @param key - * @param increment - * @return - */ - public Long incrBy(String key, long increment) { - return redisTemplate.opsForValue().increment(key, increment); - } - - /** - * @param key - * @param increment - * @return - */ - public Double incrByFloat(String key, double increment) { - return redisTemplate.opsForValue().increment(key, increment); - } - - /** - * 追加到末尾 - * - * @param key - * @param value - * @return - */ - public Integer append(String key, String value) { - return redisTemplate.opsForValue().append(key, value); - } - - /** -------------------hash相关操作------------------------- */ - - /** - * 获取存储在哈希表中指定字段的值 - * - * @param key - * @param field - * @return - */ - public Object hGet(String key, String field) { - return redisTemplate.opsForHash().get(key, field); - } - - /** - * 获取所有给定字段的值 - * - * @param key - * @return - */ - public Map hGetAll(String key) { - return redisTemplate.opsForHash().entries(key); - } - - /** - * 获取所有给定字段的值 - * - * @param key - * @param fields - * @return - */ - public List hMultiGet(String key, Collection fields) { - return redisTemplate.opsForHash().multiGet(key, fields); - } - - public void hPut(String key, String hashKey, String value) { - redisTemplate.opsForHash().put(key, hashKey, value); - } - - public void hPutAll(String key, Map maps) { - redisTemplate.opsForHash().putAll(key, maps); - } - - /** - * 仅当hashKey不存在时才设置 - * - * @param key - * @param hashKey - * @param value - * @return - */ - public Boolean hPutIfAbsent(String key, String hashKey, String value) { - return redisTemplate.opsForHash().putIfAbsent(key, hashKey, value); - } - - /** - * 删除一个或多个哈希表字段 - * - * @param key - * @param fields - * @return - */ - public Long hDelete(String key, Object... fields) { - return redisTemplate.opsForHash().delete(key, fields); - } - - /** - * 查看哈希表 key 中,指定的字段是否存在 - * - * @param key - * @param field - * @return - */ - public boolean hExists(String key, String field) { - return redisTemplate.opsForHash().hasKey(key, field); - } - - /** - * 为哈希表 key 中的指定字段的整数值加上增量 increment - * - * @param key - * @param field - * @param increment - * @return - */ - public Long hIncrBy(String key, Object field, long increment) { - return redisTemplate.opsForHash().increment(key, field, increment); - } - - /** - * 为哈希表 key 中的指定字段的整数值加上增量 increment - * - * @param key - * @param field - * @param delta - * @return - */ - public Double hIncrByFloat(String key, Object field, double delta) { - return redisTemplate.opsForHash().increment(key, field, delta); - } - - /** - * 获取所有哈希表中的字段 - * - * @param key - * @return - */ - public Set hKeys(String key) { - return redisTemplate.opsForHash().keys(key); - } - - /** - * 获取哈希表中字段的数量 - * - * @param key - * @return - */ - public Long hSize(String key) { - return redisTemplate.opsForHash().size(key); - } - - /** - * 获取哈希表中所有值 - * - * @param key - * @return - */ - public List hValues(String key) { - return redisTemplate.opsForHash().values(key); - } - - /** - * 迭代哈希表中的键值对 - * - * @param key - * @param options - * @return - */ - public Cursor> hScan(String key, ScanOptions options) { - return redisTemplate.opsForHash().scan(key, options); - } - - /** ------------------------list相关操作---------------------------- */ - - /** - * 通过索引获取列表中的元素 - * - * @param key - * @param index - * @return - */ - public String lIndex(String key, long index) { - return redisTemplate.opsForList().index(key, index); - } - - /** - * 获取列表指定范围内的元素 - * - * @param key - * @param start 开始位置, 0是开始位置 - * @param end 结束位置, -1返回所有 - * @return - */ - public List lRange(String key, long start, long end) { - return redisTemplate.opsForList().range(key, start, end); - } - - /** - * 存储在list头部 - * - * @param key - * @param value - * @return - */ - public Long lLeftPush(String key, String value) { - return redisTemplate.opsForList().leftPush(key, value); - } - - /** - * @param key - * @param value - * @return - */ - public Long lLeftPushAll(String key, String... value) { - return redisTemplate.opsForList().leftPushAll(key, value); - } - - /** - * @param key - * @param value - * @return - */ - public Long lLeftPushAll(String key, Collection value) { - return redisTemplate.opsForList().leftPushAll(key, value); - } - - /** - * 当list存在的时候才加入 - * - * @param key - * @param value - * @return - */ - public Long lLeftPushIfPresent(String key, String value) { - return redisTemplate.opsForList().leftPushIfPresent(key, value); - } - - /** - * 如果pivot存在,再pivot前面添加 - * - * @param key - * @param pivot - * @param value - * @return - */ - public Long lLeftPush(String key, String pivot, String value) { - return redisTemplate.opsForList().leftPush(key, pivot, value); - } - - /** - * @param key - * @param value - * @return - */ - public Long lRightPush(String key, String value) { - return redisTemplate.opsForList().rightPush(key, value); - } - - /** - * @param key - * @param value - * @return - */ - public Long lRightPushAll(String key, String... value) { - return redisTemplate.opsForList().rightPushAll(key, value); - } - - /** - * @param key - * @param value - * @return - */ - public Long lRightPushAll(String key, Collection value) { - return redisTemplate.opsForList().rightPushAll(key, value); - } - - /** - * 为已存在的列表添加值 - * - * @param key - * @param value - * @return - */ - public Long lRightPushIfPresent(String key, String value) { - return redisTemplate.opsForList().rightPushIfPresent(key, value); - } - - /** - * 在pivot元素的右边添加值 - * - * @param key - * @param pivot - * @param value - * @return - */ - public Long lRightPush(String key, String pivot, String value) { - return redisTemplate.opsForList().rightPush(key, pivot, value); - } - - /** - * 通过索引设置列表元素的值 - * - * @param key - * @param index 位置 - * @param value - */ - public void lSet(String key, long index, String value) { - redisTemplate.opsForList().set(key, index, value); - } - - /** - * 移出并获取列表的第一个元素 - * - * @param key - * @return 删除的元素 - */ - public String lLeftPop(String key) { - return redisTemplate.opsForList().leftPop(key); - } - - /** - * 移出并获取列表的第一个元素, 如果列表没有元素会阻塞列表直到等待超时或发现可弹出元素为止 - * - * @param key - * @param timeout 等待时间 - * @param unit 时间单位 - * @return - */ - public String lBLeftPop(String key, long timeout, TimeUnit unit) { - return redisTemplate.opsForList().leftPop(key, timeout, unit); - } - - /** - * 移除并获取列表最后一个元素 - * - * @param key - * @return 删除的元素 - */ - public String lRightPop(String key) { - return redisTemplate.opsForList().rightPop(key); - } - - /** - * 移出并获取列表的最后一个元素, 如果列表没有元素会阻塞列表直到等待超时或发现可弹出元素为止 - * - * @param key - * @param timeout 等待时间 - * @param unit 时间单位 - * @return - */ - public String lBRightPop(String key, long timeout, TimeUnit unit) { - return redisTemplate.opsForList().rightPop(key, timeout, unit); - } - - /** - * 移除列表的最后一个元素,并将该元素添加到另一个列表并返回 - * - * @param sourceKey - * @param destinationKey - * @return - */ - public String lRightPopAndLeftPush(String sourceKey, String destinationKey) { - return redisTemplate.opsForList().rightPopAndLeftPush(sourceKey, - destinationKey); - } - - /** - * 从列表中弹出一个值,将弹出的元素插入到另外一个列表中并返回它; 如果列表没有元素会阻塞列表直到等待超时或发现可弹出元素为止 - * - * @param sourceKey - * @param destinationKey - * @param timeout - * @param unit - * @return - */ - public String lBRightPopAndLeftPush(String sourceKey, String destinationKey, - long timeout, TimeUnit unit) { - return redisTemplate.opsForList().rightPopAndLeftPush(sourceKey, - destinationKey, timeout, unit); - } - - /** - * 删除集合中值等于value得元素 - * - * @param key - * @param index index=0, 删除所有值等于value的元素; index>0, 从头部开始删除第一个值等于value的元素; - * index<0, 从尾部开始删除第一个值等于value的元素; - * @param value - * @return - */ - public Long lRemove(String key, long index, String value) { - return redisTemplate.opsForList().remove(key, index, value); - } - - /** - * 裁剪list - * - * @param key - * @param start - * @param end - */ - public void lTrim(String key, long start, long end) { - redisTemplate.opsForList().trim(key, start, end); - } - - /** - * 获取列表长度 - * - * @param key - * @return - */ - public Long lLen(String key) { - return redisTemplate.opsForList().size(key); - } - - /** --------------------set相关操作-------------------------- */ - - /** - * set添加元素 - * - * @param key - * @param values - * @return - */ - public Long sAdd(String key, String... values) { - return redisTemplate.opsForSet().add(key, values); - } - - /** - * set移除元素 - * - * @param key - * @param values - * @return - */ - public Long sRemove(String key, Object... values) { - return redisTemplate.opsForSet().remove(key, values); - } - - /** - * 移除并返回集合的一个随机元素 - * - * @param key - * @return - */ - public String sPop(String key) { - return redisTemplate.opsForSet().pop(key); - } - - /** - * 将元素value从一个集合移到另一个集合 - * - * @param key - * @param value - * @param destKey - * @return - */ - public Boolean sMove(String key, String value, String destKey) { - return redisTemplate.opsForSet().move(key, value, destKey); - } - - /** - * 获取集合的大小 - * - * @param key - * @return - */ - public Long sSize(String key) { - return redisTemplate.opsForSet().size(key); - } - - /** - * 判断集合是否包含value - * - * @param key - * @param value - * @return - */ - public Boolean sIsMember(String key, Object value) { - return redisTemplate.opsForSet().isMember(key, value); - } - - /** - * 获取两个集合的交集 - * - * @param key - * @param otherKey - * @return - */ - public Set sIntersect(String key, String otherKey) { - return redisTemplate.opsForSet().intersect(key, otherKey); - } - - /** - * 获取key集合与多个集合的交集 - * - * @param key - * @param otherKeys - * @return - */ - public Set sIntersect(String key, Collection otherKeys) { - return redisTemplate.opsForSet().intersect(key, otherKeys); - } - - /** - * key集合与otherKey集合的交集存储到destKey集合中 - * - * @param key - * @param otherKey - * @param destKey - * @return - */ - public Long sIntersectAndStore(String key, String otherKey, String destKey) { - return redisTemplate.opsForSet().intersectAndStore(key, otherKey, - destKey); - } - - /** - * key集合与多个集合的交集存储到destKey集合中 - * - * @param key - * @param otherKeys - * @param destKey - * @return - */ - public Long sIntersectAndStore(String key, Collection otherKeys, - String destKey) { - return redisTemplate.opsForSet().intersectAndStore(key, otherKeys, - destKey); - } - - /** - * 获取两个集合的并集 - * - * @param key - * @param otherKeys - * @return - */ - public Set sUnion(String key, String otherKeys) { - return redisTemplate.opsForSet().union(key, otherKeys); - } - - /** - * 获取key集合与多个集合的并集 - * - * @param key - * @param otherKeys - * @return - */ - public Set sUnion(String key, Collection otherKeys) { - return redisTemplate.opsForSet().union(key, otherKeys); - } - - /** - * key集合与otherKey集合的并集存储到destKey中 - * - * @param key - * @param otherKey - * @param destKey - * @return - */ - public Long sUnionAndStore(String key, String otherKey, String destKey) { - return redisTemplate.opsForSet().unionAndStore(key, otherKey, destKey); - } - - /** - * key集合与多个集合的并集存储到destKey中 - * - * @param key - * @param otherKeys - * @param destKey - * @return - */ - public Long sUnionAndStore(String key, Collection otherKeys, - String destKey) { - return redisTemplate.opsForSet().unionAndStore(key, otherKeys, destKey); - } - - /** - * 获取两个集合的差集 - * - * @param key - * @param otherKey - * @return - */ - public Set sDifference(String key, String otherKey) { - return redisTemplate.opsForSet().difference(key, otherKey); - } - - /** - * 获取key集合与多个集合的差集 - * - * @param key - * @param otherKeys - * @return - */ - public Set sDifference(String key, Collection otherKeys) { - return redisTemplate.opsForSet().difference(key, otherKeys); - } - - /** - * key集合与otherKey集合的差集存储到destKey中 - * - * @param key - * @param otherKey - * @param destKey - * @return - */ - public Long sDifference(String key, String otherKey, String destKey) { - return redisTemplate.opsForSet().differenceAndStore(key, otherKey, - destKey); - } - - /** - * key集合与多个集合的差集存储到destKey中 - * - * @param key - * @param otherKeys - * @param destKey - * @return - */ - public Long sDifference(String key, Collection otherKeys, - String destKey) { - return redisTemplate.opsForSet().differenceAndStore(key, otherKeys, - destKey); - } - - /** - * 获取集合所有元素 - * - * @param key - * @return - */ - public Set setMembers(String key) { - return redisTemplate.opsForSet().members(key); - } - - /** - * 随机获取集合中的一个元素 - * - * @param key - * @return - */ - public String sRandomMember(String key) { - return redisTemplate.opsForSet().randomMember(key); - } - - /** - * 随机获取集合中count个元素 - * - * @param key - * @param count - * @return - */ - public List sRandomMembers(String key, long count) { - return redisTemplate.opsForSet().randomMembers(key, count); - } - - /** - * 随机获取集合中count个元素并且去除重复的 - * - * @param key - * @param count - * @return - */ - public Set sDistinctRandomMembers(String key, long count) { - return redisTemplate.opsForSet().distinctRandomMembers(key, count); - } - - /** - * @param key - * @param options - * @return - */ - public Cursor sScan(String key, ScanOptions options) { - return redisTemplate.opsForSet().scan(key, options); - } - - /**------------------zSet相关操作--------------------------------*/ - - /** - * 添加元素,有序集合是按照元素的score值由小到大排列 - * - * @param key - * @param value - * @param score - * @return - */ - public Boolean zAdd(String key, String value, double score) { - return redisTemplate.opsForZSet().add(key, value, score); - } - - /** - * @param key - * @param values - * @return - */ - public Long zAdd(String key, Set> values) { - return redisTemplate.opsForZSet().add(key, values); - } - - /** - * @param key - * @param values - * @return - */ - public Long zRemove(String key, Object... values) { - return redisTemplate.opsForZSet().remove(key, values); - } - - /** - * 增加元素的score值,并返回增加后的值 - * - * @param key - * @param value - * @param delta - * @return - */ - public Double zIncrementScore(String key, String value, double delta) { - return redisTemplate.opsForZSet().incrementScore(key, value, delta); - } - - /** - * 返回元素在集合的排名,有序集合是按照元素的score值由小到大排列 - * - * @param key - * @param value - * @return 0表示第一位 - */ - public Long zRank(String key, Object value) { - return redisTemplate.opsForZSet().rank(key, value); - } - - /** - * 返回元素在集合的排名,按元素的score值由大到小排列 - * - * @param key - * @param value - * @return - */ - public Long zReverseRank(String key, Object value) { - return redisTemplate.opsForZSet().reverseRank(key, value); - } - - /** - * 获取集合的元素, 从小到大排序 - * - * @param key - * @param start 开始位置 - * @param end 结束位置, -1查询所有 - * @return - */ - public Set zRange(String key, long start, long end) { - return redisTemplate.opsForZSet().range(key, start, end); - } - - /** - * 获取集合元素, 并且把score值也获取 - * - * @param key - * @param start - * @param end - * @return - */ - public Set> zRangeWithScores(String key, long start, - long end) { - return redisTemplate.opsForZSet().rangeWithScores(key, start, end); - } - - /** - * 根据Score值查询集合元素 - * - * @param key - * @param min 最小值 - * @param max 最大值 - * @return - */ - public Set zRangeByScore(String key, double min, double max) { - return redisTemplate.opsForZSet().rangeByScore(key, min, max); - } - - /** - * 根据Score值查询集合元素, 从小到大排序 - * - * @param key - * @param min 最小值 - * @param max 最大值 - * @return - */ - public Set> zRangeByScoreWithScores(String key, - double min, double max) { - return redisTemplate.opsForZSet().rangeByScoreWithScores(key, min, max); - } - - /** - * @param key - * @param min - * @param max - * @param start - * @param end - * @return - */ - public Set> zRangeByScoreWithScores(String key, - double min, double max, long start, long end) { - return redisTemplate.opsForZSet().rangeByScoreWithScores(key, min, max, - start, end); - } - - /** - * 获取集合的元素, 从大到小排序 - * - * @param key - * @param start - * @param end - * @return - */ - public Set zReverseRange(String key, long start, long end) { - return redisTemplate.opsForZSet().reverseRange(key, start, end); - } - - /** - * 获取集合的元素, 从大到小排序, 并返回score值 - * - * @param key - * @param start - * @param end - * @return - */ - public Set> zReverseRangeWithScores(String key, - long start, long end) { - return redisTemplate.opsForZSet().reverseRangeWithScores(key, start, - end); - } - - /** - * 根据Score值查询集合元素, 从大到小排序 - * - * @param key - * @param min - * @param max - * @return - */ - public Set zReverseRangeByScore(String key, double min, - double max) { - return redisTemplate.opsForZSet().reverseRangeByScore(key, min, max); - } - - /** - * 根据Score值查询集合元素, 从大到小排序 - * - * @param key - * @param min - * @param max - * @return - */ - public Set> zReverseRangeByScoreWithScores( - String key, double min, double max) { - return redisTemplate.opsForZSet().reverseRangeByScoreWithScores(key, - min, max); - } - - /** - * @param key - * @param min - * @param max - * @param start - * @param end - * @return - */ - public Set zReverseRangeByScore(String key, double min, - double max, long start, long end) { - return redisTemplate.opsForZSet().reverseRangeByScore(key, min, max, - start, end); - } - - /** - * 根据score值获取集合元素数量 - * - * @param key - * @param min - * @param max - * @return - */ - public Long zCount(String key, double min, double max) { - return redisTemplate.opsForZSet().count(key, min, max); - } - - /** - * 获取集合大小 - * - * @param key - * @return - */ - public Long zSize(String key) { - return redisTemplate.opsForZSet().size(key); - } - - /** - * 获取集合大小 - * - * @param key - * @return - */ - public Long zZCard(String key) { - return redisTemplate.opsForZSet().zCard(key); - } - - /** - * 获取集合中value元素的score值 - * - * @param key - * @param value - * @return - */ - public Double zScore(String key, Object value) { - return redisTemplate.opsForZSet().score(key, value); - } - - /** - * 移除指定索引位置的成员 - * - * @param key - * @param start - * @param end - * @return - */ - public Long zRemoveRange(String key, long start, long end) { - return redisTemplate.opsForZSet().removeRange(key, start, end); - } - - /** - * 根据指定的score值的范围来移除成员 - * - * @param key - * @param min - * @param max - * @return - */ - public Long zRemoveRangeByScore(String key, double min, double max) { - return redisTemplate.opsForZSet().removeRangeByScore(key, min, max); - } - - /** - * 获取key和otherKey的并集并存储在destKey中 - * - * @param key - * @param otherKey - * @param destKey - * @return - */ - public Long zUnionAndStore(String key, String otherKey, String destKey) { - return redisTemplate.opsForZSet().unionAndStore(key, otherKey, destKey); - } - - /** - * @param key - * @param otherKeys - * @param destKey - * @return - */ - public Long zUnionAndStore(String key, Collection otherKeys, - String destKey) { - return redisTemplate.opsForZSet() - .unionAndStore(key, otherKeys, destKey); - } - - /** - * 交集 - * - * @param key - * @param otherKey - * @param destKey - * @return - */ - public Long zIntersectAndStore(String key, String otherKey, - String destKey) { - return redisTemplate.opsForZSet().intersectAndStore(key, otherKey, - destKey); - } - - /** - * 交集 - * - * @param key - * @param otherKeys - * @param destKey - * @return - */ - public Long zIntersectAndStore(String key, Collection otherKeys, - String destKey) { - return redisTemplate.opsForZSet().intersectAndStore(key, otherKeys, - destKey); - } - - /** - * @param key - * @param options - * @return - */ - public Cursor> zScan(String key, ScanOptions options) { - return redisTemplate.opsForZSet().scan(key, options); - } - - /** - * 获取Redis List 序列化 - * - * @param key - * @param targetClass - * @param - * @return - */ - public List getListCache(final String key, Class targetClass) { - byte[] result = redisTemplate.execute(new RedisCallback() { - @Override - public byte[] doInRedis(RedisConnection connection) throws DataAccessException { - return connection.get(key.getBytes()); - } - }); - if (result == null) { - return null; - } - return ProtoStuffSerializerUtil.deserializeList(result, targetClass); - } - - /*** - * 将List 放进缓存里面 - * @param key - * @param objList - * @param expireTime - * @param - * @return - */ - public boolean putListCacheWithExpireTime(String key, List objList, final long expireTime) { - final byte[] bkey = key.getBytes(); - final byte[] bvalue = ProtoStuffSerializerUtil.serializeList(objList); - boolean result = redisTemplate.execute(new RedisCallback() { - @Override - public Boolean doInRedis(RedisConnection connection) throws DataAccessException { - connection.setEx(bkey, expireTime, bvalue); - return true; - } - }); - return result; - } +package cn.celess.common.util; + + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.dao.DataAccessException; +import org.springframework.data.redis.connection.DataType; +import org.springframework.data.redis.connection.RedisConnection; +import org.springframework.data.redis.core.Cursor; +import org.springframework.data.redis.core.RedisCallback; +import org.springframework.data.redis.core.ScanOptions; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.data.redis.core.ZSetOperations.TypedTuple; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.Map.Entry; +import java.util.concurrent.TimeUnit; + +/** + * Redis工具类 + * + * @author WangFan + * @version 1.1 (GitHub文档: https://github.com/whvcse/RedisUtil ) + * @date 2018-02-24 下午03:09:50 + */ + +@Component +public class RedisUtil { + @Autowired + private StringRedisTemplate redisTemplate; + + public StringRedisTemplate getRedisTemplate() { + return this.redisTemplate; + } + + public void setRedisTemplate(StringRedisTemplate redisTemplate) { + this.redisTemplate = redisTemplate; + } + + /** -------------------key相关操作--------------------- */ + + /** + * 删除key + * + * @param key + */ + public void delete(String key) { + redisTemplate.delete(key); + } + + /** + * 批量删除key + * + * @param keys + */ + public void delete(Collection keys) { + redisTemplate.delete(keys); + } + + /** + * 序列化key + * + * @param key + * @return + */ + public byte[] dump(String key) { + return redisTemplate.dump(key); + } + + /** + * 是否存在key + * + * @param key + * @return + */ + public Boolean hasKey(String key) { + return redisTemplate.hasKey(key); + } + + /** + * 设置过期时间 + * + * @param key + * @param timeout + * @param unit + * @return + */ + public Boolean expire(String key, long timeout, TimeUnit unit) { + return redisTemplate.expire(key, timeout, unit); + } + + /** + * 设置过期时间 + * + * @param key + * @param date + * @return + */ + public Boolean expireAt(String key, Date date) { + return redisTemplate.expireAt(key, date); + } + + /** + * 查找匹配的key + * + * @param pattern + * @return + */ + public Set keys(String pattern) { + return redisTemplate.keys(pattern); + } + + /** + * 将当前数据库的 key 移动到给定的数据库 db 当中 + * + * @param key + * @param dbIndex + * @return + */ + public Boolean move(String key, int dbIndex) { + return redisTemplate.move(key, dbIndex); + } + + /** + * 移除 key 的过期时间,key 将持久保持 + * + * @param key + * @return + */ + public Boolean persist(String key) { + return redisTemplate.persist(key); + } + + /** + * 返回 key 的剩余的过期时间 + * + * @param key + * @param unit + * @return + */ + public Long getExpire(String key, TimeUnit unit) { + return redisTemplate.getExpire(key, unit); + } + + /** + * 返回 key 的剩余的过期时间 + * + * @param key + * @return + */ + public Long getExpire(String key) { + return redisTemplate.getExpire(key); + } + + /** + * 从当前数据库中随机返回一个 key + * + * @return + */ + public String randomKey() { + return redisTemplate.randomKey(); + } + + /** + * 修改 key 的名称 + * + * @param oldKey + * @param newKey + */ + public void rename(String oldKey, String newKey) { + redisTemplate.rename(oldKey, newKey); + } + + /** + * 仅当 newkey 不存在时,将 oldKey 改名为 newkey + * + * @param oldKey + * @param newKey + * @return + */ + public Boolean renameIfAbsent(String oldKey, String newKey) { + return redisTemplate.renameIfAbsent(oldKey, newKey); + } + + /** + * 返回 key 所储存的值的类型 + * + * @param key + * @return + */ + public DataType type(String key) { + return redisTemplate.type(key); + } + + /** -------------------string相关操作--------------------- */ + + /** + * 设置指定 key 的值 + * + * @param key + * @param value + */ + public void set(String key, String value) { + redisTemplate.opsForValue().set(key, value); + } + + /** + * 获取指定 key 的值 + * + * @param key + * @return + */ + public String get(String key) { + return redisTemplate.opsForValue().get(key); + } + + /** + * 返回 key 中字符串值的子字符 + * + * @param key + * @param start + * @param end + * @return + */ + public String getRange(String key, long start, long end) { + return redisTemplate.opsForValue().get(key, start, end); + } + + /** + * 将给定 key 的值设为 value ,并返回 key 的旧值(old value) + * + * @param key + * @param value + * @return + */ + public String getAndSet(String key, String value) { + return redisTemplate.opsForValue().getAndSet(key, value); + } + + /** + * 对 key 所储存的字符串值,获取指定偏移量上的位(bit) + * + * @param key + * @param offset + * @return + */ + public Boolean getBit(String key, long offset) { + return redisTemplate.opsForValue().getBit(key, offset); + } + + /** + * 批量获取 + * + * @param keys + * @return + */ + public List multiGet(Collection keys) { + return redisTemplate.opsForValue().multiGet(keys); + } + + /** + * 设置ASCII码, 字符串'a'的ASCII码是97, 转为二进制是'01100001', 此方法是将二进制第offset位值变为value + * + * @param key + * @param offset 位置 + * @param value 值,true为1, false为0 + * @return + */ + public boolean setBit(String key, long offset, boolean value) { + return redisTemplate.opsForValue().setBit(key, offset, value); + } + + /** + * 将值 value 关联到 key ,并将 key 的过期时间设为 timeout + * + * @param key + * @param value + * @param timeout 过期时间 + * @param unit 时间单位, 天:TimeUnit.DAYS 小时:TimeUnit.HOURS 分钟:TimeUnit.MINUTES + * 秒:TimeUnit.SECONDS 毫秒:TimeUnit.MILLISECONDS + */ + public void setEx(String key, String value, long timeout, TimeUnit unit) { + redisTemplate.opsForValue().set(key, value, timeout, unit); + } + + /** + * 只有在 key 不存在时设置 key 的值 + * + * @param key + * @param value + * @return 之前已经存在返回false, 不存在返回true + */ + public boolean setIfAbsent(String key, String value) { + return redisTemplate.opsForValue().setIfAbsent(key, value); + } + + /** + * 用 value 参数覆写给定 key 所储存的字符串值,从偏移量 offset 开始 + * + * @param key + * @param value + * @param offset 从指定位置开始覆写 + */ + public void setRange(String key, String value, long offset) { + redisTemplate.opsForValue().set(key, value, offset); + } + + /** + * 获取字符串的长度 + * + * @param key + * @return + */ + public Long size(String key) { + return redisTemplate.opsForValue().size(key); + } + + /** + * 批量添加 + * + * @param maps + */ + public void multiSet(Map maps) { + redisTemplate.opsForValue().multiSet(maps); + } + + /** + * 同时设置一个或多个 key-value 对,当且仅当所有给定 key 都不存在 + * + * @param maps + * @return 之前已经存在返回false, 不存在返回true + */ + public boolean multiSetIfAbsent(Map maps) { + return redisTemplate.opsForValue().multiSetIfAbsent(maps); + } + + /** + * 增加(自增长), 负数则为自减 + * + * @param key + * @param increment + * @return + */ + public Long incrBy(String key, long increment) { + return redisTemplate.opsForValue().increment(key, increment); + } + + /** + * @param key + * @param increment + * @return + */ + public Double incrByFloat(String key, double increment) { + return redisTemplate.opsForValue().increment(key, increment); + } + + /** + * 追加到末尾 + * + * @param key + * @param value + * @return + */ + public Integer append(String key, String value) { + return redisTemplate.opsForValue().append(key, value); + } + + /** -------------------hash相关操作------------------------- */ + + /** + * 获取存储在哈希表中指定字段的值 + * + * @param key + * @param field + * @return + */ + public Object hGet(String key, String field) { + return redisTemplate.opsForHash().get(key, field); + } + + /** + * 获取所有给定字段的值 + * + * @param key + * @return + */ + public Map hGetAll(String key) { + return redisTemplate.opsForHash().entries(key); + } + + /** + * 获取所有给定字段的值 + * + * @param key + * @param fields + * @return + */ + public List hMultiGet(String key, Collection fields) { + return redisTemplate.opsForHash().multiGet(key, fields); + } + + public void hPut(String key, String hashKey, String value) { + redisTemplate.opsForHash().put(key, hashKey, value); + } + + public void hPutAll(String key, Map maps) { + redisTemplate.opsForHash().putAll(key, maps); + } + + /** + * 仅当hashKey不存在时才设置 + * + * @param key + * @param hashKey + * @param value + * @return + */ + public Boolean hPutIfAbsent(String key, String hashKey, String value) { + return redisTemplate.opsForHash().putIfAbsent(key, hashKey, value); + } + + /** + * 删除一个或多个哈希表字段 + * + * @param key + * @param fields + * @return + */ + public Long hDelete(String key, Object... fields) { + return redisTemplate.opsForHash().delete(key, fields); + } + + /** + * 查看哈希表 key 中,指定的字段是否存在 + * + * @param key + * @param field + * @return + */ + public boolean hExists(String key, String field) { + return redisTemplate.opsForHash().hasKey(key, field); + } + + /** + * 为哈希表 key 中的指定字段的整数值加上增量 increment + * + * @param key + * @param field + * @param increment + * @return + */ + public Long hIncrBy(String key, Object field, long increment) { + return redisTemplate.opsForHash().increment(key, field, increment); + } + + /** + * 为哈希表 key 中的指定字段的整数值加上增量 increment + * + * @param key + * @param field + * @param delta + * @return + */ + public Double hIncrByFloat(String key, Object field, double delta) { + return redisTemplate.opsForHash().increment(key, field, delta); + } + + /** + * 获取所有哈希表中的字段 + * + * @param key + * @return + */ + public Set hKeys(String key) { + return redisTemplate.opsForHash().keys(key); + } + + /** + * 获取哈希表中字段的数量 + * + * @param key + * @return + */ + public Long hSize(String key) { + return redisTemplate.opsForHash().size(key); + } + + /** + * 获取哈希表中所有值 + * + * @param key + * @return + */ + public List hValues(String key) { + return redisTemplate.opsForHash().values(key); + } + + /** + * 迭代哈希表中的键值对 + * + * @param key + * @param options + * @return + */ + public Cursor> hScan(String key, ScanOptions options) { + return redisTemplate.opsForHash().scan(key, options); + } + + /** ------------------------list相关操作---------------------------- */ + + /** + * 通过索引获取列表中的元素 + * + * @param key + * @param index + * @return + */ + public String lIndex(String key, long index) { + return redisTemplate.opsForList().index(key, index); + } + + /** + * 获取列表指定范围内的元素 + * + * @param key + * @param start 开始位置, 0是开始位置 + * @param end 结束位置, -1返回所有 + * @return + */ + public List lRange(String key, long start, long end) { + return redisTemplate.opsForList().range(key, start, end); + } + + /** + * 存储在list头部 + * + * @param key + * @param value + * @return + */ + public Long lLeftPush(String key, String value) { + return redisTemplate.opsForList().leftPush(key, value); + } + + /** + * @param key + * @param value + * @return + */ + public Long lLeftPushAll(String key, String... value) { + return redisTemplate.opsForList().leftPushAll(key, value); + } + + /** + * @param key + * @param value + * @return + */ + public Long lLeftPushAll(String key, Collection value) { + return redisTemplate.opsForList().leftPushAll(key, value); + } + + /** + * 当list存在的时候才加入 + * + * @param key + * @param value + * @return + */ + public Long lLeftPushIfPresent(String key, String value) { + return redisTemplate.opsForList().leftPushIfPresent(key, value); + } + + /** + * 如果pivot存在,再pivot前面添加 + * + * @param key + * @param pivot + * @param value + * @return + */ + public Long lLeftPush(String key, String pivot, String value) { + return redisTemplate.opsForList().leftPush(key, pivot, value); + } + + /** + * @param key + * @param value + * @return + */ + public Long lRightPush(String key, String value) { + return redisTemplate.opsForList().rightPush(key, value); + } + + /** + * @param key + * @param value + * @return + */ + public Long lRightPushAll(String key, String... value) { + return redisTemplate.opsForList().rightPushAll(key, value); + } + + /** + * @param key + * @param value + * @return + */ + public Long lRightPushAll(String key, Collection value) { + return redisTemplate.opsForList().rightPushAll(key, value); + } + + /** + * 为已存在的列表添加值 + * + * @param key + * @param value + * @return + */ + public Long lRightPushIfPresent(String key, String value) { + return redisTemplate.opsForList().rightPushIfPresent(key, value); + } + + /** + * 在pivot元素的右边添加值 + * + * @param key + * @param pivot + * @param value + * @return + */ + public Long lRightPush(String key, String pivot, String value) { + return redisTemplate.opsForList().rightPush(key, pivot, value); + } + + /** + * 通过索引设置列表元素的值 + * + * @param key + * @param index 位置 + * @param value + */ + public void lSet(String key, long index, String value) { + redisTemplate.opsForList().set(key, index, value); + } + + /** + * 移出并获取列表的第一个元素 + * + * @param key + * @return 删除的元素 + */ + public String lLeftPop(String key) { + return redisTemplate.opsForList().leftPop(key); + } + + /** + * 移出并获取列表的第一个元素, 如果列表没有元素会阻塞列表直到等待超时或发现可弹出元素为止 + * + * @param key + * @param timeout 等待时间 + * @param unit 时间单位 + * @return + */ + public String lBLeftPop(String key, long timeout, TimeUnit unit) { + return redisTemplate.opsForList().leftPop(key, timeout, unit); + } + + /** + * 移除并获取列表最后一个元素 + * + * @param key + * @return 删除的元素 + */ + public String lRightPop(String key) { + return redisTemplate.opsForList().rightPop(key); + } + + /** + * 移出并获取列表的最后一个元素, 如果列表没有元素会阻塞列表直到等待超时或发现可弹出元素为止 + * + * @param key + * @param timeout 等待时间 + * @param unit 时间单位 + * @return + */ + public String lBRightPop(String key, long timeout, TimeUnit unit) { + return redisTemplate.opsForList().rightPop(key, timeout, unit); + } + + /** + * 移除列表的最后一个元素,并将该元素添加到另一个列表并返回 + * + * @param sourceKey + * @param destinationKey + * @return + */ + public String lRightPopAndLeftPush(String sourceKey, String destinationKey) { + return redisTemplate.opsForList().rightPopAndLeftPush(sourceKey, + destinationKey); + } + + /** + * 从列表中弹出一个值,将弹出的元素插入到另外一个列表中并返回它; 如果列表没有元素会阻塞列表直到等待超时或发现可弹出元素为止 + * + * @param sourceKey + * @param destinationKey + * @param timeout + * @param unit + * @return + */ + public String lBRightPopAndLeftPush(String sourceKey, String destinationKey, + long timeout, TimeUnit unit) { + return redisTemplate.opsForList().rightPopAndLeftPush(sourceKey, + destinationKey, timeout, unit); + } + + /** + * 删除集合中值等于value得元素 + * + * @param key + * @param index index=0, 删除所有值等于value的元素; index>0, 从头部开始删除第一个值等于value的元素; + * index<0, 从尾部开始删除第一个值等于value的元素; + * @param value + * @return + */ + public Long lRemove(String key, long index, String value) { + return redisTemplate.opsForList().remove(key, index, value); + } + + /** + * 裁剪list + * + * @param key + * @param start + * @param end + */ + public void lTrim(String key, long start, long end) { + redisTemplate.opsForList().trim(key, start, end); + } + + /** + * 获取列表长度 + * + * @param key + * @return + */ + public Long lLen(String key) { + return redisTemplate.opsForList().size(key); + } + + /** --------------------set相关操作-------------------------- */ + + /** + * set添加元素 + * + * @param key + * @param values + * @return + */ + public Long sAdd(String key, String... values) { + return redisTemplate.opsForSet().add(key, values); + } + + /** + * set移除元素 + * + * @param key + * @param values + * @return + */ + public Long sRemove(String key, Object... values) { + return redisTemplate.opsForSet().remove(key, values); + } + + /** + * 移除并返回集合的一个随机元素 + * + * @param key + * @return + */ + public String sPop(String key) { + return redisTemplate.opsForSet().pop(key); + } + + /** + * 将元素value从一个集合移到另一个集合 + * + * @param key + * @param value + * @param destKey + * @return + */ + public Boolean sMove(String key, String value, String destKey) { + return redisTemplate.opsForSet().move(key, value, destKey); + } + + /** + * 获取集合的大小 + * + * @param key + * @return + */ + public Long sSize(String key) { + return redisTemplate.opsForSet().size(key); + } + + /** + * 判断集合是否包含value + * + * @param key + * @param value + * @return + */ + public Boolean sIsMember(String key, Object value) { + return redisTemplate.opsForSet().isMember(key, value); + } + + /** + * 获取两个集合的交集 + * + * @param key + * @param otherKey + * @return + */ + public Set sIntersect(String key, String otherKey) { + return redisTemplate.opsForSet().intersect(key, otherKey); + } + + /** + * 获取key集合与多个集合的交集 + * + * @param key + * @param otherKeys + * @return + */ + public Set sIntersect(String key, Collection otherKeys) { + return redisTemplate.opsForSet().intersect(key, otherKeys); + } + + /** + * key集合与otherKey集合的交集存储到destKey集合中 + * + * @param key + * @param otherKey + * @param destKey + * @return + */ + public Long sIntersectAndStore(String key, String otherKey, String destKey) { + return redisTemplate.opsForSet().intersectAndStore(key, otherKey, + destKey); + } + + /** + * key集合与多个集合的交集存储到destKey集合中 + * + * @param key + * @param otherKeys + * @param destKey + * @return + */ + public Long sIntersectAndStore(String key, Collection otherKeys, + String destKey) { + return redisTemplate.opsForSet().intersectAndStore(key, otherKeys, + destKey); + } + + /** + * 获取两个集合的并集 + * + * @param key + * @param otherKeys + * @return + */ + public Set sUnion(String key, String otherKeys) { + return redisTemplate.opsForSet().union(key, otherKeys); + } + + /** + * 获取key集合与多个集合的并集 + * + * @param key + * @param otherKeys + * @return + */ + public Set sUnion(String key, Collection otherKeys) { + return redisTemplate.opsForSet().union(key, otherKeys); + } + + /** + * key集合与otherKey集合的并集存储到destKey中 + * + * @param key + * @param otherKey + * @param destKey + * @return + */ + public Long sUnionAndStore(String key, String otherKey, String destKey) { + return redisTemplate.opsForSet().unionAndStore(key, otherKey, destKey); + } + + /** + * key集合与多个集合的并集存储到destKey中 + * + * @param key + * @param otherKeys + * @param destKey + * @return + */ + public Long sUnionAndStore(String key, Collection otherKeys, + String destKey) { + return redisTemplate.opsForSet().unionAndStore(key, otherKeys, destKey); + } + + /** + * 获取两个集合的差集 + * + * @param key + * @param otherKey + * @return + */ + public Set sDifference(String key, String otherKey) { + return redisTemplate.opsForSet().difference(key, otherKey); + } + + /** + * 获取key集合与多个集合的差集 + * + * @param key + * @param otherKeys + * @return + */ + public Set sDifference(String key, Collection otherKeys) { + return redisTemplate.opsForSet().difference(key, otherKeys); + } + + /** + * key集合与otherKey集合的差集存储到destKey中 + * + * @param key + * @param otherKey + * @param destKey + * @return + */ + public Long sDifference(String key, String otherKey, String destKey) { + return redisTemplate.opsForSet().differenceAndStore(key, otherKey, + destKey); + } + + /** + * key集合与多个集合的差集存储到destKey中 + * + * @param key + * @param otherKeys + * @param destKey + * @return + */ + public Long sDifference(String key, Collection otherKeys, + String destKey) { + return redisTemplate.opsForSet().differenceAndStore(key, otherKeys, + destKey); + } + + /** + * 获取集合所有元素 + * + * @param key + * @return + */ + public Set setMembers(String key) { + return redisTemplate.opsForSet().members(key); + } + + /** + * 随机获取集合中的一个元素 + * + * @param key + * @return + */ + public String sRandomMember(String key) { + return redisTemplate.opsForSet().randomMember(key); + } + + /** + * 随机获取集合中count个元素 + * + * @param key + * @param count + * @return + */ + public List sRandomMembers(String key, long count) { + return redisTemplate.opsForSet().randomMembers(key, count); + } + + /** + * 随机获取集合中count个元素并且去除重复的 + * + * @param key + * @param count + * @return + */ + public Set sDistinctRandomMembers(String key, long count) { + return redisTemplate.opsForSet().distinctRandomMembers(key, count); + } + + /** + * @param key + * @param options + * @return + */ + public Cursor sScan(String key, ScanOptions options) { + return redisTemplate.opsForSet().scan(key, options); + } + + /**------------------zSet相关操作--------------------------------*/ + + /** + * 添加元素,有序集合是按照元素的score值由小到大排列 + * + * @param key + * @param value + * @param score + * @return + */ + public Boolean zAdd(String key, String value, double score) { + return redisTemplate.opsForZSet().add(key, value, score); + } + + /** + * @param key + * @param values + * @return + */ + public Long zAdd(String key, Set> values) { + return redisTemplate.opsForZSet().add(key, values); + } + + /** + * @param key + * @param values + * @return + */ + public Long zRemove(String key, Object... values) { + return redisTemplate.opsForZSet().remove(key, values); + } + + /** + * 增加元素的score值,并返回增加后的值 + * + * @param key + * @param value + * @param delta + * @return + */ + public Double zIncrementScore(String key, String value, double delta) { + return redisTemplate.opsForZSet().incrementScore(key, value, delta); + } + + /** + * 返回元素在集合的排名,有序集合是按照元素的score值由小到大排列 + * + * @param key + * @param value + * @return 0表示第一位 + */ + public Long zRank(String key, Object value) { + return redisTemplate.opsForZSet().rank(key, value); + } + + /** + * 返回元素在集合的排名,按元素的score值由大到小排列 + * + * @param key + * @param value + * @return + */ + public Long zReverseRank(String key, Object value) { + return redisTemplate.opsForZSet().reverseRank(key, value); + } + + /** + * 获取集合的元素, 从小到大排序 + * + * @param key + * @param start 开始位置 + * @param end 结束位置, -1查询所有 + * @return + */ + public Set zRange(String key, long start, long end) { + return redisTemplate.opsForZSet().range(key, start, end); + } + + /** + * 获取集合元素, 并且把score值也获取 + * + * @param key + * @param start + * @param end + * @return + */ + public Set> zRangeWithScores(String key, long start, + long end) { + return redisTemplate.opsForZSet().rangeWithScores(key, start, end); + } + + /** + * 根据Score值查询集合元素 + * + * @param key + * @param min 最小值 + * @param max 最大值 + * @return + */ + public Set zRangeByScore(String key, double min, double max) { + return redisTemplate.opsForZSet().rangeByScore(key, min, max); + } + + /** + * 根据Score值查询集合元素, 从小到大排序 + * + * @param key + * @param min 最小值 + * @param max 最大值 + * @return + */ + public Set> zRangeByScoreWithScores(String key, + double min, double max) { + return redisTemplate.opsForZSet().rangeByScoreWithScores(key, min, max); + } + + /** + * @param key + * @param min + * @param max + * @param start + * @param end + * @return + */ + public Set> zRangeByScoreWithScores(String key, + double min, double max, long start, long end) { + return redisTemplate.opsForZSet().rangeByScoreWithScores(key, min, max, + start, end); + } + + /** + * 获取集合的元素, 从大到小排序 + * + * @param key + * @param start + * @param end + * @return + */ + public Set zReverseRange(String key, long start, long end) { + return redisTemplate.opsForZSet().reverseRange(key, start, end); + } + + /** + * 获取集合的元素, 从大到小排序, 并返回score值 + * + * @param key + * @param start + * @param end + * @return + */ + public Set> zReverseRangeWithScores(String key, + long start, long end) { + return redisTemplate.opsForZSet().reverseRangeWithScores(key, start, + end); + } + + /** + * 根据Score值查询集合元素, 从大到小排序 + * + * @param key + * @param min + * @param max + * @return + */ + public Set zReverseRangeByScore(String key, double min, + double max) { + return redisTemplate.opsForZSet().reverseRangeByScore(key, min, max); + } + + /** + * 根据Score值查询集合元素, 从大到小排序 + * + * @param key + * @param min + * @param max + * @return + */ + public Set> zReverseRangeByScoreWithScores( + String key, double min, double max) { + return redisTemplate.opsForZSet().reverseRangeByScoreWithScores(key, + min, max); + } + + /** + * @param key + * @param min + * @param max + * @param start + * @param end + * @return + */ + public Set zReverseRangeByScore(String key, double min, + double max, long start, long end) { + return redisTemplate.opsForZSet().reverseRangeByScore(key, min, max, + start, end); + } + + /** + * 根据score值获取集合元素数量 + * + * @param key + * @param min + * @param max + * @return + */ + public Long zCount(String key, double min, double max) { + return redisTemplate.opsForZSet().count(key, min, max); + } + + /** + * 获取集合大小 + * + * @param key + * @return + */ + public Long zSize(String key) { + return redisTemplate.opsForZSet().size(key); + } + + /** + * 获取集合大小 + * + * @param key + * @return + */ + public Long zZCard(String key) { + return redisTemplate.opsForZSet().zCard(key); + } + + /** + * 获取集合中value元素的score值 + * + * @param key + * @param value + * @return + */ + public Double zScore(String key, Object value) { + return redisTemplate.opsForZSet().score(key, value); + } + + /** + * 移除指定索引位置的成员 + * + * @param key + * @param start + * @param end + * @return + */ + public Long zRemoveRange(String key, long start, long end) { + return redisTemplate.opsForZSet().removeRange(key, start, end); + } + + /** + * 根据指定的score值的范围来移除成员 + * + * @param key + * @param min + * @param max + * @return + */ + public Long zRemoveRangeByScore(String key, double min, double max) { + return redisTemplate.opsForZSet().removeRangeByScore(key, min, max); + } + + /** + * 获取key和otherKey的并集并存储在destKey中 + * + * @param key + * @param otherKey + * @param destKey + * @return + */ + public Long zUnionAndStore(String key, String otherKey, String destKey) { + return redisTemplate.opsForZSet().unionAndStore(key, otherKey, destKey); + } + + /** + * @param key + * @param otherKeys + * @param destKey + * @return + */ + public Long zUnionAndStore(String key, Collection otherKeys, + String destKey) { + return redisTemplate.opsForZSet() + .unionAndStore(key, otherKeys, destKey); + } + + /** + * 交集 + * + * @param key + * @param otherKey + * @param destKey + * @return + */ + public Long zIntersectAndStore(String key, String otherKey, + String destKey) { + return redisTemplate.opsForZSet().intersectAndStore(key, otherKey, + destKey); + } + + /** + * 交集 + * + * @param key + * @param otherKeys + * @param destKey + * @return + */ + public Long zIntersectAndStore(String key, Collection otherKeys, + String destKey) { + return redisTemplate.opsForZSet().intersectAndStore(key, otherKeys, + destKey); + } + + /** + * @param key + * @param options + * @return + */ + public Cursor> zScan(String key, ScanOptions options) { + return redisTemplate.opsForZSet().scan(key, options); + } + + /** + * 获取Redis List 序列化 + * + * @param key + * @param targetClass + * @param + * @return + */ + public List getListCache(final String key, Class targetClass) { + byte[] result = redisTemplate.execute(new RedisCallback() { + @Override + public byte[] doInRedis(RedisConnection connection) throws DataAccessException { + return connection.get(key.getBytes()); + } + }); + if (result == null) { + return null; + } + return ProtoStuffSerializerUtil.deserializeList(result, targetClass); + } + + /*** + * 将List 放进缓存里面 + * @param key + * @param objList + * @param expireTime + * @param + * @return + */ + public boolean putListCacheWithExpireTime(String key, List objList, final long expireTime) { + final byte[] bkey = key.getBytes(); + final byte[] bvalue = ProtoStuffSerializerUtil.serializeList(objList); + boolean result = redisTemplate.execute((RedisCallback) connection -> { + connection.setEx(bkey, expireTime, bvalue); + return true; + }); + return result; + } } \ No newline at end of file diff --git a/src/main/java/cn/celess/blog/util/RegexUtil.java b/blog-common/src/main/java/cn/celess/common/util/RegexUtil.java similarity index 94% rename from src/main/java/cn/celess/blog/util/RegexUtil.java rename to blog-common/src/main/java/cn/celess/common/util/RegexUtil.java index 6926229..b9beecb 100644 --- a/src/main/java/cn/celess/blog/util/RegexUtil.java +++ b/blog-common/src/main/java/cn/celess/common/util/RegexUtil.java @@ -1,80 +1,80 @@ -package cn.celess.blog.util; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * @author : xiaohai - * @date : 2019/05/12 11:04 - */ -public class RegexUtil { - /** - * 网址匹配 - * - * @param url - * @return - */ - public static boolean urlMatch(String url) { - if (url == null || url.replaceAll(" ", "").isEmpty()) { - return false; - } - //正则 (http(s)://www.celess/xxxx,www.celess.cn/xxx) - String pattern = "^(http://|https://|)([\\w-]+\\.)+[\\w-]+(/[\\w-./?%&=]*)?$"; - return match(url, pattern); - } - - /** - * 邮箱验证 - * - * @param email - * @return - */ - public static boolean emailMatch(String email) { - if (email == null || email.replaceAll(" ", "").isEmpty()) { - return false; - } - //正则 - String pattern = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$"; - return match(email, pattern); - } - - /** - * 手机号匹配 - * - * @param phone - * @return - */ - public static boolean phoneMatch(String phone) { - if (phone == null || phone.replaceAll(" ", "").isEmpty()) { - return false; - } - //正则 - String pattern = "^([1][3,4,5,6,7,8,9])\\d{9}$"; - return match(phone, pattern); - } - - /** - * 密码正则 - * 最短6位,最长16位 {6,16} - * 可以包含小写大母 [a-z] 和大写字母 [A-Z] - * 可以包含数字 [0-9] - * 可以包含下划线 [ _ ] 和减号 [ - ] - * - * @param pwd - * @return - */ - public static boolean pwdMatch(String pwd) { - if (pwd == null || pwd.replaceAll(" ", "").isEmpty()) { - return false; - } - //正则 - String pattern = "^[\\w_-]{6,16}$"; - return match(pwd, pattern); - } - - private static boolean match(String str, String pattern) { - Pattern r = Pattern.compile(pattern); - Matcher m = r.matcher(str); - return m.matches(); - } -} +package cn.celess.common.util; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * @author : xiaohai + * @date : 2019/05/12 11:04 + */ +public class RegexUtil { + /** + * 网址匹配 + * + * @param url + * @return + */ + public static boolean urlMatch(String url) { + if (url == null || url.replaceAll(" ", "").isEmpty()) { + return false; + } + //正则 (http(s)://www.celess/xxxx,www.celess.cn/xxx) + String pattern = "^(http://|https://|)([\\w-]+\\.)+[\\w-]+(/[\\w-./?%&=]*)?$"; + return match(url, pattern); + } + + /** + * 邮箱验证 + * + * @param email + * @return + */ + public static boolean emailMatch(String email) { + if (email == null || email.replaceAll(" ", "").isEmpty()) { + return false; + } + //正则 + String pattern = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$"; + return match(email, pattern); + } + + /** + * 手机号匹配 + * + * @param phone + * @return + */ + public static boolean phoneMatch(String phone) { + if (phone == null || phone.replaceAll(" ", "").isEmpty()) { + return false; + } + //正则 + String pattern = "^([1][3,4,5,6,7,8,9])\\d{9}$"; + return match(phone, pattern); + } + + /** + * 密码正则 + * 最短6位,最长16位 {6,16} + * 可以包含小写大母 [a-z] 和大写字母 [A-Z] + * 可以包含数字 [0-9] + * 可以包含下划线 [ _ ] 和减号 [ - ] + * + * @param pwd + * @return + */ + public static boolean pwdMatch(String pwd) { + if (pwd == null || pwd.replaceAll(" ", "").isEmpty()) { + return false; + } + //正则 + String pattern = "^[\\w_-]{6,16}$"; + return match(pwd, pattern); + } + + private static boolean match(String str, String pattern) { + Pattern r = Pattern.compile(pattern); + Matcher m = r.matcher(str); + return m.matches(); + } +} diff --git a/src/main/java/cn/celess/blog/util/RequestUtil.java b/blog-common/src/main/java/cn/celess/common/util/RequestUtil.java similarity index 90% rename from src/main/java/cn/celess/blog/util/RequestUtil.java rename to blog-common/src/main/java/cn/celess/common/util/RequestUtil.java index 1a5336e..d8aa254 100644 --- a/src/main/java/cn/celess/blog/util/RequestUtil.java +++ b/blog-common/src/main/java/cn/celess/common/util/RequestUtil.java @@ -1,17 +1,17 @@ -package cn.celess.blog.util; - -import javax.servlet.http.HttpServletRequest; - -/** - * @Author: 小海 - * @Date: 2019/10/18 15:44 - * @Description: - */ -public class RequestUtil { - public static String getCompleteUrlAndMethod(HttpServletRequest request) { - // like this : /articles?page=1&count=5:GET - return request.getRequestURI() + - (request.getQueryString() == null ? "" : "?" + request.getQueryString()) + - ":" + request.getMethod(); - } -} +package cn.celess.common.util; + +import javax.servlet.http.HttpServletRequest; + +/** + * @Author: 小海 + * @Date: 2019/10/18 15:44 + * @Description: + */ +public class RequestUtil { + public static String getCompleteUrlAndMethod(HttpServletRequest request) { + // like this : /articles?page=1&count=5:GET + return request.getRequestURI() + + (request.getQueryString() == null ? "" : "?" + request.getQueryString()) + + ":" + request.getMethod(); + } +} diff --git a/src/main/java/cn/celess/blog/util/StringFromHtmlUtil.java b/blog-common/src/main/java/cn/celess/common/util/StringFromHtmlUtil.java similarity index 90% rename from src/main/java/cn/celess/blog/util/StringFromHtmlUtil.java rename to blog-common/src/main/java/cn/celess/common/util/StringFromHtmlUtil.java index afd1502..9b68da9 100644 --- a/src/main/java/cn/celess/blog/util/StringFromHtmlUtil.java +++ b/blog-common/src/main/java/cn/celess/common/util/StringFromHtmlUtil.java @@ -1,17 +1,17 @@ -package cn.celess.blog.util; - -/** - * @author : xiaohai - * @date : 2019/03/28 17:21 - */ -public class StringFromHtmlUtil { - public static String getString(String html) { - //从html中提取纯文本 - //剔出的标签 - String txtcontent = html.replaceAll("]+>", ""); - //去除字符串中的空格,回车,换行符,制表符 - txtcontent = txtcontent.replaceAll("\\s*|\t|\r|\n", ""); - return txtcontent; - } -} - +package cn.celess.common.util; + +/** + * @author : xiaohai + * @date : 2019/03/28 17:21 + */ +public class StringFromHtmlUtil { + public static String getString(String html) { + //从html中提取纯文本 + //剔出的标签 + String txtcontent = html.replaceAll("]+>", ""); + //去除字符串中的空格,回车,换行符,制表符 + txtcontent = txtcontent.replaceAll("\\s*|\t|\r|\n", ""); + return txtcontent; + } +} + diff --git a/src/main/java/cn/celess/blog/util/VeriCodeUtil.java b/blog-common/src/main/java/cn/celess/common/util/VeriCodeUtil.java similarity index 95% rename from src/main/java/cn/celess/blog/util/VeriCodeUtil.java rename to blog-common/src/main/java/cn/celess/common/util/VeriCodeUtil.java index e3cb153..abdbd0e 100644 --- a/src/main/java/cn/celess/blog/util/VeriCodeUtil.java +++ b/blog-common/src/main/java/cn/celess/common/util/VeriCodeUtil.java @@ -1,90 +1,90 @@ -package cn.celess.blog.util; - - -import java.awt.*; -import java.awt.image.BufferedImage; -import java.util.Random; - -/** - * @author : xiaohai - * @date : 2019/04/11 15:42 - */ - -public class VeriCodeUtil { - // 验证码字符集 - private static final char[] chars = { - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', - 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', - 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', - 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'}; - - // 字符数量 - private static final int SIZE = 4; - // 干扰线数量 - private static final int LINES = 5; - // 宽度 - private static final int WIDTH = 80; - // 高度 - private static final int HEIGHT = 40; - // 字体大小 - private static final int FONT_SIZE = 30; - - /** - * 生成随机验证码及图片 - * Object[0]:验证码字符串; - * Object[1]:验证码图片。 - */ - public static Object[] createImage() { - StringBuffer sb = new StringBuffer(); - // 1.创建空白图片 - BufferedImage image = new BufferedImage( - WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB); - // 2.获取图片画笔 - Graphics graphic = image.getGraphics(); - // 3.设置画笔颜色 - graphic.setColor(Color.LIGHT_GRAY); - // 4.绘制矩形背景 - graphic.fillRect(0, 0, WIDTH, HEIGHT); - // 5.画随机字符 - Random ran = new Random(); - for (int i = 0; i < SIZE; i++) { - // 取随机字符索引 - int n = ran.nextInt(chars.length); - // 设置随机颜色 - graphic.setColor(getRandomColor()); - // 设置字体大小 - graphic.setFont(new Font( - null, Font.BOLD + Font.ITALIC, FONT_SIZE)); - // 画字符 - graphic.drawString( - chars[n] + "", i * WIDTH / SIZE, HEIGHT * 2 / 3); - // 记录字符 - sb.append(chars[n]); - } - // 6.画干扰线 - for (int i = 0; i < LINES; i++) { - // 设置随机颜色 - graphic.setColor(getRandomColor()); - // 随机画线 - graphic.drawLine(ran.nextInt(WIDTH), ran.nextInt(HEIGHT), - ran.nextInt(WIDTH), ran.nextInt(HEIGHT)); - } - // 7.返回验证码和图片 - return new Object[]{sb.toString(), image}; - } - - /** - * 随机取色 - */ - public static Color getRandomColor() { - Random ran = new Random(); - Color color = new Color(ran.nextInt(256), - ran.nextInt(256), ran.nextInt(256)); - return color; - } - - -} - - +package cn.celess.common.util; + + +import java.awt.*; +import java.awt.image.BufferedImage; +import java.util.Random; + +/** + * @author : xiaohai + * @date : 2019/04/11 15:42 + */ + +public class VeriCodeUtil { + // 验证码字符集 + private static final char[] chars = { + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', + 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', + 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', + 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', + 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'}; + + // 字符数量 + private static final int SIZE = 4; + // 干扰线数量 + private static final int LINES = 5; + // 宽度 + private static final int WIDTH = 80; + // 高度 + private static final int HEIGHT = 40; + // 字体大小 + private static final int FONT_SIZE = 30; + + /** + * 生成随机验证码及图片 + * Object[0]:验证码字符串; + * Object[1]:验证码图片。 + */ + public static Object[] createImage() { + StringBuffer sb = new StringBuffer(); + // 1.创建空白图片 + BufferedImage image = new BufferedImage( + WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB); + // 2.获取图片画笔 + Graphics graphic = image.getGraphics(); + // 3.设置画笔颜色 + graphic.setColor(Color.LIGHT_GRAY); + // 4.绘制矩形背景 + graphic.fillRect(0, 0, WIDTH, HEIGHT); + // 5.画随机字符 + Random ran = new Random(); + for (int i = 0; i < SIZE; i++) { + // 取随机字符索引 + int n = ran.nextInt(chars.length); + // 设置随机颜色 + graphic.setColor(getRandomColor()); + // 设置字体大小 + graphic.setFont(new Font( + null, Font.BOLD + Font.ITALIC, FONT_SIZE)); + // 画字符 + graphic.drawString( + chars[n] + "", i * WIDTH / SIZE, HEIGHT * 2 / 3); + // 记录字符 + sb.append(chars[n]); + } + // 6.画干扰线 + for (int i = 0; i < LINES; i++) { + // 设置随机颜色 + graphic.setColor(getRandomColor()); + // 随机画线 + graphic.drawLine(ran.nextInt(WIDTH), ran.nextInt(HEIGHT), + ran.nextInt(WIDTH), ran.nextInt(HEIGHT)); + } + // 7.返回验证码和图片 + return new Object[]{sb.toString(), image}; + } + + /** + * 随机取色 + */ + public static Color getRandomColor() { + Random ran = new Random(); + Color color = new Color(ran.nextInt(256), + ran.nextInt(256), ran.nextInt(256)); + return color; + } + + +} + + diff --git a/src/main/resources/mapper/ArticleTagMapper.xml b/blog-common/src/main/resources/mapper/ArticleTagMapper.xml similarity index 86% rename from src/main/resources/mapper/ArticleTagMapper.xml rename to blog-common/src/main/resources/mapper/ArticleTagMapper.xml index bfd0c46..aaf92da 100644 --- a/src/main/resources/mapper/ArticleTagMapper.xml +++ b/blog-common/src/main/resources/mapper/ArticleTagMapper.xml @@ -1,16 +1,16 @@ - + - + - + - + @@ -64,7 +64,7 @@ and article_tag.t_id = tag_category.t_id - select tag_category.* from article_tag, tag_category diff --git a/src/main/resources/mapper/CategoryMapper.xml b/blog-common/src/main/resources/mapper/CategoryMapper.xml similarity index 91% rename from src/main/resources/mapper/CategoryMapper.xml rename to blog-common/src/main/resources/mapper/CategoryMapper.xml index e134864..1a2c415 100644 --- a/src/main/resources/mapper/CategoryMapper.xml +++ b/blog-common/src/main/resources/mapper/CategoryMapper.xml @@ -1,93 +1,93 @@ - - - - - - - - - - - - insert into tag_category (t_name, is_category) - values (#{name}, true); - - - - update tag_category - set t_name=#{name} - where t_id = #{id} - and is_category = true - - - - update tag_category - set is_delete= true - where t_id = #{id} - and is_category = true - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + insert into tag_category (t_name, is_category) + values (#{name}, true); + + + + update tag_category + set t_name=#{name} + where t_id = #{id} + and is_category = true + + + + update tag_category + set is_delete= true + where t_id = #{id} + and is_category = true + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/mapper/CommentMapper.xml b/blog-common/src/main/resources/mapper/CommentMapper.xml similarity index 91% rename from src/main/resources/mapper/CommentMapper.xml rename to blog-common/src/main/resources/mapper/CommentMapper.xml index 2696cca..4388e62 100644 --- a/src/main/resources/mapper/CommentMapper.xml +++ b/blog-common/src/main/resources/mapper/CommentMapper.xml @@ -1,131 +1,131 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - insert into comment (co_page_path, co_content, co_date, co_pid, co_from_author_id, co_to_author_id, co_status) - VALUES (#{pagePath}, #{content}, now(), #{pid}, #{fromUser.id}, #{toUser.id}, 0) - - - - update comment - set co_content=#{content} - where co_id = #{id} - - - - update comment - set co_status = 3 - where co_id = #{id} - - - - update comment - set co_status = 3 - where co_page_path = #{path} - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + insert into comment (co_page_path, co_content, co_date, co_pid, co_from_author_id, co_to_author_id, co_status) + VALUES (#{pagePath}, #{content}, now(), #{pid}, #{fromUser.id}, #{toUser.id}, 0) + + + + update comment + set co_content=#{content} + where co_id = #{id} + + + + update comment + set co_status = 3 + where co_id = #{id} + + + + update comment + set co_status = 3 + where co_page_path = #{path} + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/resources/mapper/PartnerSiteMapper.xml b/blog-common/src/main/resources/mapper/PartnerSiteMapper.xml similarity index 86% rename from src/main/resources/mapper/PartnerSiteMapper.xml rename to blog-common/src/main/resources/mapper/PartnerSiteMapper.xml index 4b625f2..bc3d245 100644 --- a/src/main/resources/mapper/PartnerSiteMapper.xml +++ b/blog-common/src/main/resources/mapper/PartnerSiteMapper.xml @@ -1,87 +1,87 @@ - - - - - - - - - - - - - - - - - insert into links (l_name, l_is_open, l_url, l_icon_path, l_desc, l_email, l_notification, is_delete) - values (#{name}, #{open}, #{url}, #{iconPath}, #{desc}, #{email}, #{notification}, false) - - - - update links - - l_is_open=#{open}, - l_icon_path=#{iconPath}, - l_desc=#{desc}, - l_url=#{url}, - l_name=#{name}, - l_notification=#{notification}, - l_email=#{email} - - where l_id=#{id} - - - - update links - set is_delete = true - where l_id = #{id} - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + insert into links (l_name, l_is_open, l_url, l_icon_path, l_desc, l_email, l_notification, is_delete) + values (#{name}, #{open}, #{url}, #{iconPath}, #{desc}, #{email}, #{notification}, false) + + + + update links + + l_is_open=#{open}, + l_icon_path=#{iconPath}, + l_desc=#{desc}, + l_url=#{url}, + l_name=#{name}, + l_notification=#{notification}, + l_email=#{email} + + where l_id=#{id} + + + + update links + set is_delete = true + where l_id = #{id} + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/mapper/UserMapper.xml b/blog-common/src/main/resources/mapper/UserMapper.xml similarity index 93% rename from src/main/resources/mapper/UserMapper.xml rename to blog-common/src/main/resources/mapper/UserMapper.xml index 98be7f6..744f95f 100644 --- a/src/main/resources/mapper/UserMapper.xml +++ b/blog-common/src/main/resources/mapper/UserMapper.xml @@ -1,137 +1,137 @@ - - - - - - - - - - - - - - - - - - insert into user(u_email, u_pwd) - values (#{email}, #{pwd}) - - - - update user set - u_desc=#{desc}, - u_display_name=#{displayName} - where u_id=#{id} - - - update user - set u_recently_landed_time=now() - where u_email = #{email} - - - update user - set u_avatar=#{avatarImgUrl} - where u_id = #{id} - - - update user - set u_email_status=#{status} - where u_email = #{email} - - - update user - set u_pwd=#{pwd} - where u_email = #{email} - - - update user - set u_role=#{role} - where u_id = #{id} - - - update user - set u_email = #{email}, - u_pwd = #{pwd}, - u_email_status = #{emailStatus}, - u_desc = #{desc}, - u_display_name = #{displayName}, - u_avatar = #{avatarImgUrl}, - u_role = #{role} - where u_id = #{id} - - - update user - set status= 2 - where u_id = #{id} - - - - update user - set status= 1 - where u_id = #{id} - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + insert into user(u_email, u_pwd) + values (#{email}, #{pwd}) + + + + update user set + u_desc=#{desc}, + u_display_name=#{displayName} + where u_id=#{id} + + + update user + set u_recently_landed_time=now() + where u_email = #{email} + + + update user + set u_avatar=#{avatarImgUrl} + where u_id = #{id} + + + update user + set u_email_status=#{status} + where u_email = #{email} + + + update user + set u_pwd=#{pwd} + where u_email = #{email} + + + update user + set u_role=#{role} + where u_id = #{id} + + + update user + set u_email = #{email}, + u_pwd = #{pwd}, + u_email_status = #{emailStatus}, + u_desc = #{desc}, + u_display_name = #{displayName}, + u_avatar = #{avatarImgUrl}, + u_role = #{role} + where u_id = #{id} + + + update user + set status= 2 + where u_id = #{id} + + + + update user + set status= 1 + where u_id = #{id} + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/resources/mapper/VisitorMapper.xml b/blog-common/src/main/resources/mapper/VisitorMapper.xml similarity index 86% rename from src/main/resources/mapper/VisitorMapper.xml rename to blog-common/src/main/resources/mapper/VisitorMapper.xml index 78c159c..93697a4 100644 --- a/src/main/resources/mapper/VisitorMapper.xml +++ b/blog-common/src/main/resources/mapper/VisitorMapper.xml @@ -1,39 +1,39 @@ - - - - - - - - - - - - - insert into visitor (v_date, v_ip, v_user_agent) - values (#{date}, #{ip}, #{ua}) - - - update visitor - set is_delete = true - where v_id = #{id} - - - - - - - + + + + + + + + + + + + + insert into visitor (v_date, v_ip, v_user_agent) + values (#{date}, #{ip}, #{ua}) + + + update visitor + set is_delete = true + where v_id = #{id} + + + + + + + \ No newline at end of file diff --git a/src/main/resources/mapper/WebUpdateInfoMapper.xml b/blog-common/src/main/resources/mapper/WebUpdateInfoMapper.xml similarity index 82% rename from src/main/resources/mapper/WebUpdateInfoMapper.xml rename to blog-common/src/main/resources/mapper/WebUpdateInfoMapper.xml index eb0094e..5a5b0e8 100644 --- a/src/main/resources/mapper/WebUpdateInfoMapper.xml +++ b/blog-common/src/main/resources/mapper/WebUpdateInfoMapper.xml @@ -1,57 +1,57 @@ - - - - - - - - - - - - insert into web_update(wu_info, wu_time, is_delete) - values (#{updateInfo}, now(), false) - - - - update web_update - set wu_info=#{info} - where wu_id = #{id}; - - - - update web_update - set is_delete = true - where wu_id = #{id} - - - - - - - - - - - - + + + + + + + + + + + + insert into web_update(wu_info, wu_time, is_delete) + values (#{updateInfo}, now(), false) + + + + update web_update + set wu_info=#{info} + where wu_id = #{id}; + + + + update web_update + set is_delete = true + where wu_id = #{id} + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/mapper/articleMapper.xml b/blog-common/src/main/resources/mapper/articleMapper.xml similarity index 90% rename from src/main/resources/mapper/articleMapper.xml rename to blog-common/src/main/resources/mapper/articleMapper.xml index a3803fb..4b5cfee 100644 --- a/src/main/resources/mapper/articleMapper.xml +++ b/blog-common/src/main/resources/mapper/articleMapper.xml @@ -1,7 +1,7 @@ - - + + @@ -16,18 +16,18 @@ - + - + - + @@ -41,25 +41,25 @@ - + - + - + - + insert into article (a_author_id, a_category_id, a_md_content, a_is_original, a_summary, a_title, a_url) values (#{user.id}, #{category.id}, #{mdContent}, #{type}, #{summary}, #{title}, #{url}) @@ -89,7 +89,7 @@ where a_id = #{id} - select * from articleView order by articleId desc diff --git a/src/main/resources/mapper/tagMapper.xml b/blog-common/src/main/resources/mapper/tagMapper.xml similarity index 86% rename from src/main/resources/mapper/tagMapper.xml rename to blog-common/src/main/resources/mapper/tagMapper.xml index 6d82167..4a20f45 100644 --- a/src/main/resources/mapper/tagMapper.xml +++ b/blog-common/src/main/resources/mapper/tagMapper.xml @@ -1,66 +1,66 @@ - - - - - - - - - insert into tag_category (t_name, is_category) - VALUES (#{name}, false); - - - - update tag_category - set t_name=#{name} - where t_id = #{id} - and is_category = false; - - - - update tag_category - set is_delete = true - where t_id = #{id} - and is_category = false; - - - - - - - - - - - - - + + + + + + + + + insert into tag_category (t_name, is_category) + VALUES (#{name}, false); + + + + update tag_category + set t_name=#{name} + where t_id = #{id} + and is_category = false; + + + + update tag_category + set is_delete = true + where t_id = #{id} + and is_category = false; + + + + + + + + + + + + + \ No newline at end of file diff --git a/blog-deploy/pom.xml b/blog-deploy/pom.xml new file mode 100644 index 0000000..681092c --- /dev/null +++ b/blog-deploy/pom.xml @@ -0,0 +1,114 @@ + + + + blog + cn.celess + 0.0.1-SNAPSHOT + + 4.0.0 + + blog-deploy + + jar + + + 13 + 13 + + + + + + junit + junit + 4.13.1 + + + com.h2database + h2 + 1.4.200 + + + com.github.kstyrc + embedded-redis + 0.6 + + + com.google.guava + guava + + + test + + + + + io.springfox + springfox-swagger2 + 2.9.2 + + + com.github.xiaoymin + swagger-bootstrap-ui + 1.9.6 + + + + cn.celess + blog-common + ${blog-common.version} + + + + cn.celess + blog-article + ${blog-article.version} + + + + cn.celess + blog-categorytag + ${blog-categorytag.version} + + + + cn.celess + blog-comment + ${blog-comment.version} + + + + cn.celess + blog-extension + ${blog-extension.version} + + + + cn.celess + blog-partnersite + ${blog-partnersite.version} + + + + cn.celess + blog-siteinfo + ${blog-siteinfo.version} + + + + cn.celess + blog-user + ${blog-user.version} + + + + cn.celess + blog-visitor + ${blog-visitor.version} + + + + + \ No newline at end of file diff --git a/src/main/java/cn/celess/blog/BlogApplication.java b/blog-deploy/src/main/java/cn/celess/BlogApplication.java similarity index 80% rename from src/main/java/cn/celess/blog/BlogApplication.java rename to blog-deploy/src/main/java/cn/celess/BlogApplication.java index f65dc22..1177793 100644 --- a/src/main/java/cn/celess/blog/BlogApplication.java +++ b/blog-deploy/src/main/java/cn/celess/BlogApplication.java @@ -1,20 +1,18 @@ -package cn.celess.blog; - -import org.mybatis.spring.annotation.MapperScan; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.scheduling.annotation.EnableAsync; - -@SpringBootApplication -@EnableAsync -@MapperScan("cn.celess.blog.mapper") -public class BlogApplication { - public static final Logger logger = LoggerFactory.getLogger(BlogApplication.class); - - public static void main(String[] args) { - SpringApplication.run(BlogApplication.class, args); - logger.info("启动完成!"); - } -} +package cn.celess; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.scheduling.annotation.EnableAsync; + +@SpringBootApplication +@EnableAsync +public class BlogApplication { + public static final Logger logger = LoggerFactory.getLogger(BlogApplication.class); + + public static void main(String[] args) { + SpringApplication.run(BlogApplication.class, args); + logger.info("启动完成!"); + } +} diff --git a/src/main/java/cn/celess/blog/configuration/CorsConfig.java b/blog-deploy/src/main/java/cn/celess/configuration/CorsConfig.java similarity index 95% rename from src/main/java/cn/celess/blog/configuration/CorsConfig.java rename to blog-deploy/src/main/java/cn/celess/configuration/CorsConfig.java index d90e4ff..bfe8e2b 100644 --- a/src/main/java/cn/celess/blog/configuration/CorsConfig.java +++ b/blog-deploy/src/main/java/cn/celess/configuration/CorsConfig.java @@ -1,45 +1,45 @@ -package cn.celess.blog.configuration; - -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.cors.CorsConfiguration; -import org.springframework.web.cors.UrlBasedCorsConfigurationSource; -import org.springframework.web.filter.CorsFilter; - -/** - * @author : xiaohai - * @date : 2019/03/30 19:55 - * 跨域 - */ -@Configuration -public class CorsConfig { - @Value("${spring.profiles.active}") - private String activeModel; - - @Bean - public CorsFilter corsFilter() { - UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); - CorsConfiguration config = new CorsConfiguration(); - config.addAllowedOrigin("http://celess.cn"); - config.addAllowedOrigin("http://www.celess.cn"); - config.addAllowedOrigin("https://celess.cn"); - config.addAllowedOrigin("https://www.celess.cn"); - // 本地调试时的跨域 - if (!"prod".equals(activeModel)) { - config.addAllowedOrigin("http://localhost:4200"); - config.addAllowedOrigin("http://127.0.0.1:4200"); - } - config.addAllowedHeader("*"); - config.addAllowedMethod("OPTIONS"); - config.addAllowedMethod("GET"); - config.addAllowedMethod("POST"); - config.addAllowedMethod("PUT"); - config.addAllowedMethod("DELETE"); - config.addExposedHeader("Authorization"); - config.setAllowCredentials(true); - config.setMaxAge(10800L); - source.registerCorsConfiguration("/**", config); - return new CorsFilter(source); - } -} +package cn.celess.configuration; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.cors.CorsConfiguration; +import org.springframework.web.cors.UrlBasedCorsConfigurationSource; +import org.springframework.web.filter.CorsFilter; + +/** + * @author : xiaohai + * @date : 2019/03/30 19:55 + * 跨域 + */ +@Configuration +public class CorsConfig { + @Value("${spring.profiles.active}") + private String activeModel; + + @Bean + public CorsFilter corsFilter() { + UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); + CorsConfiguration config = new CorsConfiguration(); + config.addAllowedOrigin("http://celess.cn"); + config.addAllowedOrigin("http://www.celess.cn"); + config.addAllowedOrigin("https://celess.cn"); + config.addAllowedOrigin("https://www.celess.cn"); + // 本地调试时的跨域 + if (!"prod".equals(activeModel)) { + config.addAllowedOrigin("http://localhost:4200"); + config.addAllowedOrigin("http://127.0.0.1:4200"); + } + config.addAllowedHeader("*"); + config.addAllowedMethod("OPTIONS"); + config.addAllowedMethod("GET"); + config.addAllowedMethod("POST"); + config.addAllowedMethod("PUT"); + config.addAllowedMethod("DELETE"); + config.addExposedHeader("Authorization"); + config.setAllowCredentials(true); + config.setMaxAge(10800L); + source.registerCorsConfiguration("/**", config); + return new CorsFilter(source); + } +} diff --git a/src/main/java/cn/celess/blog/configuration/DruidConfig.java b/blog-deploy/src/main/java/cn/celess/configuration/DruidConfig.java similarity index 93% rename from src/main/java/cn/celess/blog/configuration/DruidConfig.java rename to blog-deploy/src/main/java/cn/celess/configuration/DruidConfig.java index 8bfcacc..8e93bb0 100644 --- a/src/main/java/cn/celess/blog/configuration/DruidConfig.java +++ b/blog-deploy/src/main/java/cn/celess/configuration/DruidConfig.java @@ -1,41 +1,41 @@ -package cn.celess.blog.configuration; - -import com.alibaba.druid.pool.DruidDataSource; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -/** - * @author : xiaohai - * @date : 2019/03/28 14:26 - */ -@Configuration -public class DruidConfig { - @Value("${spring.datasource.url}") - private String dbUrl; - - @Value("${spring.datasource.username}") - private String username; - - @Value("${spring.datasource.password}") - private String password; - - @Value("${spring.datasource.driver-class-name}") - private String driverClassName; - - @Bean - public DruidDataSource druidDataSource() { - DruidDataSource dataSource = new DruidDataSource(); - dataSource.setDriverClassName(driverClassName); - // 数据库基本信息 - dataSource.setUrl(dbUrl); - dataSource.setUsername(username); - dataSource.setPassword(password); - - // 数据库连接池配置 - dataSource.setInitialSize(10); - dataSource.setMinIdle(10); - dataSource.setMaxActive(100); - return dataSource; - } -} +package cn.celess.configuration; + +import com.alibaba.druid.pool.DruidDataSource; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * @author : xiaohai + * @date : 2019/03/28 14:26 + */ +@Configuration +public class DruidConfig { + @Value("${spring.datasource.url}") + private String dbUrl; + + @Value("${spring.datasource.username}") + private String username; + + @Value("${spring.datasource.password}") + private String password; + + @Value("${spring.datasource.driver-class-name}") + private String driverClassName; + + @Bean + public DruidDataSource druidDataSource() { + DruidDataSource dataSource = new DruidDataSource(); + dataSource.setDriverClassName(driverClassName); + // 数据库基本信息 + dataSource.setUrl(dbUrl); + dataSource.setUsername(username); + dataSource.setPassword(password); + + // 数据库连接池配置 + dataSource.setInitialSize(10); + dataSource.setMinIdle(10); + dataSource.setMaxActive(100); + return dataSource; + } +} diff --git a/src/main/java/cn/celess/blog/configuration/InterceptorConfig.java b/blog-deploy/src/main/java/cn/celess/configuration/InterceptorConfig.java similarity index 79% rename from src/main/java/cn/celess/blog/configuration/InterceptorConfig.java rename to blog-deploy/src/main/java/cn/celess/configuration/InterceptorConfig.java index 85419c0..41dc3ce 100644 --- a/src/main/java/cn/celess/blog/configuration/InterceptorConfig.java +++ b/blog-deploy/src/main/java/cn/celess/configuration/InterceptorConfig.java @@ -1,39 +1,39 @@ -package cn.celess.blog.configuration; - -import cn.celess.blog.configuration.filter.AuthenticationFilter; -import cn.celess.blog.configuration.filter.MultipleSubmitFilter; -import cn.celess.blog.configuration.filter.VisitorRecord; -import cn.celess.blog.configuration.listener.SessionListener; -import org.springframework.boot.web.servlet.ServletListenerRegistrationBean; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.config.annotation.InterceptorRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; - -/** - * @Author: 小海 - * @Date: 2019/10/18 14:19 - * @Description: - */ -@Configuration -public class InterceptorConfig implements WebMvcConfigurer { - @Override - public void addInterceptors(InterceptorRegistry registry) { - registry.addInterceptor(new MultipleSubmitFilter()).addPathPatterns("/**"); - registry.addInterceptor(new VisitorRecord()).addPathPatterns("/**"); - registry.addInterceptor(authenticationFilter()).addPathPatterns("/**"); - } - - @Bean - public AuthenticationFilter authenticationFilter() { - return new AuthenticationFilter(); - } - - @Bean - public ServletListenerRegistrationBean servletListenerRegistrationBean() { - // session listener register bean - ServletListenerRegistrationBean slrBean = new ServletListenerRegistrationBean(); - slrBean.setListener(new SessionListener()); - return slrBean; - } -} +package cn.celess.configuration; + +import cn.celess.configuration.filter.AuthenticationFilter; +import cn.celess.configuration.filter.MultipleSubmitFilter; +import cn.celess.configuration.filter.VisitorRecord; +import cn.celess.configuration.listener.SessionListener; +import org.springframework.boot.web.servlet.ServletListenerRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +/** + * @Author: 小海 + * @Date: 2019/10/18 14:19 + * @Description: + */ +@Configuration +public class InterceptorConfig implements WebMvcConfigurer { + @Override + public void addInterceptors(InterceptorRegistry registry) { + registry.addInterceptor(new MultipleSubmitFilter()).addPathPatterns("/**"); + registry.addInterceptor(new VisitorRecord()).addPathPatterns("/**"); + registry.addInterceptor(authenticationFilter()).addPathPatterns("/**"); + } + + @Bean + public AuthenticationFilter authenticationFilter() { + return new AuthenticationFilter(); + } + + @Bean + public ServletListenerRegistrationBean servletListenerRegistrationBean() { + // session listener register bean + ServletListenerRegistrationBean slrBean = new ServletListenerRegistrationBean(); + slrBean.setListener(new SessionListener()); + return slrBean; + } +} diff --git a/src/main/java/cn/celess/blog/configuration/RedisConfig.java b/blog-deploy/src/main/java/cn/celess/configuration/RedisConfig.java similarity index 94% rename from src/main/java/cn/celess/blog/configuration/RedisConfig.java rename to blog-deploy/src/main/java/cn/celess/configuration/RedisConfig.java index cc48849..ba2582c 100644 --- a/src/main/java/cn/celess/blog/configuration/RedisConfig.java +++ b/blog-deploy/src/main/java/cn/celess/configuration/RedisConfig.java @@ -1,69 +1,67 @@ -package cn.celess.blog.configuration; - -import com.fasterxml.jackson.annotation.JsonAutoDetect; -import com.fasterxml.jackson.annotation.PropertyAccessor; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.springframework.cache.annotation.CachingConfigurerSupport; -import org.springframework.cache.annotation.EnableCaching; -import org.springframework.cache.interceptor.KeyGenerator; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.data.redis.connection.RedisConnectionFactory; -import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; - -import java.lang.reflect.Method; - - -/** - * @author : xiaohai - * @date : 2019/05/22 17:35 - */ -@Configuration -@EnableCaching -public class RedisConfig extends CachingConfigurerSupport { - - /** - * 缓存的命名前缀 - * - * @return KeyGenerator - */ - @Override - @Bean - public KeyGenerator keyGenerator() { - return (target, method, params) -> { - StringBuilder sb = new StringBuilder(); - String name = target.getClass().getName(); - sb.append(name.substring(name.lastIndexOf(".") + 1)); - sb.append(":"); - sb.append(method.getName()); - for (Object obj : params) { - sb.append("-").append(obj.toString()); - } - return sb.toString(); - }; - } - - /** - * 配置redisTemplate - * - * @param redisConnectionFactory redisConnectionFactory - * @return redisTemplate - */ - @Bean - public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) { - Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); - ObjectMapper om = new ObjectMapper(); - om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); - om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); - jackson2JsonRedisSerializer.setObjectMapper(om); - RedisTemplate template = new RedisTemplate(); - template.setConnectionFactory(redisConnectionFactory); - template.setKeySerializer(jackson2JsonRedisSerializer); - template.setValueSerializer(jackson2JsonRedisSerializer); - template.setHashKeySerializer(jackson2JsonRedisSerializer); - template.setHashValueSerializer(jackson2JsonRedisSerializer); - template.afterPropertiesSet(); - return template; - } +package cn.celess.configuration; + +import com.fasterxml.jackson.annotation.JsonAutoDetect; +import com.fasterxml.jackson.annotation.PropertyAccessor; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.cache.annotation.CachingConfigurerSupport; +import org.springframework.cache.annotation.EnableCaching; +import org.springframework.cache.interceptor.KeyGenerator; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; + + +/** + * @author : xiaohai + * @date : 2019/05/22 17:35 + */ +@Configuration +@EnableCaching +public class RedisConfig extends CachingConfigurerSupport { + + /** + * 缓存的命名前缀 + * + * @return KeyGenerator + */ + @Override + @Bean + public KeyGenerator keyGenerator() { + return (target, method, params) -> { + StringBuilder sb = new StringBuilder(); + String name = target.getClass().getName(); + sb.append(name.substring(name.lastIndexOf(".") + 1)); + sb.append(":"); + sb.append(method.getName()); + for (Object obj : params) { + sb.append("-").append(obj.toString()); + } + return sb.toString(); + }; + } + + /** + * 配置redisTemplate + * + * @param redisConnectionFactory redisConnectionFactory + * @return redisTemplate + */ + @Bean + public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) { + Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); + ObjectMapper om = new ObjectMapper(); + om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); + om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); + jackson2JsonRedisSerializer.setObjectMapper(om); + RedisTemplate template = new RedisTemplate(); + template.setConnectionFactory(redisConnectionFactory); + template.setKeySerializer(jackson2JsonRedisSerializer); + template.setValueSerializer(jackson2JsonRedisSerializer); + template.setHashKeySerializer(jackson2JsonRedisSerializer); + template.setHashValueSerializer(jackson2JsonRedisSerializer); + template.afterPropertiesSet(); + return template; + } } \ No newline at end of file diff --git a/src/main/java/cn/celess/blog/configuration/SwaggerConfig.java b/blog-deploy/src/main/java/cn/celess/configuration/SwaggerConfig.java similarity index 93% rename from src/main/java/cn/celess/blog/configuration/SwaggerConfig.java rename to blog-deploy/src/main/java/cn/celess/configuration/SwaggerConfig.java index 46c2970..6e1222a 100644 --- a/src/main/java/cn/celess/blog/configuration/SwaggerConfig.java +++ b/blog-deploy/src/main/java/cn/celess/configuration/SwaggerConfig.java @@ -1,46 +1,46 @@ -package cn.celess.blog.configuration; - -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import springfox.documentation.builders.ApiInfoBuilder; -import springfox.documentation.builders.PathSelectors; -import springfox.documentation.builders.RequestHandlerSelectors; -import springfox.documentation.service.ApiInfo; -import springfox.documentation.service.Contact; -import springfox.documentation.spi.DocumentationType; -import springfox.documentation.spring.web.plugins.Docket; -import springfox.documentation.swagger2.annotations.EnableSwagger2; - -/** - * @author : xiaohai - * @date : 2019/03/28 15:55 - */ -@Configuration -@EnableSwagger2 -public class SwaggerConfig { - - @Value("${spring.profiles.active}") - private String environment; - - @Bean - public Docket createRestApi() { - return new Docket(DocumentationType.SWAGGER_2) - .enable(!"prod".equals(environment)) - .apiInfo(apiInfo()) - .select() - .apis(RequestHandlerSelectors.basePackage("cn.celess.blog")) - .paths(PathSelectors.any()) - .build(); - } - - private ApiInfo apiInfo() { - return new ApiInfoBuilder() - .title("小海博客的APi") - .description("小海博客的APi") - .contact(new Contact("小海", "https://www.celess.cn", "a@celess.cn")) - .version("1.0") - .build(); - } - +package cn.celess.configuration; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import springfox.documentation.builders.ApiInfoBuilder; +import springfox.documentation.builders.PathSelectors; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.service.ApiInfo; +import springfox.documentation.service.Contact; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; +import springfox.documentation.swagger2.annotations.EnableSwagger2; + +/** + * @author : xiaohai + * @date : 2019/03/28 15:55 + */ +@Configuration +@EnableSwagger2 +public class SwaggerConfig { + + @Value("${spring.profiles.active}") + private String environment; + + @Bean + public Docket createRestApi() { + return new Docket(DocumentationType.SWAGGER_2) + .enable(!"prod".equals(environment)) + .apiInfo(apiInfo()) + .select() + .apis(RequestHandlerSelectors.basePackage("cn.celess")) + .paths(PathSelectors.any()) + .build(); + } + + private ApiInfo apiInfo() { + return new ApiInfoBuilder() + .title("小海博客的APi") + .description("小海博客的APi") + .contact(new Contact("小海", "https://www.celess.cn", "a@celess.cn")) + .version("1.0") + .build(); + } + } \ No newline at end of file diff --git a/src/main/java/cn/celess/blog/configuration/filter/AuthenticationFilter.java b/blog-deploy/src/main/java/cn/celess/configuration/filter/AuthenticationFilter.java similarity index 88% rename from src/main/java/cn/celess/blog/configuration/filter/AuthenticationFilter.java rename to blog-deploy/src/main/java/cn/celess/configuration/filter/AuthenticationFilter.java index d25f662..eab8c0e 100644 --- a/src/main/java/cn/celess/blog/configuration/filter/AuthenticationFilter.java +++ b/blog-deploy/src/main/java/cn/celess/configuration/filter/AuthenticationFilter.java @@ -1,93 +1,94 @@ -package cn.celess.blog.configuration.filter; - -import cn.celess.blog.enmu.ResponseEnum; -import cn.celess.blog.entity.Response; -import cn.celess.blog.service.UserService; -import cn.celess.blog.util.JwtUtil; -import cn.celess.blog.util.RedisUtil; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.servlet.HandlerInterceptor; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; - -/** - * @Author: 小海 - * @Date: 2019/11/16 11:21 - * @Description: 鉴权拦截器 - */ -public class AuthenticationFilter implements HandlerInterceptor { - private static final Logger logger = LoggerFactory.getLogger(AuthenticationFilter.class); - private static final String USER_PREFIX = "/user"; - private static final String ADMIN_PREFIX = "/admin"; - private static final String ROLE_ADMIN = "admin"; - private static final String ROLE_USER = "user"; - @Autowired - JwtUtil jwtUtil; - @Autowired - RedisUtil redisUtil; - @Autowired - UserService userService; - - @Override - public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { - String path = request.getRequestURI(); - path = path.replaceAll("/+", "/"); - int indexOf = path.indexOf("/", 1); - String rootPath = indexOf == -1 ? path : path.substring(0, indexOf); - String jwtStr = request.getHeader("Authorization"); - if (jwtStr != null && !jwtStr.isEmpty() && !jwtUtil.isTokenExpired(jwtStr)) { - // 已登录 记录当前email - request.getSession().setAttribute("email", jwtUtil.getUsernameFromToken(jwtStr)); - } - // 不需要鉴权的路径 - if (!USER_PREFIX.equals(rootPath.toLowerCase()) && !ADMIN_PREFIX.equals(rootPath.toLowerCase())) { - return true; - } - - if (jwtStr == null || jwtStr.isEmpty()) { - return writeResponse(ResponseEnum.HAVE_NOT_LOG_IN, response, request); - } - if (jwtUtil.isTokenExpired(jwtStr)) { - return writeResponse(ResponseEnum.LOGIN_EXPIRED, response, request); - } - String email = jwtUtil.getUsernameFromToken(jwtStr); - if (jwtUtil.isTokenExpired(jwtStr)) { - // 登陆过期 - return writeResponse(ResponseEnum.LOGIN_EXPIRED, response, request); - } - if (!redisUtil.hasKey(email + "-login")) { - return writeResponse(ResponseEnum.LOGOUT, response, request); - } - String role = userService.getUserRoleByEmail(email); - if (role.equals(ROLE_USER) || role.equals(ROLE_ADMIN)) { - // 更新token - String token = jwtUtil.updateTokenDate(jwtStr); - response.setHeader("Authorization", token); - } - if (role.equals(ROLE_ADMIN)) { - // admin - return true; - } - if (role.equals(ROLE_USER) && !rootPath.equals(ADMIN_PREFIX)) { - // user not admin page - return true; - } - return writeResponse(ResponseEnum.PERMISSION_ERROR, response, request); - } - - private boolean writeResponse(ResponseEnum e, HttpServletResponse response, HttpServletRequest request) { - response.setHeader("Content-Type", "application/json;charset=UTF-8"); - try { - logger.info("鉴权失败,[code:{},msg:{},path:{}]", e.getCode(), e.getMsg(), request.getRequestURI() + "?" + request.getQueryString()); - response.getWriter().println(new ObjectMapper().writeValueAsString(Response.response(e, null))); - } catch (IOException ex) { - ex.printStackTrace(); - } - return false; - } -} +package cn.celess.configuration.filter; + + +import cn.celess.common.enmu.ResponseEnum; +import cn.celess.common.entity.Response; +import cn.celess.common.service.UserService; +import cn.celess.common.util.RedisUtil; +import cn.celess.user.util.JwtUtil; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.servlet.HandlerInterceptor; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +/** + * @Author: 小海 + * @Date: 2019/11/16 11:21 + * @Description: 鉴权拦截器 + */ +public class AuthenticationFilter implements HandlerInterceptor { + private static final Logger logger = LoggerFactory.getLogger(AuthenticationFilter.class); + private static final String USER_PREFIX = "/user"; + private static final String ADMIN_PREFIX = "/admin"; + private static final String ROLE_ADMIN = "admin"; + private static final String ROLE_USER = "user"; + @Autowired + JwtUtil jwtUtil; + @Autowired + RedisUtil redisUtil; + @Autowired + UserService userService; + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + String path = request.getRequestURI(); + path = path.replaceAll("/+", "/"); + int indexOf = path.indexOf("/", 1); + String rootPath = indexOf == -1 ? path : path.substring(0, indexOf); + String jwtStr = request.getHeader("Authorization"); + if (jwtStr != null && !jwtStr.isEmpty() && !jwtUtil.isTokenExpired(jwtStr)) { + // 已登录 记录当前email + request.getSession().setAttribute("email", jwtUtil.getUsernameFromToken(jwtStr)); + } + // 不需要鉴权的路径 + if (!USER_PREFIX.equalsIgnoreCase(rootPath) && !ADMIN_PREFIX.equalsIgnoreCase(rootPath)) { + return true; + } + + if (jwtStr == null || jwtStr.isEmpty()) { + return writeResponse(ResponseEnum.HAVE_NOT_LOG_IN, response, request); + } + if (jwtUtil.isTokenExpired(jwtStr)) { + return writeResponse(ResponseEnum.LOGIN_EXPIRED, response, request); + } + String email = jwtUtil.getUsernameFromToken(jwtStr); + if (jwtUtil.isTokenExpired(jwtStr)) { + // 登陆过期 + return writeResponse(ResponseEnum.LOGIN_EXPIRED, response, request); + } + if (!redisUtil.hasKey(email + "-login")) { + return writeResponse(ResponseEnum.LOGOUT, response, request); + } + String role = userService.getUserRoleByEmail(email); + if (role.equals(ROLE_USER) || role.equals(ROLE_ADMIN)) { + // 更新token + String token = jwtUtil.updateTokenDate(jwtStr); + response.setHeader("Authorization", token); + } + if (role.equals(ROLE_ADMIN)) { + // admin + return true; + } + if (role.equals(ROLE_USER) && !rootPath.equals(ADMIN_PREFIX)) { + // user not admin page + return true; + } + return writeResponse(ResponseEnum.PERMISSION_ERROR, response, request); + } + + private boolean writeResponse(ResponseEnum e, HttpServletResponse response, HttpServletRequest request) { + response.setHeader("Content-Type", "application/json;charset=UTF-8"); + try { + logger.info("鉴权失败,[code:{},msg:{},path:{}]", e.getCode(), e.getMsg(), request.getRequestURI() + "?" + request.getQueryString()); + response.getWriter().println(new ObjectMapper().writeValueAsString(Response.response(e, null))); + } catch (IOException ex) { + ex.printStackTrace(); + } + return false; + } +} diff --git a/src/main/java/cn/celess/blog/configuration/filter/MultipleSubmitFilter.java b/blog-deploy/src/main/java/cn/celess/configuration/filter/MultipleSubmitFilter.java similarity index 86% rename from src/main/java/cn/celess/blog/configuration/filter/MultipleSubmitFilter.java rename to blog-deploy/src/main/java/cn/celess/configuration/filter/MultipleSubmitFilter.java index c0d908d..507d142 100644 --- a/src/main/java/cn/celess/blog/configuration/filter/MultipleSubmitFilter.java +++ b/blog-deploy/src/main/java/cn/celess/configuration/filter/MultipleSubmitFilter.java @@ -1,44 +1,44 @@ -package cn.celess.blog.configuration.filter; - -import cn.celess.blog.enmu.ResponseEnum; -import cn.celess.blog.entity.Response; -import cn.celess.blog.util.RequestUtil; -import org.springframework.web.servlet.HandlerInterceptor; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -/** - * @Author: 小海 - * @Date: 2019/10/18 13:46 - * @Description: 多次请求拦截器 - */ -public class MultipleSubmitFilter implements HandlerInterceptor { - private static final int WAIT_TIME = 200;// 多次提交中间的间隔 - - @Override - public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { - Long lastSubmitTime = (Long) request.getSession().getAttribute("lastSubmitTime"); - String completeUrl = (String) request.getSession().getAttribute("completeUrl&method"); - if (lastSubmitTime == null || completeUrl == null) { - return true; - } - if (System.currentTimeMillis() - lastSubmitTime < WAIT_TIME && RequestUtil.getCompleteUrlAndMethod(request).equals(completeUrl)) { - // 请求参数和路径均相同 且请求时间间隔小于 WAIT_TIME - response.setContentType("application/json"); - response.setCharacterEncoding("UTF-8"); - Response result = new Response(ResponseEnum.FAILURE.getCode(), "重复请求", null); - response.getWriter().println(result.toString()); - return false; - } - return true; - } - - @Override - public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { - HttpSession session = request.getSession(); - session.setAttribute("lastSubmitTime", System.currentTimeMillis()); - session.setAttribute("completeUrl&method", RequestUtil.getCompleteUrlAndMethod(request)); - } -} +package cn.celess.configuration.filter; + +import cn.celess.common.enmu.ResponseEnum; +import cn.celess.common.entity.Response; +import cn.celess.common.util.RequestUtil; +import org.springframework.web.servlet.HandlerInterceptor; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +/** + * @Author: 小海 + * @Date: 2019/10/18 13:46 + * @Description: 多次请求拦截器 + */ +public class MultipleSubmitFilter implements HandlerInterceptor { + private static final int WAIT_TIME = 200;// 多次提交中间的间隔 + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + Long lastSubmitTime = (Long) request.getSession().getAttribute("lastSubmitTime"); + String completeUrl = (String) request.getSession().getAttribute("completeUrl&method"); + if (lastSubmitTime == null || completeUrl == null) { + return true; + } + if (System.currentTimeMillis() - lastSubmitTime < WAIT_TIME && RequestUtil.getCompleteUrlAndMethod(request).equals(completeUrl)) { + // 请求参数和路径均相同 且请求时间间隔小于 WAIT_TIME + response.setContentType("application/json"); + response.setCharacterEncoding("UTF-8"); + Response result = new Response(ResponseEnum.FAILURE.getCode(), "重复请求", null); + response.getWriter().println(result); + return false; + } + return true; + } + + @Override + public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { + HttpSession session = request.getSession(); + session.setAttribute("lastSubmitTime", System.currentTimeMillis()); + session.setAttribute("completeUrl&method", RequestUtil.getCompleteUrlAndMethod(request)); + } +} diff --git a/src/main/java/cn/celess/blog/configuration/filter/VisitorRecord.java b/blog-deploy/src/main/java/cn/celess/configuration/filter/VisitorRecord.java similarity index 90% rename from src/main/java/cn/celess/blog/configuration/filter/VisitorRecord.java rename to blog-deploy/src/main/java/cn/celess/configuration/filter/VisitorRecord.java index fdc465e..8cc1e8c 100644 --- a/src/main/java/cn/celess/blog/configuration/filter/VisitorRecord.java +++ b/blog-deploy/src/main/java/cn/celess/configuration/filter/VisitorRecord.java @@ -1,38 +1,38 @@ -package cn.celess.blog.configuration.filter; - -import cn.celess.blog.util.RequestUtil; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.HandlerInterceptor; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; -import java.util.HashMap; - -/** - * @Author: 小海 - * @Date: 2019/10/18 15:38 - * @Description: 记录访问情况 - */ -@Configuration -public class VisitorRecord implements HandlerInterceptor { - - @SuppressWarnings("unchecked") - @Override - public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { - HttpSession session = request.getSession(); - - HashMap visitDetail = (HashMap) session.getAttribute("visitDetail"); - if (visitDetail == null) { - return true; - } - // 获取访问次数 - Integer count = visitDetail.get(RequestUtil.getCompleteUrlAndMethod(request)); - // 自增 - count = count == null ? 1 : ++count; - // 更新 - visitDetail.put(RequestUtil.getCompleteUrlAndMethod(request), count); - session.setAttribute("ip", request.getRemoteAddr()); - return true; - } -} +package cn.celess.configuration.filter; + +import cn.celess.common.util.RequestUtil; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.HandlerInterceptor; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; +import java.util.HashMap; + +/** + * @Author: 小海 + * @Date: 2019/10/18 15:38 + * @Description: 记录访问情况 + */ +@Configuration +public class VisitorRecord implements HandlerInterceptor { + + @SuppressWarnings("unchecked") + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + HttpSession session = request.getSession(); + + HashMap visitDetail = (HashMap) session.getAttribute("visitDetail"); + if (visitDetail == null) { + return true; + } + // 获取访问次数 + Integer count = visitDetail.get(RequestUtil.getCompleteUrlAndMethod(request)); + // 自增 + count = count == null ? 1 : ++count; + // 更新 + visitDetail.put(RequestUtil.getCompleteUrlAndMethod(request), count); + session.setAttribute("ip", request.getRemoteAddr()); + return true; + } +} diff --git a/src/main/java/cn/celess/blog/configuration/listener/SessionListener.java b/blog-deploy/src/main/java/cn/celess/configuration/listener/SessionListener.java similarity index 92% rename from src/main/java/cn/celess/blog/configuration/listener/SessionListener.java rename to blog-deploy/src/main/java/cn/celess/configuration/listener/SessionListener.java index f56c598..439cc8c 100644 --- a/src/main/java/cn/celess/blog/configuration/listener/SessionListener.java +++ b/blog-deploy/src/main/java/cn/celess/configuration/listener/SessionListener.java @@ -1,49 +1,49 @@ -package cn.celess.blog.configuration.listener; - -import cn.celess.blog.util.RedisUserUtil; -import lombok.extern.log4j.Log4j2; -import org.springframework.beans.factory.annotation.Autowired; - -import javax.servlet.annotation.WebListener; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSessionEvent; -import javax.servlet.http.HttpSessionListener; -import java.util.HashMap; - -/** - * @Author: 小海 - * @Date: 2019/10/18 15:33 - * @Description: 监听session的情况 - */ -@Log4j2 -@WebListener -public class SessionListener implements HttpSessionListener { - @Autowired - RedisUserUtil redisUserUtil; - @Autowired - HttpServletRequest request; - - @Override - public void sessionCreated(HttpSessionEvent se) { - se.getSession().setAttribute("visitDetail", new HashMap()); - // 10s for debug - // se.getSession().setMaxInactiveInterval(10); - // log.info("新增一个Session[{}]", se.getSession().getId()); - } - - @SuppressWarnings("unchecked") - @Override - public void sessionDestroyed(HttpSessionEvent se) { - HashMap visitDetail = (HashMap) se.getSession().getAttribute("visitDetail"); - StringBuilder sb = new StringBuilder(); - sb.append("ip => ").append(se.getSession().getAttribute("ip")); - if (visitDetail.size() == 0) { - return; - } - sb.append("\t登录情况 => "); - String email = (String) se.getSession().getAttribute("email"); - sb.append(email == null ? "游客访问" : email); - visitDetail.forEach((s, integer) -> sb.append("\n").append("Method:[").append(s.split(":")[1]).append("]\tTimes:[").append(integer).append("]\tPath:[").append(s.split(":")[0]).append("]")); - log.info(sb.toString()); - } -} +package cn.celess.configuration.listener; + +import cn.celess.user.util.RedisUserUtil; +import lombok.extern.log4j.Log4j2; +import org.springframework.beans.factory.annotation.Autowired; + +import javax.servlet.annotation.WebListener; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSessionEvent; +import javax.servlet.http.HttpSessionListener; +import java.util.HashMap; + +/** + * @Author: 小海 + * @Date: 2019/10/18 15:33 + * @Description: 监听session的情况 + */ +@Log4j2 +@WebListener +public class SessionListener implements HttpSessionListener { + @Autowired + RedisUserUtil redisUserUtil; + @Autowired + HttpServletRequest request; + + @Override + public void sessionCreated(HttpSessionEvent se) { + se.getSession().setAttribute("visitDetail", new HashMap()); + // 10s for debug + // se.getSession().setMaxInactiveInterval(10); + // log.info("新增一个Session[{}]", se.getSession().getId()); + } + + @SuppressWarnings("unchecked") + @Override + public void sessionDestroyed(HttpSessionEvent se) { + HashMap visitDetail = (HashMap) se.getSession().getAttribute("visitDetail"); + StringBuilder sb = new StringBuilder(); + sb.append("ip => ").append(se.getSession().getAttribute("ip")); + if (visitDetail.size() == 0) { + return; + } + sb.append("\t登录情况 => "); + String email = (String) se.getSession().getAttribute("email"); + sb.append(email == null ? "游客访问" : email); + visitDetail.forEach((s, integer) -> sb.append("\n").append("Method:[").append(s.split(":")[1]).append("]\tTimes:[").append(integer).append("]\tPath:[").append(s.split(":")[0]).append("]")); + log.info(sb.toString()); + } +} diff --git a/src/main/resources/application-openSource.properties b/blog-deploy/src/main/resources/application-openSource.properties similarity index 95% rename from src/main/resources/application-openSource.properties rename to blog-deploy/src/main/resources/application-openSource.properties index 766a8f7..ea38559 100644 --- a/src/main/resources/application-openSource.properties +++ b/blog-deploy/src/main/resources/application-openSource.properties @@ -1,90 +1,90 @@ -server.port=8081 - -# 七牛的密钥配置 -qiniu.accessKey= -qiniu.secretKey= -qiniu.bucket= -# sitemap 存放地址 -sitemap.path= -# 生成JWT时候的密钥 -jwt.secret= - -spring.jpa.show-sql=false -spring.jpa.hibernate.ddl-auto=update -# 上传单个文件的大小 -spring.servlet.multipart.max-file-size=10MB -# 上传文件的总大小 -spring.servlet.multipart.max-request-size=10MB -##null字段不显示 -spring.jackson.default-property-inclusion=non_null - - -################# 数据库 ################## -#请先填写下面的配置 -spring.datasource.type=com.alibaba.druid.pool.DruidDataSource -spring.datasource.url= -spring.datasource.username= -spring.datasource.password= -spring.datasource.driver-class-name=com.mysql.jdbc.Driver -spring.datasource.platform=mysql -# never / always / embedded -spring.datasource.initialization-mode=never -spring.datasource.sql-script-encoding=utf-8 -spring.datasource.schema=classpath:sql/schema.sql -spring.datasource.data=classpath:sql/data.sql - - -################## mybatis ################## -mybatis.mapper-locations=classpath:mapper/*.xml -mybatis.type-aliases-package=cn.celess.blog.entity - - -pagehelper.helper-dialect=mysql -pagehelper.reasonable=true -pagehelper.support-methods-arguments=true -pagehelper.params=count=countSql - - - - -################ email ############## -#请先填写下面的配置,不然可能运行不起来 -spring.mail.host= -spring.mail.username= -spring.mail.password= -spring.mail.properties.mail.smtp.auth=true -spring.mail.properties.mail.smtp.starttls.enable=true -spring.mail.properties.mail.smtp.starttls.required=true -spring.mail.default-encoding=UTF-8 -spring.mail.port=465 -spring.mail.properties.mail.smtp.socketFactory.port=465 -spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory -spring.mail.properties.mail.smtp.socketFactory.fallback=false - - -#### 用于nginx的代理 获取真实ip -server.use-forward-headers = true -server.tomcat.remote-ip-header = X-Real-IP -server.tomcat.protocol-header = X-Forwarded-Proto - - -############### redis ############## -# REDIS (RedisProperties) -# Redis数据库索引(默认为0) -spring.redis.database=0 -# Redis服务器地址 -spring.redis.host= -# Redis服务器连接端口 -spring.redis.port=6379 -# Redis服务器连接密码(默认为空) -spring.redis.password= -# 连接池最大连接数(使用负值表示没有限制) -spring.redis.jedis.pool.max-active=-1 -# 连接池最大阻塞等待时间(使用负值表示没有限制) -spring.redis.jedis.pool.max-wait=-1 -# 连接池中的最大空闲连接 -spring.redis.jedis.pool.max-idle=8 -# 连接池中的最小空闲连接 -spring.redis.jedis.pool.min-idle=0 -# 连接超时时间(毫秒) +server.port=8081 + +# 七牛的密钥配置 +qiniu.accessKey= +qiniu.secretKey= +qiniu.bucket= +# sitemap 存放地址 +sitemap.path= +# 生成JWT时候的密钥 +jwt.secret= + +spring.jpa.show-sql=false +spring.jpa.hibernate.ddl-auto=update +# 上传单个文件的大小 +spring.servlet.multipart.max-file-size=10MB +# 上传文件的总大小 +spring.servlet.multipart.max-request-size=10MB +##null字段不显示 +spring.jackson.default-property-inclusion=non_null + + +################# 数据库 ################## +#请先填写下面的配置 +spring.datasource.type=com.alibaba.druid.pool.DruidDataSource +spring.datasource.url= +spring.datasource.username= +spring.datasource.password= +spring.datasource.driver-class-name=com.mysql.jdbc.Driver +spring.datasource.platform=mysql +# never / always / embedded +spring.datasource.initialization-mode=never +spring.datasource.sql-script-encoding=utf-8 +spring.datasource.schema=classpath:sql/schema.sql +spring.datasource.data=classpath:sql/data.sql + + +################## mybatis ################## +mybatis.mapper-locations=classpath:mapper/*.xml +mybatis.type-aliases-package=cn.celess.common.entity + + +pagehelper.helper-dialect=mysql +pagehelper.reasonable=true +pagehelper.support-methods-arguments=true +pagehelper.params=count=countSql + + + + +################ email ############## +#请先填写下面的配置,不然可能运行不起来 +spring.mail.host= +spring.mail.username= +spring.mail.password= +spring.mail.properties.mail.smtp.auth=true +spring.mail.properties.mail.smtp.starttls.enable=true +spring.mail.properties.mail.smtp.starttls.required=true +spring.mail.default-encoding=UTF-8 +spring.mail.port=465 +spring.mail.properties.mail.smtp.socketFactory.port=465 +spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory +spring.mail.properties.mail.smtp.socketFactory.fallback=false + + +#### 用于nginx的代理 获取真实ip +server.use-forward-headers = true +server.tomcat.remote-ip-header = X-Real-IP +server.tomcat.protocol-header = X-Forwarded-Proto + + +############### redis ############## +# REDIS (RedisProperties) +# Redis数据库索引(默认为0) +spring.redis.database=0 +# Redis服务器地址 +spring.redis.host= +# Redis服务器连接端口 +spring.redis.port=6379 +# Redis服务器连接密码(默认为空) +spring.redis.password= +# 连接池最大连接数(使用负值表示没有限制) +spring.redis.jedis.pool.max-active=-1 +# 连接池最大阻塞等待时间(使用负值表示没有限制) +spring.redis.jedis.pool.max-wait=-1 +# 连接池中的最大空闲连接 +spring.redis.jedis.pool.max-idle=8 +# 连接池中的最小空闲连接 +spring.redis.jedis.pool.min-idle=0 +# 连接超时时间(毫秒) spring.redis.timeout=5000 \ No newline at end of file diff --git a/blog-deploy/src/main/resources/application-prod.properties b/blog-deploy/src/main/resources/application-prod.properties new file mode 100644 index 0000000..d2b7e5d --- /dev/null +++ b/blog-deploy/src/main/resources/application-prod.properties @@ -0,0 +1,68 @@ +server.port=8081 +# 七牛的密钥配置 +qiniu.accessKey=si3O2_Q7edFtjzmyyzXkoE9G1toxcjDfULhX5zdh +qiniu.secretKey=Pnq8q2Iy1Ez8RQXQR33XmgAYlit7M8C197BZ4lCj +qiniu.bucket=xiaohai +# sitemap 存放地址 +sitemap.path= +# 生成JWT时候的密钥 +jwt.secret=sdjfi77;47h7uuo4l;4lgiu4;dl5684aasdasdpsidf;sdf +#mybatis.type-handlers-package=cn.celess.common.mapper.typehandler +spring.jpa.show-sql=false +spring.jpa.hibernate.ddl-auto=update +# 上传单个文件的大小 +spring.servlet.multipart.max-file-size=10MB +# 上传文件的总大小 +spring.servlet.multipart.max-request-size=10MB +spring.jackson.default-property-inclusion=non_null +################# 数据库 ################## +spring.datasource.type=com.alibaba.druid.pool.DruidDataSource +# spring.datasource.url=jdbc:mysql://localhost:3306/blog?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true +spring.datasource.url=jdbc:mysql://localhost:3306/blog?characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true +spring.datasource.username=root +spring.datasource.password=zhenghai +spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver +spring.datasource.initialization-mode=never +################## mybatis ################## +mybatis.mapper-locations=classpath:mapper/*.xml +mybatis.type-aliases-package=cn.celess.common.entity +pagehelper.helper-dialect=mysql +pagehelper.reasonable=true +pagehelper.support-methods-arguments=true +pagehelper.params=count=countSql +#### 用于nginx的代理 获取真实ip +server.use-forward-headers=true +server.tomcat.remote-ip-header=X-Real-IP +server.tomcat.protocol-header=X-Forwarded-Proto +############### email ############## +spring.mail.host=smtp.163.com +spring.mail.username=xiaohai2271@163.com +spring.mail.password=56462271Zh +spring.mail.properties.mail.smtp.auth=true +spring.mail.properties.mail.smtp.starttls.enable=true +spring.mail.properties.mail.smtp.starttls.required=true +spring.mail.default-encoding=UTF-8 +spring.mail.port=465 +spring.mail.properties.mail.smtp.socketFactory.port=465 +spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory +spring.mail.properties.mail.smtp.socketFactory.fallback=false +############### redis ############## +# REDIS (RedisProperties) +# Redis数据库索引(默认为0) +spring.redis.database=0 +# Redis服务器地址 +spring.redis.host=127.0.0.1 +# Redis服务器连接端口 +spring.redis.port=6379 +# Redis服务器连接密码(默认为空) +spring.redis.password=zhenghai +# 连接池最大连接数(使用负值表示没有限制) +spring.redis.jedis.pool.max-active=-1 +# 连接池最大阻塞等待时间(使用负值表示没有限制) +spring.redis.jedis.pool.max-wait=-1 +# 连接池中的最大空闲连接 +spring.redis.jedis.pool.max-idle=8 +# 连接池中的最小空闲连接 +spring.redis.jedis.pool.min-idle=0 +# 连接超时时间(毫秒) +spring.redis.timeout=5000 \ No newline at end of file diff --git a/src/main/resources/application-test.properties b/blog-deploy/src/main/resources/application-test.properties similarity index 94% rename from src/main/resources/application-test.properties rename to blog-deploy/src/main/resources/application-test.properties index 7f8f605..9800929 100644 --- a/src/main/resources/application-test.properties +++ b/blog-deploy/src/main/resources/application-test.properties @@ -8,23 +8,17 @@ qiniu.bucket= sitemap.path= # 生成JWT时候的密钥 jwt.secret=sdaniod213k123123ipoeqowekqwe - ##spring.jpa.show-sql=false ##spring.jpa.hibernate.ddl-auto=update - -mybatis.type-handlers-package=cn.celess.blog.mapper.typehandler -logging.level.cn.celess.blog.mapper=debug +mybatis.type-handlers-package=cn.celess.common.mapper.typehandler +logging.level.cn.celess.common.mapper=debug # 上传单个文件的大小 spring.servlet.multipart.max-file-size=10MB # 上传文件的总大小 spring.servlet.multipart.max-request-size=10MB - spring.jackson.default-property-inclusion=non_null - - ################# 数据库 ################## spring.datasource.type=com.alibaba.druid.pool.DruidDataSource - #h2 spring.datasource.driver-class-name=org.h2.Driver spring.datasource.url=jdbc:h2:mem:testdb;mode=mysql;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false @@ -41,7 +35,7 @@ spring.datasource.data=classpath:sql/data.sql ################## mybatis ################## mybatis.mapper-locations=classpath:mapper/*.xml -mybatis.type-aliases-package=cn.celess.blog.entity +mybatis.type-aliases-package=cn.celess.common.entity pagehelper.helper-dialect=mysql diff --git a/src/main/resources/application.properties b/blog-deploy/src/main/resources/application.properties similarity index 76% rename from src/main/resources/application.properties rename to blog-deploy/src/main/resources/application.properties index e0c3787..18dc243 100644 --- a/src/main/resources/application.properties +++ b/blog-deploy/src/main/resources/application.properties @@ -1,7 +1,8 @@ -spring.profiles.active=prod -####七牛的配置 -####cn.celess.blog.service.serviceimpl.QiniuServiceImpl -logging.level.cn.celess.blog=debug -logging.level.cn.celess.blog.mapper=info - +spring.profiles.active=prod +####七牛的配置 +####cn.celess.blog.service.serviceimpl.QiniuServiceImpl +logging.level.cn.celess.blog=debug +logging.level.cn.celess.common.mapper=info +spring.cache.type=redis + ## 修改openSource 添加-test 文件用于测试 -prod文件用于线上发布 \ No newline at end of file diff --git a/src/main/resources/ip2region/ip2region.db b/blog-deploy/src/main/resources/ip2region/ip2region.db similarity index 100% rename from src/main/resources/ip2region/ip2region.db rename to blog-deploy/src/main/resources/ip2region/ip2region.db diff --git a/src/main/resources/sql/data.sql b/blog-deploy/src/main/resources/sql/data.sql similarity index 98% rename from src/main/resources/sql/data.sql rename to blog-deploy/src/main/resources/sql/data.sql index 1a52c25..9427cb7 100644 --- a/src/main/resources/sql/data.sql +++ b/blog-deploy/src/main/resources/sql/data.sql @@ -60,7 +60,7 @@ VALUES (3, '关于这个博客我有话要说', 'https://www.sinosky.org/linux-sublime-text-fcitx.html', 1, 0, 341, 0, 0, 3, '2019-04-16 15:21:34', NULL, 1, 0), (8, 'shiro前后端分离中的跳转问题', '\n1.问题描述\n\n\n\n因为想实现前后端分离,并且使用shiro进行权限管理但是碰到一个问题就是shiro的重定向问题\n 1.未登录,shiro会自动重定向到 /login\n 2.访问路径无权限,shiro会抛出401 http错误\n\n\n2.解决\n\n\n\n因为我纯粹只想用springBoot写后端api所以就必须kill掉这些问题通过查资料发现在 ......', - '> 1.问题描述\n\n因为想实现前后端分离,并且使用shiro进行权限管理 \n但是碰到一个问题就是shiro的重定向问题\n\n 1.未登录,shiro会自动重定向到 /login\n 2.访问路径无权限,shiro会抛出401 http错误\n\n> 2.解决\n\n因为我纯粹只想用springBoot写后端api所以就必须kill掉这些问题\n通过查资料发现在 ` org.apache.shiro.web.filter.authz.AuthorizationFilter`下有\nonAccessDenied方法,源码:\n```\nprotected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {\n Subject subject = this.getSubject(request, response);\n if (subject.getPrincipal() == null) {\n this.saveRequestAndRedirectToLogin(request, response);\n } else {\n String unauthorizedUrl = this.getUnauthorizedUrl();\n if (StringUtils.hasText(unauthorizedUrl)) {\n WebUtils.issueRedirect(request, response, unauthorizedUrl);\n } else {\n WebUtils.toHttp(response).sendError(401);\n }\n }\n\n return false;\n }\n```\n重写此方法即可解决重定向的问题\n随即\n``` \npublic class RestAuthorizationFilter extends PermissionsAuthorizationFilter {\n\n @Override\n protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {\n response.setContentType("application/Json");\n response.setCharacterEncoding("UTF-8");\n Subject subject = this.getSubject(request, response);\n if (subject.getPrincipal() == null) {\n response.getWriter().print(ResponseUtil.response(CodeAndMsgEnum.DIDNOTLOGIN, null));\n } else {\n String unauthorizedUrl = this.getUnauthorizedUrl();\n if (StringUtils.hasText(unauthorizedUrl)) {\n WebUtils.issueRedirect(request, response, unauthorizedUrl);\n } else {\n response.getWriter().print(ResponseUtil.response(CodeAndMsgEnum.PERMISSION_FAILD, null));\n }\n }\n\n return false;\n }\n}\n\n```\n当无权限/需要登录的的时候返回一个json字符串即可\n> 3.最终效果:(note:需要将对象转json,图中是object.toString效果)\n\n### 未登录:\n!["没有登录"](http://56462271.oss-cn-beijing.aliyuncs.com/web/blogimg/didnotlogin.png)\n\n### 无权限:\n!["无权限"](http://56462271.oss-cn-beijing.aliyuncs.com/web/blogimg/permission.png)\n\n', + '> 1.问题描述\n\n因为想实现前后端分离,并且使用shiro进行权限管理 \n但是碰到一个问题就是shiro的重定向问题\n\n 1.未登录,shiro会自动重定向到 /login\n 2.访问路径无权限,shiro会抛出401 http错误\n\n> 2.解决\n\n因为我纯粹只想用springBoot写后端api所以就必须kill掉这些问题\n通过查资料发现在 ` org.apache.shiro.web.cn.celess.blog.filter.authz.AuthorizationFilter`下有\nonAccessDenied方法,源码:\n```\nprotected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {\n Subject subject = this.getSubject(request, response);\n if (subject.getPrincipal() == null) {\n this.saveRequestAndRedirectToLogin(request, response);\n } else {\n String unauthorizedUrl = this.getUnauthorizedUrl();\n if (StringUtils.hasText(unauthorizedUrl)) {\n WebUtils.issueRedirect(request, response, unauthorizedUrl);\n } else {\n WebUtils.toHttp(response).sendError(401);\n }\n }\n\n return false;\n }\n```\n重写此方法即可解决重定向的问题\n随即\n``` \npublic class RestAuthorizationFilter extends PermissionsAuthorizationFilter {\n\n @Override\n protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {\n response.setContentType("application/Json");\n response.setCharacterEncoding("UTF-8");\n Subject subject = this.getSubject(request, response);\n if (subject.getPrincipal() == null) {\n response.getWriter().print(ResponseUtil.response(CodeAndMsgEnum.DIDNOTLOGIN, null));\n } else {\n String unauthorizedUrl = this.getUnauthorizedUrl();\n if (StringUtils.hasText(unauthorizedUrl)) {\n WebUtils.issueRedirect(request, response, unauthorizedUrl);\n } else {\n response.getWriter().print(ResponseUtil.response(CodeAndMsgEnum.PERMISSION_FAILD, null));\n }\n }\n\n return false;\n }\n}\n\n```\n当无权限/需要登录的的时候返回一个json字符串即可\n> 3.最终效果:(note:需要将对象转json,图中是object.toString效果)\n\n### 未登录:\n!["没有登录"](http://56462271.oss-cn-beijing.aliyuncs.com/web/blogimg/didnotlogin.png)\n\n### 无权限:\n!["无权限"](http://56462271.oss-cn-beijing.aliyuncs.com/web/blogimg/permission.png)\n\n', '', 1, 1, 245, 0, 0, 2, '2019-04-16 15:23:30', NULL, 1, 0), (10, 'Linux下Vim的“假死”', '随手一个Ctrl+S 是个好习惯\n然而....\n然而这个习惯却在我使用Vim的时候坑了我\n由于不是经常发生,也就没在意。每次很麻烦的关掉terminal的窗口,重新再打开terminal。今天发生了好几次,很是郁闷。就想看看究竟是怎么回事,结果发现每次按下Ctrl+S就会出现这个问题。\n后来百度,Google才发现 这货是一个快捷键 对应的是 锁定屏幕\n要解除锁定 只需 Ctrl + Q\n我估计这可能是Vim中我记得最牢的一个快捷键之一吧\n', diff --git a/src/main/resources/sql/schema.sql b/blog-deploy/src/main/resources/sql/schema.sql similarity index 100% rename from src/main/resources/sql/schema.sql rename to blog-deploy/src/main/resources/sql/schema.sql diff --git a/src/main/resources/sql/schema_h2.sql b/blog-deploy/src/main/resources/sql/schema_h2.sql similarity index 100% rename from src/main/resources/sql/schema_h2.sql rename to blog-deploy/src/main/resources/sql/schema_h2.sql diff --git a/src/test/java/cn/celess/blog/BaseTest.java b/blog-deploy/src/test/java/cn/celess/BaseTest.java similarity index 91% rename from src/test/java/cn/celess/blog/BaseTest.java rename to blog-deploy/src/test/java/cn/celess/BaseTest.java index 3a349c3..901b73c 100644 --- a/src/test/java/cn/celess/blog/BaseTest.java +++ b/blog-deploy/src/test/java/cn/celess/BaseTest.java @@ -1,12 +1,11 @@ -package cn.celess.blog; +package cn.celess; - -import cn.celess.blog.entity.Response; -import cn.celess.blog.entity.model.QiniuResponse; -import cn.celess.blog.entity.model.UserModel; -import cn.celess.blog.entity.request.LoginReq; -import cn.celess.blog.service.MailService; -import cn.celess.blog.service.QiniuService; +import cn.celess.common.entity.Response; +import cn.celess.common.entity.dto.LoginReq; +import cn.celess.common.entity.vo.QiniuResponse; +import cn.celess.common.entity.vo.UserModel; +import cn.celess.common.service.MailService; +import cn.celess.common.service.QiniuService; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; @@ -30,6 +29,8 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; @@ -40,11 +41,8 @@ import java.lang.reflect.Field; import java.util.Map; import java.util.UUID; -import static cn.celess.blog.enmu.ResponseEnum.SUCCESS; +import static cn.celess.common.enmu.ResponseEnum.SUCCESS; import static org.junit.Assert.*; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; /** * @Author: 小海 @@ -134,7 +132,7 @@ public class BaseTest { protected String login(LoginReq req) { String str = null; try { - str = getMockData(post("/login"), null, req) + str = getMockData(MockMvcRequestBuilders.post("/login"), null, req) .andReturn().getResponse().getContentAsString(); Response response = mapper.readValue(str, new TypeReference>() { }); @@ -158,8 +156,8 @@ public class BaseTest { assertNotEquals(userLogin(), adminLogin()); try { // 测试getMockData方法 - assertNotNull(getMockData(get("/headerInfo"))); - getMockData((get("/headerInfo"))).andDo(result -> assertNotNull(getResponse(result, OBJECT_TYPE))); + assertNotNull(getMockData(MockMvcRequestBuilders.get("/headerInfo"))); + getMockData((MockMvcRequestBuilders.get("/headerInfo"))).andDo(result -> assertNotNull(getResponse(result, OBJECT_TYPE))); } catch (Exception e) { e.printStackTrace(); } @@ -225,7 +223,7 @@ public class BaseTest { builder.content(mapper.writeValueAsString(content)).contentType(MediaType.APPLICATION_JSON); logger.debug("param::json->{}", mapper.writeValueAsString(content)); } - return mockMvc.perform(builder).andExpect(status().isOk()); + return mockMvc.perform(builder).andExpect(MockMvcResultMatchers.status().isOk()); } diff --git a/src/test/java/cn/celess/blog/RedisServerMock.java b/blog-deploy/src/test/java/cn/celess/RedisServerMock.java similarity index 96% rename from src/test/java/cn/celess/blog/RedisServerMock.java rename to blog-deploy/src/test/java/cn/celess/RedisServerMock.java index 009afa1..75dea4e 100644 --- a/src/test/java/cn/celess/blog/RedisServerMock.java +++ b/blog-deploy/src/test/java/cn/celess/RedisServerMock.java @@ -1,4 +1,4 @@ -package cn.celess.blog; +package cn.celess; import org.springframework.stereotype.Component; import redis.embedded.RedisServer; diff --git a/src/test/java/cn/celess/blog/controller/ArticleControllerTest.java b/blog-deploy/src/test/java/cn/celess/controller/ArticleControllerTest.java similarity index 94% rename from src/test/java/cn/celess/blog/controller/ArticleControllerTest.java rename to blog-deploy/src/test/java/cn/celess/controller/ArticleControllerTest.java index d63d8a7..b3ebc09 100644 --- a/src/test/java/cn/celess/blog/controller/ArticleControllerTest.java +++ b/blog-deploy/src/test/java/cn/celess/controller/ArticleControllerTest.java @@ -1,302 +1,303 @@ -package cn.celess.blog.controller; - -import cn.celess.blog.BaseTest; -import cn.celess.blog.entity.Article; -import cn.celess.blog.entity.Response; -import cn.celess.blog.entity.Tag; -import cn.celess.blog.entity.model.ArticleModel; -import cn.celess.blog.entity.model.PageData; -import cn.celess.blog.entity.request.ArticleReq; -import cn.celess.blog.mapper.ArticleMapper; -import com.fasterxml.jackson.core.type.TypeReference; -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; -import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; - -import java.util.List; - -import static cn.celess.blog.enmu.ResponseEnum.*; -import static org.junit.Assert.*; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; - -public class ArticleControllerTest extends BaseTest { - @Autowired - ArticleMapper articleMapper; - private static final TypeReference ARTICLE_MODEL_TYPE = new TypeReference>() { - }; - private static final TypeReference ARTICLE_MODEL_PAGE_TYPE = new TypeReference>>() { - }; - - @Test - public void create() { - ArticleReq articleReq = new ArticleReq(); - // 应该正常通过 - articleReq.setTitle("test-" + randomStr()); - articleReq.setMdContent("# test title"); - articleReq.setCategory("随笔"); - String[] tagList = {"tag", "category"}; - articleReq.setTags(tagList); - articleReq.setOpen(true); - articleReq.setType(true); - articleReq.setUrl("http://xxxx.com"); - MockHttpServletRequestBuilder post = post("/admin/article/create"); - - try { - getMockData(post, adminLogin(), articleReq).andDo(result -> { - Response response = getResponse(result, ARTICLE_MODEL_TYPE); - assertEquals(SUCCESS.getCode(), response.getCode()); - assertNotNull(response.getResult()); - ArticleModel articleModel = response.getResult(); - assertNotNull(articleModel.getId()); - assertNotNull(articleModel.getTitle()); - assertNotNull(articleModel.getSummary()); - assertNotNull(articleModel.getOriginal()); - assertNotNull(articleModel.getTags()); - assertNotNull(articleModel.getCategory()); - assertNotNull(articleModel.getPublishDateFormat()); - assertNotNull(articleModel.getMdContent()); - assertNotNull(articleModel.getPreArticle()); - assertNull(articleModel.getNextArticle()); - assertNotNull(articleModel.getOpen()); - assertNotNull(articleModel.getReadingNumber()); - assertNotNull(articleModel.getAuthor()); - assertNotNull(articleModel.getUrl()); - }); - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Test - public void delete() { - Article article; - do { - article = articleMapper.getLastestArticle(); - create(); - } while (article.isDeleted()); - assertFalse(article.isDeleted()); - MockHttpServletRequestBuilder delete = MockMvcRequestBuilders.delete("/admin/article/del?articleID=" + article.getId()); - try { - Article finalArticle = article; - getMockData(delete, adminLogin()).andDo(result -> { - Response response = getResponse(result, BOOLEAN_TYPE); - assertEquals(SUCCESS.getCode(), response.getCode()); - // 断言删除成功 - assertTrue(response.getResult()); - assertTrue(articleMapper.isDeletedById(finalArticle.getId())); - }); - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Test - public void update() { - Article article = articleMapper.getLastestArticle(); - ArticleReq articleReq = new ArticleReq(); - articleReq.setId(article.getId()); - articleReq.setUrl("http://www.test.test"); - articleReq.setType(!article.getType()); - articleReq.setCategory("test"); - articleReq.setMdContent("test-" + article.getMdContent()); - articleReq.setOpen(!article.getOpen()); - String tag1 = randomStr(4); - String tag2 = randomStr(4); - String[] tagList = {"test", tag1, tag2}; - articleReq.setTags(tagList); - articleReq.setTitle("test-" + article.getTitle()); - try { - getMockData(put("/admin/article/update"), adminLogin(), articleReq).andDo(result -> { - Response response = getResponse(result, ARTICLE_MODEL_TYPE); - assertEquals(SUCCESS.getCode(), response.getCode()); - ArticleModel a = response.getResult(); - assertEquals(articleReq.getCategory(), a.getCategory()); - assertEquals(articleReq.getUrl(), a.getUrl()); - assertEquals(articleReq.getMdContent(), a.getMdContent()); - assertEquals(articleReq.getTitle(), a.getTitle()); - assertEquals(articleReq.getType(), a.getOriginal()); - // Tag - List asList = a.getTags(); - assertEquals(3, asList.size()); - assertEquals(articleReq.getOpen(), a.getOpen()); - assertEquals(articleReq.getId(), a.getId()); - }); - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Test - public void retrieveOneById() { - try { - long articleID = 3; - getMockData(MockMvcRequestBuilders.get("/article/articleID/" + articleID)); - getMockData(MockMvcRequestBuilders.get("/article/articleID/" + articleID + "?update=true")); - - // 文章不存在 - getMockData(MockMvcRequestBuilders.get("/article/articleID/-1")) - .andDo(result -> assertEquals(ARTICLE_NOT_EXIST.getCode(), getResponse(result, STRING_TYPE).getCode())); - - // 正常情况 - getMockData(MockMvcRequestBuilders.get("/article/articleID/" + articleID + "?update=false")).andDo(result -> { - Response response = getResponse(result, ARTICLE_MODEL_TYPE); - // 断言获取数据成功 - assertEquals(SUCCESS.getCode(), response.getCode()); - assertNotNull(response.getResult()); - - ArticleModel a = response.getResult(); - assertNotNull(a.getTitle()); - assertNotNull(a.getId()); - assertNotNull(a.getSummary()); - assertNotNull(a.getMdContent()); - assertNotNull(a.getUrl()); - assertNotNull(a.getUpdateDateFormat()); - assertTrue(a.getPreArticle() != null || a.getNextArticle() != null); - assertNotNull(a.getReadingNumber()); - assertNotNull(a.getOriginal()); - assertNotNull(a.getPublishDateFormat()); - assertNotNull(a.getCategory()); - assertNotNull(a.getTags()); - assertNotNull(a.getAuthor()); - }); - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Test - public void articles() { - try { - // 测试不带参数访问 - getMockData(MockMvcRequestBuilders.get("/articles")); - getMockData(MockMvcRequestBuilders.get("/articles?page=1&count=5")).andDo(result -> { - Response> response = getResponse(result, ARTICLE_MODEL_PAGE_TYPE); - // 断言获取数据成功 - assertEquals(SUCCESS.getCode(), response.getCode()); - // 结果集非空 - assertNotNull(response.getResult()); - // 判断pageInfo是否包装完全 - PageData pageData = response.getResult(); - assertNotEquals(0, pageData.getTotal()); - assertEquals(1, pageData.getPageNum()); - assertEquals(5, pageData.getPageSize()); - // 内容完整 - for (ArticleModel a : pageData.getList()) { - assertNotNull(a.getTitle()); - assertNotNull(a.getId()); - assertNotNull(a.getSummary()); - assertNotNull(a.getOriginal()); - assertNotNull(a.getPublishDateFormat()); - assertNotNull(a.getCategory()); - assertNotNull(a.getTags()); - assertNotNull(a.getAuthor()); - assertNull(a.getOpen()); - assertNull(a.getMdContent()); - } - }); - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Test - public void adminArticles() { - try { - getMockData(get("/admin/articles?page=1&count=10")).andExpect(result -> - assertEquals(HAVE_NOT_LOG_IN.getCode(), getResponse(result, STRING_TYPE).getCode()) - ); - - // User权限登陆 - getMockData(get("/admin/articles?page=1&count=10"), userLogin()).andDo(result -> - assertEquals(PERMISSION_ERROR.getCode(), getResponse(result, STRING_TYPE).getCode()) - ); - for (int i = 0; i < 2; i++) { - // admin权限登陆 - int finalI = i; - getMockData(get("/admin/articles?page=1&count=10&deleted=" + (i == 1)), adminLogin()).andDo(result -> { - Response> response = getResponse(result, ARTICLE_MODEL_PAGE_TYPE); - assertEquals(SUCCESS.getCode(), response.getCode()); - assertNotNull(response.getResult()); - // 判断pageInfo是否包装完全 - PageData pageData = response.getResult(); - assertNotEquals(0, pageData.getTotal()); - assertEquals(1, pageData.getPageNum()); - assertEquals(10, pageData.getPageSize()); - // 内容完整 - for (ArticleModel a : pageData.getList()) { - assertNotNull(a.getTitle()); - assertNotNull(a.getId()); - assertNotNull(a.getOriginal()); - assertNotNull(a.getPublishDateFormat()); - assertNotNull(a.getOpen()); - assertNotNull(a.getReadingNumber()); - assertNotNull(a.getLikeCount()); - assertNotNull(a.getDislikeCount()); - assertEquals((finalI == 1), a.isDeleted()); - assertNull(a.getMdContent()); - } - }); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Test - public void findByCategory() { - try { - // 分类不存在 - String categoryName = "NoSuchCategory"; - getMockData(MockMvcRequestBuilders.get("/articles/category/" + categoryName + "?page=1&count=10")) - .andDo(result -> assertEquals(CATEGORY_NOT_EXIST.getCode(), getResponse(result, STRING_TYPE).getCode())); - // 正常查询 - categoryName = "linux"; - getMockData(MockMvcRequestBuilders.get("/articles/category/" + categoryName + "?page=1&count=10")) - .andDo(result -> { - Response> response = getResponse(result, ARTICLE_MODEL_PAGE_TYPE); - assertEquals(SUCCESS.getCode(), response.getCode()); - PageData pageData = response.getResult(); - assertNotEquals(0, pageData.getTotal()); - assertEquals(1, pageData.getPageNum()); - assertEquals(10, pageData.getPageSize()); - for (ArticleModel arc : pageData.getList()) { - assertNotEquals(0, arc.getId().longValue()); - assertNotNull(arc.getTitle()); - assertNotNull(arc.getSummary()); - } - }); - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Test - public void findByTag() { - try { - // 分类不存在 - String tagName = "NoSuchTag"; - getMockData(MockMvcRequestBuilders.get("/articles/tag/" + tagName + "?page=1&count=10")) - .andDo(result -> assertEquals(TAG_NOT_EXIST.getCode(), getResponse(result, STRING_TYPE).getCode())); - // 正常查询 - tagName = "linux"; - getMockData(MockMvcRequestBuilders.get("/articles/tag/" + tagName + "?page=1&count=10")) - .andDo(result -> { - Response> response = getResponse(result, ARTICLE_MODEL_PAGE_TYPE); - assertEquals(SUCCESS.getCode(), response.getCode()); - PageData pageData = response.getResult(); - assertNotEquals(0, pageData.getTotal()); - assertEquals(1, pageData.getPageNum()); - assertEquals(10, pageData.getPageSize()); - - for (ArticleModel arc : pageData.getList()) { - assertNotEquals(0, arc.getId().longValue()); - assertNotNull(arc.getTitle()); - assertNotNull(arc.getSummary()); - } - }); - } catch (Exception e) { - e.printStackTrace(); - } - } +package cn.celess.controller; + + +import cn.celess.BaseTest; +import cn.celess.common.entity.Article; +import cn.celess.common.entity.Response; +import cn.celess.common.entity.Tag; +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.mapper.ArticleMapper; +import com.fasterxml.jackson.core.type.TypeReference; +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; + +import java.util.List; + +import static cn.celess.common.enmu.ResponseEnum.*; +import static org.junit.Assert.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; + +public class ArticleControllerTest extends BaseTest { + @Autowired + ArticleMapper articleMapper; + private static final TypeReference ARTICLE_MODEL_TYPE = new TypeReference>() { + }; + private static final TypeReference ARTICLE_MODEL_PAGE_TYPE = new TypeReference>>() { + }; + + @Test + public void create() { + ArticleReq articleReq = new ArticleReq(); + // 应该正常通过 + articleReq.setTitle("test-" + randomStr()); + articleReq.setMdContent("# test title"); + articleReq.setCategory("随笔"); + String[] tagList = {"tag", "category"}; + articleReq.setTags(tagList); + articleReq.setOpen(true); + articleReq.setType(true); + articleReq.setUrl("http://xxxx.com"); + MockHttpServletRequestBuilder post = post("/admin/article/create"); + + try { + getMockData(post, adminLogin(), articleReq).andDo(result -> { + Response response = getResponse(result, ARTICLE_MODEL_TYPE); + assertEquals(SUCCESS.getCode(), response.getCode()); + assertNotNull(response.getResult()); + ArticleModel articleModel = response.getResult(); + assertNotNull(articleModel.getId()); + assertNotNull(articleModel.getTitle()); + assertNotNull(articleModel.getSummary()); + assertNotNull(articleModel.getOriginal()); + assertNotNull(articleModel.getTags()); + assertNotNull(articleModel.getCategory()); + assertNotNull(articleModel.getPublishDateFormat()); + assertNotNull(articleModel.getMdContent()); + assertNotNull(articleModel.getPreArticle()); + assertNull(articleModel.getNextArticle()); + assertNotNull(articleModel.getOpen()); + assertNotNull(articleModel.getReadingNumber()); + assertNotNull(articleModel.getAuthor()); + assertNotNull(articleModel.getUrl()); + }); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Test + public void delete() { + Article article; + do { + article = articleMapper.getLastestArticle(); + create(); + } while (article.isDeleted()); + assertFalse(article.isDeleted()); + MockHttpServletRequestBuilder delete = MockMvcRequestBuilders.delete("/admin/article/del?articleID=" + article.getId()); + try { + Article finalArticle = article; + getMockData(delete, adminLogin()).andDo(result -> { + Response response = getResponse(result, BOOLEAN_TYPE); + assertEquals(SUCCESS.getCode(), response.getCode()); + // 断言删除成功 + assertTrue(response.getResult()); + assertTrue(articleMapper.isDeletedById(finalArticle.getId())); + }); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Test + public void update() { + Article article = articleMapper.getLastestArticle(); + ArticleReq articleReq = new ArticleReq(); + articleReq.setId(article.getId()); + articleReq.setUrl("http://www.test.test"); + articleReq.setType(!article.getType()); + articleReq.setCategory("test"); + articleReq.setMdContent("test-" + article.getMdContent()); + articleReq.setOpen(!article.getOpen()); + String tag1 = randomStr(4); + String tag2 = randomStr(4); + String[] tagList = {"test", tag1, tag2}; + articleReq.setTags(tagList); + articleReq.setTitle("test-" + article.getTitle()); + try { + getMockData(put("/admin/article/update"), adminLogin(), articleReq).andDo(result -> { + Response response = getResponse(result, ARTICLE_MODEL_TYPE); + assertEquals(SUCCESS.getCode(), response.getCode()); + ArticleModel a = response.getResult(); + assertEquals(articleReq.getCategory(), a.getCategory()); + assertEquals(articleReq.getUrl(), a.getUrl()); + assertEquals(articleReq.getMdContent(), a.getMdContent()); + assertEquals(articleReq.getTitle(), a.getTitle()); + assertEquals(articleReq.getType(), a.getOriginal()); + // Tag + List asList = a.getTags(); + assertEquals(3, asList.size()); + assertEquals(articleReq.getOpen(), a.getOpen()); + assertEquals(articleReq.getId(), a.getId()); + }); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Test + public void retrieveOneById() { + try { + long articleID = 3; + getMockData(MockMvcRequestBuilders.get("/article/articleID/" + articleID)); + getMockData(MockMvcRequestBuilders.get("/article/articleID/" + articleID + "?update=true")); + + // 文章不存在 + getMockData(MockMvcRequestBuilders.get("/article/articleID/-1")) + .andDo(result -> assertEquals(ARTICLE_NOT_EXIST.getCode(), getResponse(result, STRING_TYPE).getCode())); + + // 正常情况 + getMockData(MockMvcRequestBuilders.get("/article/articleID/" + articleID + "?update=false")).andDo(result -> { + Response response = getResponse(result, ARTICLE_MODEL_TYPE); + // 断言获取数据成功 + assertEquals(SUCCESS.getCode(), response.getCode()); + assertNotNull(response.getResult()); + + ArticleModel a = response.getResult(); + assertNotNull(a.getTitle()); + assertNotNull(a.getId()); + assertNotNull(a.getSummary()); + assertNotNull(a.getMdContent()); + assertNotNull(a.getUrl()); + assertNotNull(a.getUpdateDateFormat()); + assertTrue(a.getPreArticle() != null || a.getNextArticle() != null); + assertNotNull(a.getReadingNumber()); + assertNotNull(a.getOriginal()); + assertNotNull(a.getPublishDateFormat()); + assertNotNull(a.getCategory()); + assertNotNull(a.getTags()); + assertNotNull(a.getAuthor()); + }); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Test + public void articles() { + try { + // 测试不带参数访问 + getMockData(MockMvcRequestBuilders.get("/articles")); + getMockData(MockMvcRequestBuilders.get("/articles?page=1&count=5")).andDo(result -> { + Response> response = getResponse(result, ARTICLE_MODEL_PAGE_TYPE); + // 断言获取数据成功 + assertEquals(SUCCESS.getCode(), response.getCode()); + // 结果集非空 + assertNotNull(response.getResult()); + // 判断pageInfo是否包装完全 + PageData pageData = response.getResult(); + assertNotEquals(0, pageData.getTotal()); + assertEquals(1, pageData.getPageNum()); + assertEquals(5, pageData.getPageSize()); + // 内容完整 + for (ArticleModel a : pageData.getList()) { + assertNotNull(a.getTitle()); + assertNotNull(a.getId()); + assertNotNull(a.getSummary()); + assertNotNull(a.getOriginal()); + assertNotNull(a.getPublishDateFormat()); + assertNotNull(a.getCategory()); + assertNotNull(a.getTags()); + assertNotNull(a.getAuthor()); + assertNull(a.getOpen()); + assertNull(a.getMdContent()); + } + }); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Test + public void adminArticles() { + try { + getMockData(get("/admin/articles?page=1&count=10")).andExpect(result -> + assertEquals(HAVE_NOT_LOG_IN.getCode(), getResponse(result, STRING_TYPE).getCode()) + ); + + // User权限登陆 + getMockData(get("/admin/articles?page=1&count=10"), userLogin()).andDo(result -> + assertEquals(PERMISSION_ERROR.getCode(), getResponse(result, STRING_TYPE).getCode()) + ); + for (int i = 0; i < 2; i++) { + // admin权限登陆 + int finalI = i; + getMockData(get("/admin/articles?page=1&count=10&deleted=" + (i == 1)), adminLogin()).andDo(result -> { + Response> response = getResponse(result, ARTICLE_MODEL_PAGE_TYPE); + assertEquals(SUCCESS.getCode(), response.getCode()); + assertNotNull(response.getResult()); + // 判断pageInfo是否包装完全 + PageData pageData = response.getResult(); + assertNotEquals(0, pageData.getTotal()); + assertEquals(1, pageData.getPageNum()); + assertEquals(10, pageData.getPageSize()); + // 内容完整 + for (ArticleModel a : pageData.getList()) { + assertNotNull(a.getTitle()); + assertNotNull(a.getId()); + assertNotNull(a.getOriginal()); + assertNotNull(a.getPublishDateFormat()); + assertNotNull(a.getOpen()); + assertNotNull(a.getReadingNumber()); + assertNotNull(a.getLikeCount()); + assertNotNull(a.getDislikeCount()); + assertEquals((finalI == 1), a.isDeleted()); + assertNull(a.getMdContent()); + } + }); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Test + public void findByCategory() { + try { + // 分类不存在 + String categoryName = "NoSuchCategory"; + getMockData(MockMvcRequestBuilders.get("/articles/category/" + categoryName + "?page=1&count=10")) + .andDo(result -> assertEquals(CATEGORY_NOT_EXIST.getCode(), getResponse(result, STRING_TYPE).getCode())); + // 正常查询 + categoryName = "linux"; + getMockData(MockMvcRequestBuilders.get("/articles/category/" + categoryName + "?page=1&count=10")) + .andDo(result -> { + Response> response = getResponse(result, ARTICLE_MODEL_PAGE_TYPE); + assertEquals(SUCCESS.getCode(), response.getCode()); + PageData pageData = response.getResult(); + assertNotEquals(0, pageData.getTotal()); + assertEquals(1, pageData.getPageNum()); + assertEquals(10, pageData.getPageSize()); + for (ArticleModel arc : pageData.getList()) { + assertNotEquals(0, arc.getId().longValue()); + assertNotNull(arc.getTitle()); + assertNotNull(arc.getSummary()); + } + }); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Test + public void findByTag() { + try { + // 分类不存在 + String tagName = "NoSuchTag"; + getMockData(MockMvcRequestBuilders.get("/articles/tag/" + tagName + "?page=1&count=10")) + .andDo(result -> assertEquals(TAG_NOT_EXIST.getCode(), getResponse(result, STRING_TYPE).getCode())); + // 正常查询 + tagName = "linux"; + getMockData(MockMvcRequestBuilders.get("/articles/tag/" + tagName + "?page=1&count=10")) + .andDo(result -> { + Response> response = getResponse(result, ARTICLE_MODEL_PAGE_TYPE); + assertEquals(SUCCESS.getCode(), response.getCode()); + PageData pageData = response.getResult(); + assertNotEquals(0, pageData.getTotal()); + assertEquals(1, pageData.getPageNum()); + assertEquals(10, pageData.getPageSize()); + + for (ArticleModel arc : pageData.getList()) { + assertNotEquals(0, arc.getId().longValue()); + assertNotNull(arc.getTitle()); + assertNotNull(arc.getSummary()); + } + }); + } catch (Exception e) { + e.printStackTrace(); + } + } } \ No newline at end of file diff --git a/src/test/java/cn/celess/blog/controller/CategoryControllerTest.java b/blog-deploy/src/test/java/cn/celess/controller/CategoryControllerTest.java similarity index 87% rename from src/test/java/cn/celess/blog/controller/CategoryControllerTest.java rename to blog-deploy/src/test/java/cn/celess/controller/CategoryControllerTest.java index 286f367..391009c 100644 --- a/src/test/java/cn/celess/blog/controller/CategoryControllerTest.java +++ b/blog-deploy/src/test/java/cn/celess/controller/CategoryControllerTest.java @@ -1,78 +1,78 @@ -package cn.celess.blog.controller; - -import cn.celess.blog.BaseTest; -import cn.celess.blog.entity.Category; -import cn.celess.blog.entity.Response; -import cn.celess.blog.entity.model.CategoryModel; -import cn.celess.blog.entity.model.PageData; -import cn.celess.blog.mapper.CategoryMapper; -import com.fasterxml.jackson.core.type.TypeReference; -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; - -import static cn.celess.blog.enmu.ResponseEnum.SUCCESS; -import static org.junit.Assert.*; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; - -public class CategoryControllerTest extends BaseTest { - - @Autowired - CategoryMapper categoryMapper; - private static final TypeReference CATEGORY_MODEL_TYPE = new TypeReference>() { - }; - private static final TypeReference CATEGORY_MODEL_PAGE_TYPE = new TypeReference>>() { - }; - - @Test - public void addOne() throws Exception { - String categoryName = randomStr(4); - getMockData(post("/admin/category/create?name=" + categoryName), adminLogin()).andDo(result -> { - Response response = getResponse(result, CATEGORY_MODEL_TYPE); - assertEquals(SUCCESS.getCode(), response.getCode()); - CategoryModel category = response.getResult(); - assertEquals(categoryName, category.getName()); - assertNotNull(category.getId()); - assertNull(category.getArticles()); - }); - } - - @Test - public void deleteOne() throws Exception { - Category category = categoryMapper.getLastestCategory(); - getMockData(delete("/admin/category/del?id=" + category.getId()), adminLogin()).andDo(result -> { - Response response = getResponse(result, BOOLEAN_TYPE); - assertEquals(SUCCESS.getCode(), response.getCode()); - assertTrue(response.getResult()); - }); - } - - @Test - public void updateOne() throws Exception { - Category category = categoryMapper.getLastestCategory(); - String name = randomStr(4); - getMockData(put("/admin/category/update?id=" + category.getId() + "&name=" + name), adminLogin()).andDo(result -> { - // Response response = mapper.readValue(result.getResponse().getContentAsString(), new ResponseType>()); - Response response = getResponse(result, CATEGORY_MODEL_TYPE); - assertEquals(SUCCESS.getCode(), response.getCode()); - CategoryModel c = response.getResult(); - assertEquals(name, c.getName()); - assertNull(c.getArticles()); - assertNotNull(c.getId()); - }); - } - - @Test - public void getPage() throws Exception { - getMockData(get("/categories")).andDo(result -> { - Response> response = getResponse(result, CATEGORY_MODEL_PAGE_TYPE); - assertEquals(SUCCESS.getCode(), response.getCode()); - assertNotNull(response.getResult()); - response.getResult().getList().forEach(c -> { - assertNotNull(c.getName()); - assertNotNull(c.getId()); - assertNotNull(c.getArticles()); - }); - }); - - } +package cn.celess.controller; + +import cn.celess.BaseTest; +import cn.celess.common.entity.Category; +import cn.celess.common.entity.Response; +import cn.celess.common.entity.vo.CategoryModel; +import cn.celess.common.entity.vo.PageData; +import cn.celess.common.mapper.CategoryMapper; +import com.fasterxml.jackson.core.type.TypeReference; +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; + +import static cn.celess.common.enmu.ResponseEnum.SUCCESS; +import static org.junit.Assert.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; + +public class CategoryControllerTest extends BaseTest { + + @Autowired + CategoryMapper categoryMapper; + private static final TypeReference CATEGORY_MODEL_TYPE = new TypeReference>() { + }; + private static final TypeReference CATEGORY_MODEL_PAGE_TYPE = new TypeReference>>() { + }; + + @Test + public void addOne() throws Exception { + String categoryName = randomStr(4); + getMockData(post("/admin/category/create?name=" + categoryName), adminLogin()).andDo(result -> { + Response response = getResponse(result, CATEGORY_MODEL_TYPE); + assertEquals(SUCCESS.getCode(), response.getCode()); + CategoryModel category = response.getResult(); + assertEquals(categoryName, category.getName()); + assertNotNull(category.getId()); + assertNull(category.getArticles()); + }); + } + + @Test + public void deleteOne() throws Exception { + Category category = categoryMapper.getLastestCategory(); + getMockData(delete("/admin/category/del?id=" + category.getId()), adminLogin()).andDo(result -> { + Response response = getResponse(result, BOOLEAN_TYPE); + assertEquals(SUCCESS.getCode(), response.getCode()); + assertTrue(response.getResult()); + }); + } + + @Test + public void updateOne() throws Exception { + Category category = categoryMapper.getLastestCategory(); + String name = randomStr(4); + getMockData(put("/admin/category/update?id=" + category.getId() + "&name=" + name), adminLogin()).andDo(result -> { + // Response response = mapper.readValue(result.getResponse().getContentAsString(), new ResponseType>()); + Response response = getResponse(result, CATEGORY_MODEL_TYPE); + assertEquals(SUCCESS.getCode(), response.getCode()); + CategoryModel c = response.getResult(); + assertEquals(name, c.getName()); + assertNull(c.getArticles()); + assertNotNull(c.getId()); + }); + } + + @Test + public void getPage() throws Exception { + getMockData(get("/categories")).andDo(result -> { + Response> response = getResponse(result, CATEGORY_MODEL_PAGE_TYPE); + assertEquals(SUCCESS.getCode(), response.getCode()); + assertNotNull(response.getResult()); + response.getResult().getList().forEach(c -> { + assertNotNull(c.getName()); + assertNotNull(c.getId()); + assertNotNull(c.getArticles()); + }); + }); + + } } \ No newline at end of file diff --git a/src/test/java/cn/celess/blog/controller/CommentControllerTest.java b/blog-deploy/src/test/java/cn/celess/controller/CommentControllerTest.java similarity index 88% rename from src/test/java/cn/celess/blog/controller/CommentControllerTest.java rename to blog-deploy/src/test/java/cn/celess/controller/CommentControllerTest.java index dcafc2c..8591f69 100644 --- a/src/test/java/cn/celess/blog/controller/CommentControllerTest.java +++ b/blog-deploy/src/test/java/cn/celess/controller/CommentControllerTest.java @@ -1,134 +1,134 @@ -package cn.celess.blog.controller; - -import cn.celess.blog.BaseTest; -import cn.celess.blog.entity.Article; -import cn.celess.blog.entity.Comment; -import cn.celess.blog.entity.Response; -import cn.celess.blog.entity.User; -import cn.celess.blog.entity.model.CommentModel; -import cn.celess.blog.entity.request.CommentReq; -import cn.celess.blog.mapper.ArticleMapper; -import cn.celess.blog.mapper.CommentMapper; -import cn.celess.blog.mapper.UserMapper; -import com.fasterxml.jackson.core.type.TypeReference; -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; - -import java.util.List; - -import static cn.celess.blog.enmu.ResponseEnum.DATA_IS_DELETED; -import static cn.celess.blog.enmu.ResponseEnum.SUCCESS; -import static org.junit.Assert.*; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; - -public class CommentControllerTest extends BaseTest { - @Autowired - ArticleMapper articleMapper; - @Autowired - UserMapper userMapper; - @Autowired - CommentMapper commentMapper; - private static final TypeReference COMMENT_MODEL_TYPE = new TypeReference>() { - }; - - @Test - public void addOne() throws Exception { - Article article = articleMapper.getLastestArticle(); - CommentReq commentReq = new CommentReq(); - commentReq.setPagePath("/article/" + article.getId()); - commentReq.setContent(randomStr()); - List all = userMapper.findAll(); - commentReq.setPid(1L); - commentReq.setToUserId(2l); - getMockData(post("/user/comment/create"), userLogin(), commentReq).andDo(result -> { - Response response = getResponse(result, COMMENT_MODEL_TYPE); - assertEquals(SUCCESS.getCode(), response.getCode()); - CommentModel model = response.getResult(); - assertNotEquals(0, model.getId()); - assertEquals(commentReq.getPid(), model.getPid().longValue()); - assertEquals(1, model.getPid().longValue()); - assertEquals(commentReq.getContent(), model.getContent()); - assertNotNull(model.getDate()); - assertNotNull(model.getFromUser()); - assertNotNull(model.getToUser()); - }); - - - commentReq.setPagePath("/article/" + article.getId()); - commentReq.setContent(randomStr()); - commentReq.setPid(-1L); - commentReq.setToUserId(2); - getMockData(post("/user/comment/create"), userLogin(), commentReq).andDo(result -> { - Response response = getResponse(result, COMMENT_MODEL_TYPE); - assertEquals(SUCCESS.getCode(), response.getCode()); - CommentModel model = response.getResult(); - // 响应数据的完整性 - assertNotEquals(0, model.getId()); - assertEquals(commentReq.getPid(), model.getPid().longValue()); - assertEquals(-1, model.getPid().longValue()); - assertEquals(commentReq.getContent(), model.getContent()); - assertEquals(commentReq.getPagePath(), "/article/" + article.getId()); - assertNotNull(model.getDate()); - assertNotNull(model.getFromUser()); - assertNotNull(model.getToUser()); - }); - - // 测试二级回复 - Comment latestComment = commentMapper.getLastestComment(); - commentReq.setPagePath("/article/" + article.getId()); - commentReq.setContent(randomStr()); - commentReq.setPid(latestComment.getId()); - getMockData(post("/user/comment/create"), userLogin(), commentReq).andDo(result -> { - Response response = getResponse(result, COMMENT_MODEL_TYPE); - assertEquals(SUCCESS.getCode(), response.getCode()); - CommentModel model = response.getResult(); - // 重新获取父评论信息 - Comment pCommon = commentMapper.findCommentById(latestComment.getId()); - assertEquals(pCommon.getId(), model.getPid()); - }); - } - - @Test - public void deleteTest() throws Exception { - // 准备数据 - User from = userMapper.findByEmail("zh56462271@qq.com"); - assertNotNull(from); - User to = userMapper.findByEmail("a@celess.cn"); - assertNotNull(to); - - Comment comment = new Comment(); - comment.setContent(randomStr(8)); - comment.setFromUser(from); - comment.setToUser(to); - comment.setPagePath("/tags"); - comment.setPid(-1L); - commentMapper.insert(comment); - comment = commentMapper.findCommentById(comment.getId()); - // 接口测试 - long id = comment.getId(); - assertNotEquals(0, id); - getMockData(delete("/user/comment/del?id=" + id), userLogin()).andDo(result -> { - Response response = getResponse(result, BOOLEAN_TYPE); - assertEquals(SUCCESS.getCode(), response.getCode()); - assertTrue(response.getResult()); - }); - getMockData(delete("/user/comment/del?id=" + id), userLogin()) - .andDo(result -> assertEquals(DATA_IS_DELETED.getCode(), getResponse(result, COMMENT_MODEL_TYPE).getCode())); - } - - @Test - public void update() throws Exception { - Comment comment = commentMapper.getLastestComment(); - CommentReq commentReq = new CommentReq(); - commentReq.setId(comment.getId()); - commentReq.setContent(randomStr()); - // 不合法数据 setResponseId - getMockData(put("/user/comment/update"), userLogin(), commentReq).andDo(result -> { - Response response = getResponse(result, COMMENT_MODEL_TYPE); - assertEquals(SUCCESS.getCode(), response.getCode()); - CommentModel c = response.getResult(); - assertEquals(commentReq.getContent(), c.getContent()); - }); - } - +package cn.celess.controller; + +import cn.celess.BaseTest; +import cn.celess.common.entity.Article; +import cn.celess.common.entity.Comment; +import cn.celess.common.entity.Response; +import cn.celess.common.entity.User; +import cn.celess.common.entity.dto.CommentReq; +import cn.celess.common.entity.vo.CommentModel; +import cn.celess.common.mapper.ArticleMapper; +import cn.celess.common.mapper.CommentMapper; +import cn.celess.common.mapper.UserMapper; +import com.fasterxml.jackson.core.type.TypeReference; +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; + +import java.util.List; + +import static cn.celess.common.enmu.ResponseEnum.DATA_IS_DELETED; +import static cn.celess.common.enmu.ResponseEnum.SUCCESS; +import static org.junit.Assert.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; + +public class CommentControllerTest extends BaseTest { + @Autowired + ArticleMapper articleMapper; + @Autowired + UserMapper userMapper; + @Autowired + CommentMapper commentMapper; + private static final TypeReference COMMENT_MODEL_TYPE = new TypeReference>() { + }; + + @Test + public void addOne() throws Exception { + Article article = articleMapper.getLastestArticle(); + CommentReq commentReq = new CommentReq(); + commentReq.setPagePath("/article/" + article.getId()); + commentReq.setContent(randomStr()); + List all = userMapper.findAll(); + commentReq.setPid(1L); + commentReq.setToUserId(2l); + getMockData(post("/user/comment/create"), userLogin(), commentReq).andDo(result -> { + Response response = getResponse(result, COMMENT_MODEL_TYPE); + assertEquals(SUCCESS.getCode(), response.getCode()); + CommentModel model = response.getResult(); + assertNotEquals(0, model.getId()); + assertEquals(commentReq.getPid(), model.getPid().longValue()); + assertEquals(1, model.getPid().longValue()); + assertEquals(commentReq.getContent(), model.getContent()); + assertNotNull(model.getDate()); + assertNotNull(model.getFromUser()); + assertNotNull(model.getToUser()); + }); + + + commentReq.setPagePath("/article/" + article.getId()); + commentReq.setContent(randomStr()); + commentReq.setPid(-1L); + commentReq.setToUserId(2); + getMockData(post("/user/comment/create"), userLogin(), commentReq).andDo(result -> { + Response response = getResponse(result, COMMENT_MODEL_TYPE); + assertEquals(SUCCESS.getCode(), response.getCode()); + CommentModel model = response.getResult(); + // 响应数据的完整性 + assertNotEquals(0, model.getId()); + assertEquals(commentReq.getPid(), model.getPid().longValue()); + assertEquals(-1, model.getPid().longValue()); + assertEquals(commentReq.getContent(), model.getContent()); + assertEquals(commentReq.getPagePath(), "/article/" + article.getId()); + assertNotNull(model.getDate()); + assertNotNull(model.getFromUser()); + assertNotNull(model.getToUser()); + }); + + // 测试二级回复 + Comment latestComment = commentMapper.getLastestComment(); + commentReq.setPagePath("/article/" + article.getId()); + commentReq.setContent(randomStr()); + commentReq.setPid(latestComment.getId()); + getMockData(post("/user/comment/create"), userLogin(), commentReq).andDo(result -> { + Response response = getResponse(result, COMMENT_MODEL_TYPE); + assertEquals(SUCCESS.getCode(), response.getCode()); + CommentModel model = response.getResult(); + // 重新获取父评论信息 + Comment pCommon = commentMapper.findCommentById(latestComment.getId()); + assertEquals(pCommon.getId(), model.getPid()); + }); + } + + @Test + public void deleteTest() throws Exception { + // 准备数据 + User from = userMapper.findByEmail("zh56462271@qq.com"); + assertNotNull(from); + User to = userMapper.findByEmail("a@celess.cn"); + assertNotNull(to); + + Comment comment = new Comment(); + comment.setContent(randomStr(8)); + comment.setFromUser(from); + comment.setToUser(to); + comment.setPagePath("/tags"); + comment.setPid(-1L); + commentMapper.insert(comment); + comment = commentMapper.findCommentById(comment.getId()); + // 接口测试 + long id = comment.getId(); + assertNotEquals(0, id); + getMockData(delete("/user/comment/del?id=" + id), userLogin()).andDo(result -> { + Response response = getResponse(result, BOOLEAN_TYPE); + assertEquals(SUCCESS.getCode(), response.getCode()); + assertTrue(response.getResult()); + }); + getMockData(delete("/user/comment/del?id=" + id), userLogin()) + .andDo(result -> assertEquals(DATA_IS_DELETED.getCode(), getResponse(result, COMMENT_MODEL_TYPE).getCode())); + } + + @Test + public void update() throws Exception { + Comment comment = commentMapper.getLastestComment(); + CommentReq commentReq = new CommentReq(); + commentReq.setId(comment.getId()); + commentReq.setContent(randomStr()); + // 不合法数据 setResponseId + getMockData(put("/user/comment/update"), userLogin(), commentReq).andDo(result -> { + Response response = getResponse(result, COMMENT_MODEL_TYPE); + assertEquals(SUCCESS.getCode(), response.getCode()); + CommentModel c = response.getResult(); + assertEquals(commentReq.getContent(), c.getContent()); + }); + } + } \ No newline at end of file diff --git a/src/test/java/cn/celess/blog/controller/LinksControllerTest.java b/blog-deploy/src/test/java/cn/celess/controller/LinksControllerTest.java similarity index 94% rename from src/test/java/cn/celess/blog/controller/LinksControllerTest.java rename to blog-deploy/src/test/java/cn/celess/controller/LinksControllerTest.java index 646ef85..c37304e 100644 --- a/src/test/java/cn/celess/blog/controller/LinksControllerTest.java +++ b/blog-deploy/src/test/java/cn/celess/controller/LinksControllerTest.java @@ -1,14 +1,15 @@ -package cn.celess.blog.controller; +package cn.celess.controller; -import cn.celess.blog.BaseTest; -import cn.celess.blog.entity.PartnerSite; -import cn.celess.blog.entity.Response; -import cn.celess.blog.entity.model.PageData; -import cn.celess.blog.entity.request.LinkApplyReq; -import cn.celess.blog.entity.request.LinkReq; -import cn.celess.blog.exception.MyException; -import cn.celess.blog.mapper.PartnerMapper; -import cn.celess.blog.service.PartnerSiteService; + +import cn.celess.BaseTest; +import cn.celess.common.entity.PartnerSite; +import cn.celess.common.entity.Response; +import cn.celess.common.entity.dto.LinkApplyReq; +import cn.celess.common.entity.dto.LinkReq; +import cn.celess.common.entity.vo.PageData; +import cn.celess.common.exception.MyException; +import cn.celess.common.mapper.PartnerMapper; +import cn.celess.common.service.PartnerSiteService; import com.fasterxml.jackson.core.type.TypeReference; import lombok.extern.slf4j.Slf4j; import org.junit.Test; @@ -16,7 +17,7 @@ import org.springframework.beans.factory.annotation.Autowired; import java.util.List; -import static cn.celess.blog.enmu.ResponseEnum.*; +import static cn.celess.common.enmu.ResponseEnum.*; import static org.junit.Assert.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; diff --git a/src/test/java/cn/celess/blog/controller/TagControllerTest.java b/blog-deploy/src/test/java/cn/celess/controller/TagControllerTest.java similarity index 90% rename from src/test/java/cn/celess/blog/controller/TagControllerTest.java rename to blog-deploy/src/test/java/cn/celess/controller/TagControllerTest.java index dd3811f..0e4b2ed 100644 --- a/src/test/java/cn/celess/blog/controller/TagControllerTest.java +++ b/blog-deploy/src/test/java/cn/celess/controller/TagControllerTest.java @@ -1,110 +1,111 @@ -package cn.celess.blog.controller; - -import cn.celess.blog.BaseTest; -import cn.celess.blog.entity.Response; -import cn.celess.blog.entity.Tag; -import cn.celess.blog.entity.model.PageData; -import cn.celess.blog.entity.model.TagModel; -import cn.celess.blog.mapper.TagMapper; -import com.fasterxml.jackson.core.type.TypeReference; -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; - -import java.util.List; -import java.util.Map; - -import static cn.celess.blog.enmu.ResponseEnum.*; -import static org.junit.Assert.*; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; - -public class TagControllerTest extends BaseTest { - @Autowired - TagMapper tagMapper; - private static final TypeReference TAG_MODEL_TYPE = new TypeReference>() { - - }; - private static final TypeReference TAG_MODEL_PAGE_TYPE = new TypeReference>>() { - }; - private static final TypeReference TAG_NAC_LIST_TYPE = new TypeReference>>>() { - }; - - @Test - public void addOne() throws Exception { - String name = randomStr(4); - getMockData(post("/admin/tag/create?name=" + name)).andDo(result -> assertEquals(HAVE_NOT_LOG_IN.getCode(), getResponse(result, STRING_TYPE).getCode())); - getMockData(post("/admin/tag/create?name=" + name), userLogin()).andDo(result -> assertEquals(PERMISSION_ERROR.getCode(), getResponse(result, STRING_TYPE).getCode())); - getMockData(post("/admin/tag/create?name=" + name), adminLogin()).andDo(result -> { - Response response = getResponse(result, TAG_MODEL_TYPE); - assertEquals(SUCCESS.getCode(), response.getCode()); - TagModel tag = response.getResult(); - assertNotNull(tag.getId()); - assertEquals(name, tag.getName()); - }); - - - } - - @Test - public void delOne() throws Exception { - Tag lastestTag = tagMapper.getLastestTag(); - assertNotNull(lastestTag.getId()); - getMockData(delete("/admin/tag/del?id=" + lastestTag.getId()), adminLogin()).andDo(result -> { - Response response = getResponse(result, BOOLEAN_TYPE); - assertEquals(SUCCESS.getCode(), response.getCode()); - assertTrue(response.getResult()); - }); - long id = lastestTag.getId() * 2; - getMockData(delete("/admin/tag/del?id=" + id), adminLogin()) - .andDo(result -> assertEquals(TAG_NOT_EXIST.getCode(), getResponse(result, STRING_TYPE).getCode())); - - } - - @Test - public void updateOne() throws Exception { - Tag tag = tagMapper.getLastestTag(); - assertNotNull(tag.getId()); - String name = randomStr(4); - getMockData(put("/admin/tag/update?id=" + tag.getId() + "&name=" + name), adminLogin()).andDo(result -> { - Response response = getResponse(result, TAG_MODEL_TYPE); - assertEquals(SUCCESS.getCode(), response.getCode()); - assertNotNull(response.getResult()); - TagModel t = response.getResult(); - assertEquals(name, t.getName()); - assertEquals(tag.getId(), t.getId()); - }); - - } - - @Test - public void getPage() throws Exception { - getMockData(get("/tags?page=1&count=5")).andDo(result -> { - Response> response = getResponse(result, TAG_MODEL_PAGE_TYPE); - assertEquals(SUCCESS.getCode(), response.getCode()); - // 结果集非空 - assertNotNull(response.getResult()); - // 判断pageInfo是否包装完全 - PageData pageData = response.getResult(); - assertNotEquals(0, pageData.getTotal()); - assertEquals(1, pageData.getPageNum()); - assertEquals(5, pageData.getPageSize()); - // 内容完整 - for (TagModel t : pageData.getList()) { - assertNotNull(t.getId()); - assertNotNull(t.getName()); - } - }); - } - - @Test - public void getTagNameAndCount() throws Exception { - getMockData(get("/tags/nac")).andDo(result -> { - Response>> response = getResponse(result, TAG_NAC_LIST_TYPE); - assertEquals(SUCCESS.getCode(), response.getCode()); - assertNotNull(response.getResult()); - response.getResult().forEach(o -> { - assertNotNull(o.get("name")); - assertNotNull(o.get("size")); - }); - }); - } +package cn.celess.controller; + + +import cn.celess.BaseTest; +import cn.celess.common.entity.Response; +import cn.celess.common.entity.Tag; +import cn.celess.common.entity.vo.PageData; +import cn.celess.common.entity.vo.TagModel; +import cn.celess.common.mapper.TagMapper; +import com.fasterxml.jackson.core.type.TypeReference; +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; + +import java.util.List; +import java.util.Map; + +import static cn.celess.common.enmu.ResponseEnum.*; +import static org.junit.Assert.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; + +public class TagControllerTest extends BaseTest { + @Autowired + TagMapper tagMapper; + private static final TypeReference TAG_MODEL_TYPE = new TypeReference>() { + + }; + private static final TypeReference TAG_MODEL_PAGE_TYPE = new TypeReference>>() { + }; + private static final TypeReference TAG_NAC_LIST_TYPE = new TypeReference>>>() { + }; + + @Test + public void addOne() throws Exception { + String name = randomStr(4); + getMockData(post("/admin/tag/create?name=" + name)).andDo(result -> assertEquals(HAVE_NOT_LOG_IN.getCode(), getResponse(result, STRING_TYPE).getCode())); + getMockData(post("/admin/tag/create?name=" + name), userLogin()).andDo(result -> assertEquals(PERMISSION_ERROR.getCode(), getResponse(result, STRING_TYPE).getCode())); + getMockData(post("/admin/tag/create?name=" + name), adminLogin()).andDo(result -> { + Response response = getResponse(result, TAG_MODEL_TYPE); + assertEquals(SUCCESS.getCode(), response.getCode()); + TagModel tag = response.getResult(); + assertNotNull(tag.getId()); + assertEquals(name, tag.getName()); + }); + + + } + + @Test + public void delOne() throws Exception { + Tag lastestTag = tagMapper.getLastestTag(); + assertNotNull(lastestTag.getId()); + getMockData(delete("/admin/tag/del?id=" + lastestTag.getId()), adminLogin()).andDo(result -> { + Response response = getResponse(result, BOOLEAN_TYPE); + assertEquals(SUCCESS.getCode(), response.getCode()); + assertTrue(response.getResult()); + }); + long id = lastestTag.getId() * 2; + getMockData(delete("/admin/tag/del?id=" + id), adminLogin()) + .andDo(result -> assertEquals(TAG_NOT_EXIST.getCode(), getResponse(result, STRING_TYPE).getCode())); + + } + + @Test + public void updateOne() throws Exception { + Tag tag = tagMapper.getLastestTag(); + assertNotNull(tag.getId()); + String name = randomStr(4); + getMockData(put("/admin/tag/update?id=" + tag.getId() + "&name=" + name), adminLogin()).andDo(result -> { + Response response = getResponse(result, TAG_MODEL_TYPE); + assertEquals(SUCCESS.getCode(), response.getCode()); + assertNotNull(response.getResult()); + TagModel t = response.getResult(); + assertEquals(name, t.getName()); + assertEquals(tag.getId(), t.getId()); + }); + + } + + @Test + public void getPage() throws Exception { + getMockData(get("/tags?page=1&count=5")).andDo(result -> { + Response> response = getResponse(result, TAG_MODEL_PAGE_TYPE); + assertEquals(SUCCESS.getCode(), response.getCode()); + // 结果集非空 + assertNotNull(response.getResult()); + // 判断pageInfo是否包装完全 + PageData pageData = response.getResult(); + assertNotEquals(0, pageData.getTotal()); + assertEquals(1, pageData.getPageNum()); + assertEquals(5, pageData.getPageSize()); + // 内容完整 + for (TagModel t : pageData.getList()) { + assertNotNull(t.getId()); + assertNotNull(t.getName()); + } + }); + } + + @Test + public void getTagNameAndCount() throws Exception { + getMockData(get("/tags/nac")).andDo(result -> { + Response>> response = getResponse(result, TAG_NAC_LIST_TYPE); + assertEquals(SUCCESS.getCode(), response.getCode()); + assertNotNull(response.getResult()); + response.getResult().forEach(o -> { + assertNotNull(o.get("name")); + assertNotNull(o.get("size")); + }); + }); + } } \ No newline at end of file diff --git a/src/test/java/cn/celess/blog/controller/UserControllerTest.java b/blog-deploy/src/test/java/cn/celess/controller/UserControllerTest.java similarity index 95% rename from src/test/java/cn/celess/blog/controller/UserControllerTest.java rename to blog-deploy/src/test/java/cn/celess/controller/UserControllerTest.java index a6bc88b..0abaf16 100644 --- a/src/test/java/cn/celess/blog/controller/UserControllerTest.java +++ b/blog-deploy/src/test/java/cn/celess/controller/UserControllerTest.java @@ -1,16 +1,16 @@ -package cn.celess.blog.controller; +package cn.celess.controller; -import cn.celess.blog.BaseTest; -import cn.celess.blog.entity.Response; -import cn.celess.blog.entity.User; -import cn.celess.blog.entity.model.PageData; -import cn.celess.blog.entity.model.UserModel; -import cn.celess.blog.entity.request.LoginReq; -import cn.celess.blog.entity.request.UserReq; -import cn.celess.blog.mapper.UserMapper; -import cn.celess.blog.service.UserService; -import cn.celess.blog.util.MD5Util; -import cn.celess.blog.util.RedisUtil; +import cn.celess.BaseTest; +import cn.celess.common.entity.Response; +import cn.celess.common.entity.User; +import cn.celess.common.entity.dto.LoginReq; +import cn.celess.common.entity.dto.UserReq; +import cn.celess.common.entity.vo.PageData; +import cn.celess.common.entity.vo.UserModel; +import cn.celess.common.mapper.UserMapper; +import cn.celess.common.service.UserService; +import cn.celess.common.util.MD5Util; +import cn.celess.common.util.RedisUtil; import com.fasterxml.jackson.core.type.TypeReference; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -30,7 +30,7 @@ import java.util.Random; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; -import static cn.celess.blog.enmu.ResponseEnum.*; +import static cn.celess.common.enmu.ResponseEnum.*; import static org.junit.Assert.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; diff --git a/src/test/java/cn/celess/blog/controller/VisitorControllerTest.java b/blog-deploy/src/test/java/cn/celess/controller/VisitorControllerTest.java similarity index 89% rename from src/test/java/cn/celess/blog/controller/VisitorControllerTest.java rename to blog-deploy/src/test/java/cn/celess/controller/VisitorControllerTest.java index 10b5da8..0994739 100644 --- a/src/test/java/cn/celess/blog/controller/VisitorControllerTest.java +++ b/blog-deploy/src/test/java/cn/celess/controller/VisitorControllerTest.java @@ -1,85 +1,85 @@ -package cn.celess.blog.controller; - -import cn.celess.blog.BaseTest; -import cn.celess.blog.entity.Response; -import cn.celess.blog.entity.model.PageData; -import cn.celess.blog.entity.model.VisitorModel; -import com.fasterxml.jackson.core.type.TypeReference; -import org.junit.Test; - -import static cn.celess.blog.enmu.ResponseEnum.SUCCESS; -import static org.junit.Assert.*; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; - -public class VisitorControllerTest extends BaseTest { - private final TypeReference VISITOR_PAGE_TYPE = new TypeReference>>() { - }; - private final TypeReference VISITOR_TYPE = new TypeReference>() { - }; - - @Test - public void getVisitorCount() throws Exception { - getMockData(get("/visitor/count")).andDo(result -> { - Response response = getResponse(result); - assertEquals(SUCCESS.getCode(), response.getCode()); - assertNotNull(response.getResult()); - }); - } - - @Test - public void page() throws Exception { - int count = 10; - int page = 1; - // 默认显示location - getMockData(get("/admin/visitor/page?count=" + count + "&page=" + page), adminLogin()).andDo(result -> { - Response> response = getResponse(result, VISITOR_PAGE_TYPE); - assertEquals(SUCCESS.getCode(), response.getCode()); - PageData pageData = response.getResult(); - assertNotEquals(0, pageData.getTotal()); - assertEquals(1, pageData.getPageNum()); - assertEquals(10, pageData.getPageSize()); - for (VisitorModel v : pageData.getList()) { - assertNotEquals(0, v.getId()); - assertNotNull(v.getDate()); - assertNotNull(v.getLocation()); - } - }); - } - - @Test - public void add() throws Exception { - getMockData(post("/visit")).andDo(result -> { - Response response = getResponse(result, VISITOR_TYPE); - assertEquals(SUCCESS.getCode(), response.getCode()); - VisitorModel visitorModel = response.getResult(); - assertNotEquals(0, visitorModel.getId()); - assertNotNull(visitorModel.getIp()); - }); - } - - @Test - public void dayVisitCount() throws Exception { - getMockData(get("/dayVisitCount")).andDo(result -> assertEquals(SUCCESS.getCode(), getResponse(result).getCode())); - } - - // 手动测试 - // @Test - public void ipLocation() throws Exception { - String ip = "127.0.0.1"; - getMockData(get("/ip/" + ip)).andDo(result -> { - Response response = getResponse(result); - assertEquals(SUCCESS.getCode(), response.getCode()); - assertNotNull(response.getResult()); - }); - } - - @Test - public void getIp() throws Exception { - getMockData(get("/ip")).andDo(result -> { - Response response = getResponse(result, STRING_TYPE); - assertEquals(SUCCESS.getCode(), response.getCode()); - assertEquals("127.0.0.1", response.getResult()); - }); - } +package cn.celess.controller; + +import cn.celess.BaseTest; +import cn.celess.common.entity.Response; +import cn.celess.common.entity.vo.PageData; +import cn.celess.common.entity.vo.VisitorModel; +import com.fasterxml.jackson.core.type.TypeReference; +import org.junit.Test; + +import static cn.celess.common.enmu.ResponseEnum.SUCCESS; +import static org.junit.Assert.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; + +public class VisitorControllerTest extends BaseTest { + private final TypeReference VISITOR_PAGE_TYPE = new TypeReference>>() { + }; + private final TypeReference VISITOR_TYPE = new TypeReference>() { + }; + + @Test + public void getVisitorCount() throws Exception { + getMockData(get("/visitor/count")).andDo(result -> { + Response response = getResponse(result); + assertEquals(SUCCESS.getCode(), response.getCode()); + assertNotNull(response.getResult()); + }); + } + + @Test + public void page() throws Exception { + int count = 10; + int page = 1; + // 默认显示location + getMockData(get("/admin/visitor/page?count=" + count + "&page=" + page), adminLogin()).andDo(result -> { + Response> response = getResponse(result, VISITOR_PAGE_TYPE); + assertEquals(SUCCESS.getCode(), response.getCode()); + PageData pageData = response.getResult(); + assertNotEquals(0, pageData.getTotal()); + assertEquals(1, pageData.getPageNum()); + assertEquals(10, pageData.getPageSize()); + for (VisitorModel v : pageData.getList()) { + assertNotEquals(0, v.getId()); + assertNotNull(v.getDate()); + assertNotNull(v.getLocation()); + } + }); + } + + @Test + public void add() throws Exception { + getMockData(post("/visit")).andDo(result -> { + Response response = getResponse(result, VISITOR_TYPE); + assertEquals(SUCCESS.getCode(), response.getCode()); + VisitorModel visitorModel = response.getResult(); + assertNotEquals(0, visitorModel.getId()); + assertNotNull(visitorModel.getIp()); + }); + } + + @Test + public void dayVisitCount() throws Exception { + getMockData(get("/dayVisitCount")).andDo(result -> assertEquals(SUCCESS.getCode(), getResponse(result).getCode())); + } + + // 手动测试 + // @Test + public void ipLocation() throws Exception { + String ip = "127.0.0.1"; + getMockData(get("/ip/" + ip)).andDo(result -> { + Response response = getResponse(result); + assertEquals(SUCCESS.getCode(), response.getCode()); + assertNotNull(response.getResult()); + }); + } + + @Test + public void getIp() throws Exception { + getMockData(get("/ip")).andDo(result -> { + Response response = getResponse(result, STRING_TYPE); + assertEquals(SUCCESS.getCode(), response.getCode()); + assertEquals("127.0.0.1", response.getResult()); + }); + } } \ No newline at end of file diff --git a/src/test/java/cn/celess/blog/controller/WebUpdateInfoControllerTest.java b/blog-deploy/src/test/java/cn/celess/controller/WebUpdateInfoControllerTest.java similarity index 90% rename from src/test/java/cn/celess/blog/controller/WebUpdateInfoControllerTest.java rename to blog-deploy/src/test/java/cn/celess/controller/WebUpdateInfoControllerTest.java index 648a41a..ca5d99d 100644 --- a/src/test/java/cn/celess/blog/controller/WebUpdateInfoControllerTest.java +++ b/blog-deploy/src/test/java/cn/celess/controller/WebUpdateInfoControllerTest.java @@ -1,132 +1,132 @@ -package cn.celess.blog.controller; - -import cn.celess.blog.BaseTest; -import cn.celess.blog.entity.Response; -import cn.celess.blog.entity.WebUpdate; -import cn.celess.blog.entity.model.PageData; -import cn.celess.blog.entity.model.WebUpdateModel; -import cn.celess.blog.mapper.WebUpdateInfoMapper; -import com.fasterxml.jackson.core.type.TypeReference; -import lombok.extern.slf4j.Slf4j; -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; - -import java.util.Date; -import java.util.List; - -import static cn.celess.blog.enmu.ResponseEnum.DATA_NOT_EXIST; -import static cn.celess.blog.enmu.ResponseEnum.SUCCESS; -import static org.junit.Assert.*; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; - -@Slf4j -public class WebUpdateInfoControllerTest extends BaseTest { - - private final TypeReference MODAL_TYPE = new TypeReference>() { - }; - private final TypeReference MODAL_LIST_TYPE = new TypeReference>>() { - }; - private final TypeReference MODAL_PAGE_TYPE = new TypeReference>>() { - }; - - - @Autowired - WebUpdateInfoMapper mapper; - - @Test - public void create() throws Exception { - String info = randomStr(); - getMockData(post("/admin/webUpdate/create?info=" + info), adminLogin()).andDo(result -> { - Response response = getResponse(result, MODAL_TYPE); - assertEquals(SUCCESS.getCode(), response.getCode()); - assertNotNull(response.getResult()); - WebUpdateModel webUpdateModel = response.getResult(); - assertEquals(info, webUpdateModel.getInfo()); - assertNotNull(webUpdateModel.getTime()); - assertNotEquals(0, webUpdateModel.getId()); - }); - } - - @Test - public void del() throws Exception { - // 新增数据 - WebUpdate webUpdate = new WebUpdate(); - webUpdate.setUpdateInfo(randomStr()); - webUpdate.setUpdateTime(new Date()); - mapper.insert(webUpdate); - // 接口测试 - List updateList = mapper.findAll(); - WebUpdate update = updateList.get(updateList.size() - 1); - assertNotEquals(0, update.getId()); - - long id = update.getId(); - getMockData(delete("/admin/webUpdate/del/" + id), adminLogin()).andDo(result -> { - Response response = getResponse(result); - assertEquals(SUCCESS.getCode(), response.getCode()); - assertNotNull(response.getResult()); - }); - do { - id += 2; - } while (mapper.existsById(id)); - log.debug("准备删除ID={}的不存在记录", id); - getMockData(delete("/admin/webUpdate/del/" + id), adminLogin()).andDo(result -> assertEquals(DATA_NOT_EXIST.getCode(), getResponse(result).getCode())); - } - - @Test - public void update() throws Exception { - // 新增数据 - WebUpdate webUpdate = new WebUpdate(); - webUpdate.setUpdateInfo(randomStr()); - webUpdate.setUpdateTime(new Date()); - mapper.insert(webUpdate); - List all = mapper.findAll(); - WebUpdate update = all.get(all.size() - 1); - assertNotEquals(0, update.getId()); - assertNotNull(update.getUpdateInfo()); - String info = randomStr(); - getMockData(put("/admin/webUpdate/update?id=" + update.getId() + "&info=" + info), adminLogin()).andDo(result -> { - List list = mapper.findAll(); - WebUpdate up = list.get(list.size() - 1); - assertEquals(update.getId(), up.getId()); - assertEquals(update.getUpdateTime(), up.getUpdateTime()); - assertEquals(info, up.getUpdateInfo()); - }); - } - - @Test - public void findAll() throws Exception { - getMockData(get("/webUpdate")).andDo(result -> { - Response> response = getResponse(result, MODAL_LIST_TYPE); - assertEquals(SUCCESS.getCode(), response.getCode()); - assertNotNull(response.getResult()); - assertNotEquals(0, response.getResult()); - response.getResult().forEach(webUpdate -> { - assertNotEquals(0, webUpdate.getId()); - assertNotNull(webUpdate.getTime()); - assertNotNull(webUpdate.getInfo()); - }); - }); - } - - @Test - public void page() throws Exception { - getMockData(get("/webUpdate/pages?page=1&count=10")).andDo(result -> { - Response> response = getResponse(result, MODAL_PAGE_TYPE); - assertEquals(SUCCESS.getCode(), response.getCode()); - assertNotNull(response.getResult()); - PageData pageData = response.getResult(); - assertEquals(1, pageData.getPageNum()); - assertEquals(10, pageData.getPageSize()); - for (WebUpdateModel model : pageData.getList()) { - assertNotEquals(0, model.getId()); - assertNotNull(model.getTime()); - assertNotNull(model.getInfo()); - } - }); - } - - @Test - public void lastestUpdateTime() throws Exception { - getMockData(get("/lastestUpdate")).andDo(result -> assertEquals(SUCCESS.getCode(), getResponse(result).getCode())); - } +package cn.celess.controller; + +import cn.celess.BaseTest; +import cn.celess.common.entity.Response; +import cn.celess.common.entity.WebUpdate; +import cn.celess.common.entity.vo.PageData; +import cn.celess.common.entity.vo.WebUpdateModel; +import cn.celess.common.mapper.WebUpdateInfoMapper; +import com.fasterxml.jackson.core.type.TypeReference; +import lombok.extern.slf4j.Slf4j; +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; + +import java.util.Date; +import java.util.List; + +import static cn.celess.common.enmu.ResponseEnum.DATA_NOT_EXIST; +import static cn.celess.common.enmu.ResponseEnum.SUCCESS; +import static org.junit.Assert.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; + +@Slf4j +public class WebUpdateInfoControllerTest extends BaseTest { + + private final TypeReference MODAL_TYPE = new TypeReference>() { + }; + private final TypeReference MODAL_LIST_TYPE = new TypeReference>>() { + }; + private final TypeReference MODAL_PAGE_TYPE = new TypeReference>>() { + }; + + + @Autowired + WebUpdateInfoMapper mapper; + + @Test + public void create() throws Exception { + String info = randomStr(); + getMockData(post("/admin/webUpdate/create?info=" + info), adminLogin()).andDo(result -> { + Response response = getResponse(result, MODAL_TYPE); + assertEquals(SUCCESS.getCode(), response.getCode()); + assertNotNull(response.getResult()); + WebUpdateModel webUpdateModel = response.getResult(); + assertEquals(info, webUpdateModel.getInfo()); + assertNotNull(webUpdateModel.getTime()); + assertNotEquals(0, webUpdateModel.getId()); + }); + } + + @Test + public void del() throws Exception { + // 新增数据 + WebUpdate webUpdate = new WebUpdate(); + webUpdate.setUpdateInfo(randomStr()); + webUpdate.setUpdateTime(new Date()); + mapper.insert(webUpdate); + // 接口测试 + List updateList = mapper.findAll(); + WebUpdate update = updateList.get(updateList.size() - 1); + assertNotEquals(0, update.getId()); + + long id = update.getId(); + getMockData(delete("/admin/webUpdate/del/" + id), adminLogin()).andDo(result -> { + Response response = getResponse(result); + assertEquals(SUCCESS.getCode(), response.getCode()); + assertNotNull(response.getResult()); + }); + do { + id += 2; + } while (mapper.existsById(id)); + log.debug("准备删除ID={}的不存在记录", id); + getMockData(delete("/admin/webUpdate/del/" + id), adminLogin()).andDo(result -> assertEquals(DATA_NOT_EXIST.getCode(), getResponse(result).getCode())); + } + + @Test + public void update() throws Exception { + // 新增数据 + WebUpdate webUpdate = new WebUpdate(); + webUpdate.setUpdateInfo(randomStr()); + webUpdate.setUpdateTime(new Date()); + mapper.insert(webUpdate); + List all = mapper.findAll(); + WebUpdate update = all.get(all.size() - 1); + assertNotEquals(0, update.getId()); + assertNotNull(update.getUpdateInfo()); + String info = randomStr(); + getMockData(put("/admin/webUpdate/update?id=" + update.getId() + "&info=" + info), adminLogin()).andDo(result -> { + List list = mapper.findAll(); + WebUpdate up = list.get(list.size() - 1); + assertEquals(update.getId(), up.getId()); + assertEquals(update.getUpdateTime(), up.getUpdateTime()); + assertEquals(info, up.getUpdateInfo()); + }); + } + + @Test + public void findAll() throws Exception { + getMockData(get("/webUpdate")).andDo(result -> { + Response> response = getResponse(result, MODAL_LIST_TYPE); + assertEquals(SUCCESS.getCode(), response.getCode()); + assertNotNull(response.getResult()); + assertNotEquals(0, response.getResult()); + response.getResult().forEach(webUpdate -> { + assertNotEquals(0, webUpdate.getId()); + assertNotNull(webUpdate.getTime()); + assertNotNull(webUpdate.getInfo()); + }); + }); + } + + @Test + public void page() throws Exception { + getMockData(get("/webUpdate/pages?page=1&count=10")).andDo(result -> { + Response> response = getResponse(result, MODAL_PAGE_TYPE); + assertEquals(SUCCESS.getCode(), response.getCode()); + assertNotNull(response.getResult()); + PageData pageData = response.getResult(); + assertEquals(1, pageData.getPageNum()); + assertEquals(10, pageData.getPageSize()); + for (WebUpdateModel model : pageData.getList()) { + assertNotEquals(0, model.getId()); + assertNotNull(model.getTime()); + assertNotNull(model.getInfo()); + } + }); + } + + @Test + public void lastestUpdateTime() throws Exception { + getMockData(get("/lastestUpdate")).andDo(result -> assertEquals(SUCCESS.getCode(), getResponse(result).getCode())); + } } \ No newline at end of file diff --git a/src/test/java/cn/celess/blog/enmu/UserAccountStatusEnumTest.java b/blog-deploy/src/test/java/cn/celess/enmu/UserAccountStatusEnumTest.java similarity index 89% rename from src/test/java/cn/celess/blog/enmu/UserAccountStatusEnumTest.java rename to blog-deploy/src/test/java/cn/celess/enmu/UserAccountStatusEnumTest.java index e7d4448..8486bc9 100644 --- a/src/test/java/cn/celess/blog/enmu/UserAccountStatusEnumTest.java +++ b/blog-deploy/src/test/java/cn/celess/enmu/UserAccountStatusEnumTest.java @@ -1,13 +1,14 @@ -package cn.celess.blog.enmu; +package cn.celess.enmu; -import cn.celess.blog.BaseTest; +import cn.celess.BaseTest; +import cn.celess.common.enmu.UserAccountStatusEnum; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import java.io.IOException; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; public class UserAccountStatusEnumTest extends BaseTest { diff --git a/src/test/java/cn/celess/blog/filter/AuthorizationFilter.java b/blog-deploy/src/test/java/cn/celess/filter/AuthorizationFilter.java similarity index 91% rename from src/test/java/cn/celess/blog/filter/AuthorizationFilter.java rename to blog-deploy/src/test/java/cn/celess/filter/AuthorizationFilter.java index 8747cde..b2a0c74 100644 --- a/src/test/java/cn/celess/blog/filter/AuthorizationFilter.java +++ b/blog-deploy/src/test/java/cn/celess/filter/AuthorizationFilter.java @@ -1,53 +1,53 @@ -package cn.celess.blog.filter; - -import cn.celess.blog.BaseTest; -import cn.celess.blog.entity.Response; -import org.junit.Test; - -import static cn.celess.blog.enmu.ResponseEnum.*; -import static org.junit.Assert.*; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; - -/** - * @Author: 小海 - * @Date: 2019/11/28 16:05 - * @Description: 授权拦截器的测试类 - */ -public class AuthorizationFilter extends BaseTest { - - @Test - public void UserAccess() throws Exception { - // 未登录 - getMockData(get("/user/userInfo")).andDo(result -> assertEquals(HAVE_NOT_LOG_IN.getCode(), getResponse(result).getCode())); - // user权限登录 - getMockData(get("/user/userInfo"), userLogin()).andDo(result -> assertEquals(SUCCESS.getCode(), getResponse(result).getCode())); - } - - @Test - public void AdminAccess() throws Exception { - // 未登录 - getMockData(get("/admin/articles?page=1&count=1")).andDo(result -> assertEquals(HAVE_NOT_LOG_IN.getCode(), getResponse(result).getCode())); - // user权限 - getMockData(get("/admin/articles?page=1&count=1"), userLogin()).andDo(result -> assertEquals(PERMISSION_ERROR.getCode(), getResponse(result).getCode())); - // admin 权限 - getMockData(get("/admin/articles?page=1&count=1"), adminLogin()).andDo(result -> assertEquals(SUCCESS.getCode(), getResponse(result).getCode())); - } - - @Test - public void VisitorAccess() throws Exception { - getMockData(get("/user/userInfo")).andDo(result -> assertEquals(HAVE_NOT_LOG_IN.getCode(), getResponse(result).getCode())); - getMockData(get("/admin/articles?page=1&count=1")).andDo(result -> assertEquals(HAVE_NOT_LOG_IN.getCode(), getResponse(result).getCode())); - } - - @Test - public void authorizationTest() throws Exception { - // 测试response中有无Authorization字段 - String token = userLogin(); - getMockData(get("/user/userInfo"), token).andDo(result -> { - Response response = getResponse(result); - assertEquals(SUCCESS.getCode(), response.getCode()); - assertNotNull(result.getResponse().getHeader("Authorization")); - assertNotEquals(token, result.getResponse().getHeader("Authorization")); - }); - } -} +package cn.celess.filter; + +import cn.celess.BaseTest; +import cn.celess.common.entity.Response; +import org.junit.Test; + +import static cn.celess.common.enmu.ResponseEnum.*; +import static org.junit.Assert.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; + +/** + * @Author: 小海 + * @Date: 2019/11/28 16:05 + * @Description: 授权拦截器的测试类 + */ +public class AuthorizationFilter extends BaseTest { + + @Test + public void UserAccess() throws Exception { + // 未登录 + getMockData(get("/user/userInfo")).andDo(result -> assertEquals(HAVE_NOT_LOG_IN.getCode(), getResponse(result).getCode())); + // user权限登录 + getMockData(get("/user/userInfo"), userLogin()).andDo(result -> assertEquals(SUCCESS.getCode(), getResponse(result).getCode())); + } + + @Test + public void AdminAccess() throws Exception { + // 未登录 + getMockData(get("/admin/articles?page=1&count=1")).andDo(result -> assertEquals(HAVE_NOT_LOG_IN.getCode(), getResponse(result).getCode())); + // user权限 + getMockData(get("/admin/articles?page=1&count=1"), userLogin()).andDo(result -> assertEquals(PERMISSION_ERROR.getCode(), getResponse(result).getCode())); + // admin 权限 + getMockData(get("/admin/articles?page=1&count=1"), adminLogin()).andDo(result -> assertEquals(SUCCESS.getCode(), getResponse(result).getCode())); + } + + @Test + public void VisitorAccess() throws Exception { + getMockData(get("/user/userInfo")).andDo(result -> assertEquals(HAVE_NOT_LOG_IN.getCode(), getResponse(result).getCode())); + getMockData(get("/admin/articles?page=1&count=1")).andDo(result -> assertEquals(HAVE_NOT_LOG_IN.getCode(), getResponse(result).getCode())); + } + + @Test + public void authorizationTest() throws Exception { + // 测试response中有无Authorization字段 + String token = userLogin(); + getMockData(get("/user/userInfo"), token).andDo(result -> { + Response response = getResponse(result); + assertEquals(SUCCESS.getCode(), response.getCode()); + assertNotNull(result.getResponse().getHeader("Authorization")); + assertNotEquals(token, result.getResponse().getHeader("Authorization")); + }); + } +} diff --git a/src/test/java/cn/celess/blog/filter/MultipleSubmitFilter.java b/blog-deploy/src/test/java/cn/celess/filter/MultipleSubmitFilter.java similarity index 85% rename from src/test/java/cn/celess/blog/filter/MultipleSubmitFilter.java rename to blog-deploy/src/test/java/cn/celess/filter/MultipleSubmitFilter.java index 108550a..df5dacd 100644 --- a/src/test/java/cn/celess/blog/filter/MultipleSubmitFilter.java +++ b/blog-deploy/src/test/java/cn/celess/filter/MultipleSubmitFilter.java @@ -1,37 +1,37 @@ -package cn.celess.blog.filter; - -import cn.celess.blog.BaseTest; -import cn.celess.blog.enmu.ResponseEnum; -import cn.celess.blog.entity.Response; -import org.junit.Assert; -import org.junit.Test; -import org.springframework.mock.web.MockHttpSession; -import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; - -/** - * @Author: 小海 - * @Date: 2019/11/28 16:17 - * @Description: 测试重复请求 - */ -public class MultipleSubmitFilter extends BaseTest { - - private MockHttpSession session = null; - - @Test - public void submitTest() throws Exception { - session = new MockHttpSession(); - sendRequest(ResponseEnum.SUCCESS); - sendRequest(ResponseEnum.FAILURE, "重复请求"); - } - - - private void sendRequest(ResponseEnum expectResponse, String... msg) throws Exception { - getMockData(MockMvcRequestBuilders.get("/counts").session(session)).andDo(result -> { - Response response = getResponse(result); - Assert.assertEquals(expectResponse.getCode(), response.getCode()); - if (msg.length != 0) { - Assert.assertEquals(msg[0], response.getMsg()); - } - }); - } -} +package cn.celess.filter; + +import cn.celess.BaseTest; +import cn.celess.common.enmu.ResponseEnum; +import cn.celess.common.entity.Response; +import org.junit.Assert; +import org.junit.Test; +import org.springframework.mock.web.MockHttpSession; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; + +/** + * @Author: 小海 + * @Date: 2019/11/28 16:17 + * @Description: 测试重复请求 + */ +public class MultipleSubmitFilter extends BaseTest { + + private MockHttpSession session = null; + + @Test + public void submitTest() throws Exception { + session = new MockHttpSession(); + sendRequest(ResponseEnum.SUCCESS); + sendRequest(ResponseEnum.FAILURE, "重复请求"); + } + + + private void sendRequest(ResponseEnum expectResponse, String... msg) throws Exception { + getMockData(MockMvcRequestBuilders.get("/counts").session(session)).andDo(result -> { + Response response = getResponse(result); + Assert.assertEquals(expectResponse.getCode(), response.getCode()); + if (msg.length != 0) { + Assert.assertEquals(msg[0], response.getMsg()); + } + }); + } +} diff --git a/src/test/java/cn/celess/blog/mapper/ArticleMapperTest.java b/blog-deploy/src/test/java/cn/celess/mapper/ArticleMapperTest.java similarity index 97% rename from src/test/java/cn/celess/blog/mapper/ArticleMapperTest.java rename to blog-deploy/src/test/java/cn/celess/mapper/ArticleMapperTest.java index b3183df..50e5c5e 100644 --- a/src/test/java/cn/celess/blog/mapper/ArticleMapperTest.java +++ b/blog-deploy/src/test/java/cn/celess/mapper/ArticleMapperTest.java @@ -1,7 +1,10 @@ -package cn.celess.blog.mapper; +package cn.celess.mapper; -import cn.celess.blog.BaseTest; -import cn.celess.blog.entity.*; +import cn.celess.BaseTest; +import cn.celess.common.entity.*; +import cn.celess.common.mapper.ArticleMapper; +import cn.celess.common.mapper.ArticleTagMapper; +import cn.celess.common.mapper.TagMapper; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; diff --git a/src/test/java/cn/celess/blog/mapper/ArticleTagMapperTest.java b/blog-deploy/src/test/java/cn/celess/mapper/ArticleTagMapperTest.java similarity index 95% rename from src/test/java/cn/celess/blog/mapper/ArticleTagMapperTest.java rename to blog-deploy/src/test/java/cn/celess/mapper/ArticleTagMapperTest.java index 457f760..200487b 100644 --- a/src/test/java/cn/celess/blog/mapper/ArticleTagMapperTest.java +++ b/blog-deploy/src/test/java/cn/celess/mapper/ArticleTagMapperTest.java @@ -1,7 +1,10 @@ -package cn.celess.blog.mapper; +package cn.celess.mapper; -import cn.celess.blog.BaseTest; -import cn.celess.blog.entity.*; +import cn.celess.BaseTest; +import cn.celess.common.entity.*; +import cn.celess.common.mapper.ArticleMapper; +import cn.celess.common.mapper.ArticleTagMapper; +import cn.celess.common.mapper.TagMapper; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; diff --git a/src/test/java/cn/celess/blog/mapper/CategoryMapperTest.java b/blog-deploy/src/test/java/cn/celess/mapper/CategoryMapperTest.java similarity index 96% rename from src/test/java/cn/celess/blog/mapper/CategoryMapperTest.java rename to blog-deploy/src/test/java/cn/celess/mapper/CategoryMapperTest.java index 4cf659d..6f09fbb 100644 --- a/src/test/java/cn/celess/blog/mapper/CategoryMapperTest.java +++ b/blog-deploy/src/test/java/cn/celess/mapper/CategoryMapperTest.java @@ -1,7 +1,8 @@ -package cn.celess.blog.mapper; +package cn.celess.mapper; -import cn.celess.blog.BaseTest; -import cn.celess.blog.entity.Category; +import cn.celess.BaseTest; +import cn.celess.common.entity.Category; +import cn.celess.common.mapper.CategoryMapper; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; diff --git a/src/test/java/cn/celess/blog/mapper/CommentMapperTest.java b/blog-deploy/src/test/java/cn/celess/mapper/CommentMapperTest.java similarity index 94% rename from src/test/java/cn/celess/blog/mapper/CommentMapperTest.java rename to blog-deploy/src/test/java/cn/celess/mapper/CommentMapperTest.java index d411dfa..d1e024d 100644 --- a/src/test/java/cn/celess/blog/mapper/CommentMapperTest.java +++ b/blog-deploy/src/test/java/cn/celess/mapper/CommentMapperTest.java @@ -1,9 +1,11 @@ -package cn.celess.blog.mapper; +package cn.celess.mapper; -import cn.celess.blog.BaseTest; -import cn.celess.blog.enmu.CommentStatusEnum; -import cn.celess.blog.entity.Comment; -import cn.celess.blog.entity.User; +import cn.celess.BaseTest; +import cn.celess.common.enmu.CommentStatusEnum; +import cn.celess.common.entity.Comment; +import cn.celess.common.entity.User; +import cn.celess.common.mapper.CommentMapper; +import cn.celess.common.mapper.UserMapper; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; diff --git a/src/test/java/cn/celess/blog/mapper/PartnerMapperTest.java b/blog-deploy/src/test/java/cn/celess/mapper/PartnerMapperTest.java similarity index 95% rename from src/test/java/cn/celess/blog/mapper/PartnerMapperTest.java rename to blog-deploy/src/test/java/cn/celess/mapper/PartnerMapperTest.java index aed93aa..17d8946 100644 --- a/src/test/java/cn/celess/blog/mapper/PartnerMapperTest.java +++ b/blog-deploy/src/test/java/cn/celess/mapper/PartnerMapperTest.java @@ -1,7 +1,8 @@ -package cn.celess.blog.mapper; +package cn.celess.mapper; -import cn.celess.blog.BaseTest; -import cn.celess.blog.entity.PartnerSite; +import cn.celess.BaseTest; +import cn.celess.common.entity.PartnerSite; +import cn.celess.common.mapper.PartnerMapper; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; diff --git a/src/test/java/cn/celess/blog/mapper/TagMapperTest.java b/blog-deploy/src/test/java/cn/celess/mapper/TagMapperTest.java similarity index 94% rename from src/test/java/cn/celess/blog/mapper/TagMapperTest.java rename to blog-deploy/src/test/java/cn/celess/mapper/TagMapperTest.java index 58ddff3..b024229 100644 --- a/src/test/java/cn/celess/blog/mapper/TagMapperTest.java +++ b/blog-deploy/src/test/java/cn/celess/mapper/TagMapperTest.java @@ -1,7 +1,8 @@ -package cn.celess.blog.mapper; +package cn.celess.mapper; -import cn.celess.blog.BaseTest; -import cn.celess.blog.entity.Tag; +import cn.celess.BaseTest; +import cn.celess.common.entity.Tag; +import cn.celess.common.mapper.TagMapper; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; diff --git a/src/test/java/cn/celess/blog/mapper/UserMapperTest.java b/blog-deploy/src/test/java/cn/celess/mapper/UserMapperTest.java similarity index 95% rename from src/test/java/cn/celess/blog/mapper/UserMapperTest.java rename to blog-deploy/src/test/java/cn/celess/mapper/UserMapperTest.java index 0b6e6a3..09eef63 100644 --- a/src/test/java/cn/celess/blog/mapper/UserMapperTest.java +++ b/blog-deploy/src/test/java/cn/celess/mapper/UserMapperTest.java @@ -1,10 +1,11 @@ -package cn.celess.blog.mapper; +package cn.celess.mapper; -import cn.celess.blog.BaseTest; -import cn.celess.blog.enmu.RoleEnum; -import cn.celess.blog.enmu.UserAccountStatusEnum; -import cn.celess.blog.entity.User; -import cn.celess.blog.util.MD5Util; +import cn.celess.BaseTest; +import cn.celess.common.enmu.RoleEnum; +import cn.celess.common.enmu.UserAccountStatusEnum; +import cn.celess.common.entity.User; +import cn.celess.common.mapper.UserMapper; +import cn.celess.common.util.MD5Util; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; diff --git a/src/test/java/cn/celess/blog/mapper/VisitorMapperTest.java b/blog-deploy/src/test/java/cn/celess/mapper/VisitorMapperTest.java similarity index 87% rename from src/test/java/cn/celess/blog/mapper/VisitorMapperTest.java rename to blog-deploy/src/test/java/cn/celess/mapper/VisitorMapperTest.java index 1e2c78d..1caee91 100644 --- a/src/test/java/cn/celess/blog/mapper/VisitorMapperTest.java +++ b/blog-deploy/src/test/java/cn/celess/mapper/VisitorMapperTest.java @@ -1,7 +1,8 @@ -package cn.celess.blog.mapper; +package cn.celess.mapper; -import cn.celess.blog.BaseTest; -import cn.celess.blog.entity.Visitor; +import cn.celess.BaseTest; +import cn.celess.common.entity.Visitor; +import cn.celess.common.mapper.VisitorMapper; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; diff --git a/src/test/java/cn/celess/blog/mapper/WebUpdateInfoMapperTest.java b/blog-deploy/src/test/java/cn/celess/mapper/WebUpdateInfoMapperTest.java similarity index 94% rename from src/test/java/cn/celess/blog/mapper/WebUpdateInfoMapperTest.java rename to blog-deploy/src/test/java/cn/celess/mapper/WebUpdateInfoMapperTest.java index 2ddd107..fee61fc 100644 --- a/src/test/java/cn/celess/blog/mapper/WebUpdateInfoMapperTest.java +++ b/blog-deploy/src/test/java/cn/celess/mapper/WebUpdateInfoMapperTest.java @@ -1,7 +1,8 @@ -package cn.celess.blog.mapper; +package cn.celess.mapper; -import cn.celess.blog.BaseTest; -import cn.celess.blog.entity.WebUpdate; +import cn.celess.BaseTest; +import cn.celess.common.entity.WebUpdate; +import cn.celess.common.mapper.WebUpdateInfoMapper; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; diff --git a/src/test/java/cn/celess/blog/service/ArticleServiceTest.java b/blog-deploy/src/test/java/cn/celess/service/ArticleServiceTest.java similarity index 88% rename from src/test/java/cn/celess/blog/service/ArticleServiceTest.java rename to blog-deploy/src/test/java/cn/celess/service/ArticleServiceTest.java index 6f15706..5433ced 100644 --- a/src/test/java/cn/celess/blog/service/ArticleServiceTest.java +++ b/blog-deploy/src/test/java/cn/celess/service/ArticleServiceTest.java @@ -1,9 +1,10 @@ -package cn.celess.blog.service; +package cn.celess.service; -import cn.celess.blog.BaseTest; -import cn.celess.blog.entity.model.ArticleModel; -import cn.celess.blog.entity.model.PageData; -import cn.celess.blog.mapper.ArticleMapper; +import cn.celess.BaseTest; +import cn.celess.common.entity.vo.ArticleModel; +import cn.celess.common.entity.vo.PageData; +import cn.celess.common.mapper.ArticleMapper; +import cn.celess.common.service.ArticleService; import org.junit.Assert; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; diff --git a/src/test/java/cn/celess/blog/service/PartnerSiteServiceTest.java b/blog-deploy/src/test/java/cn/celess/service/PartnerSiteServiceTest.java similarity index 79% rename from src/test/java/cn/celess/blog/service/PartnerSiteServiceTest.java rename to blog-deploy/src/test/java/cn/celess/service/PartnerSiteServiceTest.java index 0ae95d8..1ad3bf9 100644 --- a/src/test/java/cn/celess/blog/service/PartnerSiteServiceTest.java +++ b/blog-deploy/src/test/java/cn/celess/service/PartnerSiteServiceTest.java @@ -1,15 +1,16 @@ -package cn.celess.blog.service; +package cn.celess.service; -import cn.celess.blog.BaseTest; -import cn.celess.blog.entity.PartnerSite; -import cn.celess.blog.entity.model.PageData; +import cn.celess.BaseTest; +import cn.celess.common.entity.PartnerSite; +import cn.celess.common.entity.vo.PageData; +import cn.celess.common.service.PartnerSiteService; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import java.util.List; -import java.util.stream.Stream; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; public class PartnerSiteServiceTest extends BaseTest { diff --git a/src/test/java/cn/celess/blog/service/UserServiceTest.java b/blog-deploy/src/test/java/cn/celess/service/UserServiceTest.java similarity index 85% rename from src/test/java/cn/celess/blog/service/UserServiceTest.java rename to blog-deploy/src/test/java/cn/celess/service/UserServiceTest.java index 04661eb..87f0d7c 100644 --- a/src/test/java/cn/celess/blog/service/UserServiceTest.java +++ b/blog-deploy/src/test/java/cn/celess/service/UserServiceTest.java @@ -1,15 +1,16 @@ -package cn.celess.blog.service; +package cn.celess.service; -import cn.celess.blog.BaseTest; -import cn.celess.blog.enmu.ResponseEnum; -import cn.celess.blog.enmu.UserAccountStatusEnum; -import cn.celess.blog.entity.User; -import cn.celess.blog.entity.model.PageData; -import cn.celess.blog.entity.model.UserModel; -import cn.celess.blog.entity.request.LoginReq; -import cn.celess.blog.exception.MyException; -import cn.celess.blog.mapper.UserMapper; -import cn.celess.blog.util.MD5Util; +import cn.celess.BaseTest; +import cn.celess.common.enmu.ResponseEnum; +import cn.celess.common.enmu.UserAccountStatusEnum; +import cn.celess.common.entity.User; +import cn.celess.common.entity.dto.LoginReq; +import cn.celess.common.entity.vo.PageData; +import cn.celess.common.entity.vo.UserModel; +import cn.celess.common.exception.MyException; +import cn.celess.common.mapper.UserMapper; +import cn.celess.common.service.UserService; +import cn.celess.common.util.MD5Util; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; diff --git a/src/test/java/cn/celess/blog/service/VisitorServiceTest.java b/blog-deploy/src/test/java/cn/celess/service/VisitorServiceTest.java similarity index 72% rename from src/test/java/cn/celess/blog/service/VisitorServiceTest.java rename to blog-deploy/src/test/java/cn/celess/service/VisitorServiceTest.java index 9c1a7b2..fd4171b 100644 --- a/src/test/java/cn/celess/blog/service/VisitorServiceTest.java +++ b/blog-deploy/src/test/java/cn/celess/service/VisitorServiceTest.java @@ -1,13 +1,15 @@ -package cn.celess.blog.service; +package cn.celess.service; -import cn.celess.blog.BaseTest; -import cn.celess.blog.entity.model.PageData; -import cn.celess.blog.entity.model.VisitorModel; +import cn.celess.BaseTest; +import cn.celess.common.entity.vo.PageData; +import cn.celess.common.entity.vo.VisitorModel; +import cn.celess.common.service.VisitorService; import com.alibaba.druid.util.StringUtils; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; public class VisitorServiceTest extends BaseTest { diff --git a/src/test/java/cn/celess/blog/util/AddressUtilTest.java b/blog-deploy/src/test/java/cn/celess/util/AddressUtilTest.java similarity index 69% rename from src/test/java/cn/celess/blog/util/AddressUtilTest.java rename to blog-deploy/src/test/java/cn/celess/util/AddressUtilTest.java index 5c01440..d38bdad 100644 --- a/src/test/java/cn/celess/blog/util/AddressUtilTest.java +++ b/blog-deploy/src/test/java/cn/celess/util/AddressUtilTest.java @@ -1,9 +1,10 @@ -package cn.celess.blog.util; +package cn.celess.util; -import cn.celess.blog.BaseTest; +import cn.celess.BaseTest; +import cn.celess.visitor.util.AddressUtil; import org.junit.Test; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; public class AddressUtilTest extends BaseTest { diff --git a/src/test/java/cn/celess/blog/util/DateFormatUtilTest.java b/blog-deploy/src/test/java/cn/celess/util/DateFormatUtilTest.java similarity index 82% rename from src/test/java/cn/celess/blog/util/DateFormatUtilTest.java rename to blog-deploy/src/test/java/cn/celess/util/DateFormatUtilTest.java index c1a8b8e..8b30f75 100644 --- a/src/test/java/cn/celess/blog/util/DateFormatUtilTest.java +++ b/blog-deploy/src/test/java/cn/celess/util/DateFormatUtilTest.java @@ -1,6 +1,7 @@ -package cn.celess.blog.util; +package cn.celess.util; -import cn.celess.blog.BaseTest; +import cn.celess.BaseTest; +import cn.celess.common.util.DateFormatUtil; import org.junit.Test; import java.util.Date; diff --git a/src/test/java/cn/celess/blog/util/HttpUtilTest.java b/blog-deploy/src/test/java/cn/celess/util/HttpUtilTest.java similarity index 84% rename from src/test/java/cn/celess/blog/util/HttpUtilTest.java rename to blog-deploy/src/test/java/cn/celess/util/HttpUtilTest.java index 544d0ab..6cec6e4 100644 --- a/src/test/java/cn/celess/blog/util/HttpUtilTest.java +++ b/blog-deploy/src/test/java/cn/celess/util/HttpUtilTest.java @@ -1,6 +1,7 @@ -package cn.celess.blog.util; +package cn.celess.util; -import cn.celess.blog.BaseTest; +import cn.celess.BaseTest; +import cn.celess.common.util.HttpUtil; import org.junit.Test; import static org.junit.Assert.assertNotNull; diff --git a/src/test/java/cn/celess/blog/util/JwtUtilTest.java b/blog-deploy/src/test/java/cn/celess/util/JwtUtilTest.java similarity index 93% rename from src/test/java/cn/celess/blog/util/JwtUtilTest.java rename to blog-deploy/src/test/java/cn/celess/util/JwtUtilTest.java index 402c37b..83d7714 100644 --- a/src/test/java/cn/celess/blog/util/JwtUtilTest.java +++ b/blog-deploy/src/test/java/cn/celess/util/JwtUtilTest.java @@ -1,80 +1,81 @@ -package cn.celess.blog.util; - -import cn.celess.blog.BaseTest; -import cn.celess.blog.entity.User; -import io.jsonwebtoken.Jwts; -import io.jsonwebtoken.SignatureAlgorithm; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; - -import java.time.Instant; -import java.util.Date; - -import static org.junit.Assert.*; - -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -public class JwtUtilTest extends BaseTest { - - @Autowired - JwtUtil jwtUtil; - @Value("${jwt.secret}") - private String secret; - - @Test - public void testGenerateToken() { - User user = new User(); - user.setEmail("a@celess.cn"); - String s = jwtUtil.generateToken(user, false); - assertNotNull(s); - String str = null; - try { - str = jwtUtil.generateToken(null, false); - } catch (Exception e) { - // ignore - } - assertNull(str); - } - - @Test - public void testIsTokenExpired() throws InterruptedException { - String s = Jwts.builder() - .setClaims(null) - .setExpiration(new Date(Instant.now().toEpochMilli() + 1000)) - .signWith(SignatureAlgorithm.HS512, secret) - .compact(); - Thread.sleep(1010); - assertTrue(jwtUtil.isTokenExpired(s)); - assertFalse(jwtUtil.isTokenExpired(jwtUtil.generateToken(new User(), false))); - } - - @Test - public void testGetUsernameFromToken() { - User user = new User(); - user.setEmail("a@celess.cn"); - String s = jwtUtil.generateToken(user, false); - assertEquals(user.getEmail(), jwtUtil.getUsernameFromToken(s)); - user.setEmail("example@celess.cn"); - assertNotEquals(user.getEmail(), jwtUtil.getUsernameFromToken(s)); - } - - @Test - public void testGetExpirationDateFromToken() { - User user = new User(); - user.setEmail("a@celess.cn"); - String s = jwtUtil.generateToken(user, false); - assertNotNull(jwtUtil.getExpirationDateFromToken(s)); - } - - @Test - public void updateTokenDate() { - User user = new User(); - user.setEmail("a@celess.cn"); - String s = jwtUtil.generateToken(user, false); - Date before = jwtUtil.getExpirationDateFromToken(s); - String s1 = jwtUtil.updateTokenDate(s); - assertTrue(jwtUtil.getExpirationDateFromToken(s1).getTime() - jwtUtil.getExpirationDateFromToken(s).getTime() > 0); - } +package cn.celess.util; + +import cn.celess.BaseTest; +import cn.celess.common.entity.User; +import cn.celess.user.util.JwtUtil; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.SignatureAlgorithm; +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.junit.runners.MethodSorters; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; + +import java.time.Instant; +import java.util.Date; + +import static org.junit.Assert.*; + +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +public class JwtUtilTest extends BaseTest { + + @Autowired + JwtUtil jwtUtil; + @Value("${jwt.secret}") + private String secret; + + @Test + public void testGenerateToken() { + User user = new User(); + user.setEmail("a@celess.cn"); + String s = jwtUtil.generateToken(user, false); + assertNotNull(s); + String str = null; + try { + str = jwtUtil.generateToken(null, false); + } catch (Exception e) { + // ignore + } + assertNull(str); + } + + @Test + public void testIsTokenExpired() throws InterruptedException { + String s = Jwts.builder() + .setClaims(null) + .setExpiration(new Date(Instant.now().toEpochMilli() + 1000)) + .signWith(SignatureAlgorithm.HS512, secret) + .compact(); + Thread.sleep(1010); + assertTrue(jwtUtil.isTokenExpired(s)); + assertFalse(jwtUtil.isTokenExpired(jwtUtil.generateToken(new User(), false))); + } + + @Test + public void testGetUsernameFromToken() { + User user = new User(); + user.setEmail("a@celess.cn"); + String s = jwtUtil.generateToken(user, false); + assertEquals(user.getEmail(), jwtUtil.getUsernameFromToken(s)); + user.setEmail("example@celess.cn"); + assertNotEquals(user.getEmail(), jwtUtil.getUsernameFromToken(s)); + } + + @Test + public void testGetExpirationDateFromToken() { + User user = new User(); + user.setEmail("a@celess.cn"); + String s = jwtUtil.generateToken(user, false); + assertNotNull(jwtUtil.getExpirationDateFromToken(s)); + } + + @Test + public void updateTokenDate() { + User user = new User(); + user.setEmail("a@celess.cn"); + String s = jwtUtil.generateToken(user, false); + Date before = jwtUtil.getExpirationDateFromToken(s); + String s1 = jwtUtil.updateTokenDate(s); + assertTrue(jwtUtil.getExpirationDateFromToken(s1).getTime() - jwtUtil.getExpirationDateFromToken(s).getTime() > 0); + } } \ No newline at end of file diff --git a/src/test/java/cn/celess/blog/util/MD5UtilTest.java b/blog-deploy/src/test/java/cn/celess/util/MD5UtilTest.java similarity index 73% rename from src/test/java/cn/celess/blog/util/MD5UtilTest.java rename to blog-deploy/src/test/java/cn/celess/util/MD5UtilTest.java index b8604a0..602762b 100644 --- a/src/test/java/cn/celess/blog/util/MD5UtilTest.java +++ b/blog-deploy/src/test/java/cn/celess/util/MD5UtilTest.java @@ -1,6 +1,7 @@ -package cn.celess.blog.util; +package cn.celess.util; -import cn.celess.blog.BaseTest; +import cn.celess.BaseTest; +import cn.celess.common.util.MD5Util; import org.junit.Test; import static org.junit.Assert.assertEquals; diff --git a/blog-extension/pom.xml b/blog-extension/pom.xml new file mode 100644 index 0000000..d9e4d9d --- /dev/null +++ b/blog-extension/pom.xml @@ -0,0 +1,49 @@ + + + + blog + cn.celess + 0.0.1-SNAPSHOT + + 4.0.0 + + blog-extension + + + 13 + 13 + + + + cn.celess + blog-common + ${blog-common.version} + + + + cn.celess + blog-user + ${blog-user.version} + + + + org.springframework.boot + spring-boot-starter-web + + + + + com.qiniu + qiniu-java-sdk + [7.2.0, 7.2.99] + + + + + org.springframework.boot + spring-boot-starter-mail + + + \ No newline at end of file diff --git a/src/main/java/cn/celess/blog/controller/CommonController.java b/blog-extension/src/main/java/cn/celess/extension/controller/ExtensionController.java similarity index 92% rename from src/main/java/cn/celess/blog/controller/CommonController.java rename to blog-extension/src/main/java/cn/celess/extension/controller/ExtensionController.java index 7f7ce96..676f3b6 100644 --- a/src/main/java/cn/celess/blog/controller/CommonController.java +++ b/blog-extension/src/main/java/cn/celess/extension/controller/ExtensionController.java @@ -1,15 +1,15 @@ -package cn.celess.blog.controller; +package cn.celess.extension.controller; -import cn.celess.blog.enmu.ResponseEnum; -import cn.celess.blog.entity.Response; -import cn.celess.blog.entity.model.QiniuResponse; -import cn.celess.blog.exception.MyException; -import cn.celess.blog.service.CountService; -import cn.celess.blog.service.QiniuService; -import cn.celess.blog.util.HttpUtil; -import cn.celess.blog.util.RedisUserUtil; -import cn.celess.blog.util.RedisUtil; -import cn.celess.blog.util.VeriCodeUtil; +import cn.celess.common.enmu.ResponseEnum; +import cn.celess.common.entity.Response; +import cn.celess.common.entity.vo.QiniuResponse; +import cn.celess.common.exception.MyException; +import cn.celess.common.service.CountService; +import cn.celess.common.service.QiniuService; +import cn.celess.common.util.HttpUtil; +import cn.celess.common.util.RedisUtil; +import cn.celess.common.util.VeriCodeUtil; +import cn.celess.user.util.RedisUserUtil; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import org.slf4j.Logger; @@ -36,7 +36,7 @@ import java.util.concurrent.TimeUnit; * @date : 2019/04/02 22:03 */ @RestController -public class CommonController { +public class ExtensionController { public static final Logger logger = LoggerFactory.getLogger(Object.class); @Autowired @@ -159,8 +159,8 @@ public class CommonController { String fileName = file.getOriginalFilename(); assert fileName != null; String mime = fileName.substring(fileName.lastIndexOf(".")); - if (".png".equals(mime.toLowerCase()) || ".jpg".equals(mime.toLowerCase()) || - ".jpeg".equals(mime.toLowerCase()) || ".bmp".equals(mime.toLowerCase())) { + if (".png".equalsIgnoreCase(mime) || ".jpg".equalsIgnoreCase(mime) || + ".jpeg".equalsIgnoreCase(mime) || ".bmp".equalsIgnoreCase(mime)) { QiniuResponse qiniuResponse = qiniuService.uploadFile(file.getInputStream(), "img_" + System.currentTimeMillis() + mime); map.put("success", 1); map.put("message", "上传成功"); diff --git a/src/main/java/cn/celess/blog/service/serviceimpl/CountServiceImpl.java b/blog-extension/src/main/java/cn/celess/extension/serviceimpl/CountServiceImpl.java similarity index 85% rename from src/main/java/cn/celess/blog/service/serviceimpl/CountServiceImpl.java rename to blog-extension/src/main/java/cn/celess/extension/serviceimpl/CountServiceImpl.java index fecd29b..5a8054a 100644 --- a/src/main/java/cn/celess/blog/service/serviceimpl/CountServiceImpl.java +++ b/blog-extension/src/main/java/cn/celess/extension/serviceimpl/CountServiceImpl.java @@ -1,68 +1,68 @@ -package cn.celess.blog.service.serviceimpl; - -import cn.celess.blog.mapper.*; -import cn.celess.blog.service.CountService; -import cn.celess.blog.util.RedisUtil; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -/** - * @author : xiaohai - * @date : 2019/04/02 22:06 - */ -@Service -public class CountServiceImpl implements CountService { - @Autowired - ArticleMapper articleMapper; - @Autowired - TagMapper tagMapper; - @Autowired - CommentMapper commentMapper; - @Autowired - CategoryMapper categoryMapper; - @Autowired - UserMapper userMapper; - @Autowired - VisitorMapper visitorMapper; - @Autowired - RedisUtil redisUtil; - - @Override - public long getCommentCount() { - return commentMapper.count(); - } - - @Override - public long getArticleCount() { - return articleMapper.count(); - } - - @Override - public long getCategoriesCount() { - return categoryMapper.count(); - } - - @Override - public long getTagsCount() { - return tagMapper.count(); - } - - @Override - public long getUserCount() { - return userMapper.count(); - } - - @Override - public long getVisitorCount() { - return visitorMapper.count(); - } - - @Override - public long getDayVisitCount() { - String dayVisitCount = redisUtil.get("dayVisitCount"); - if (dayVisitCount == null) { - return 1; - } - return Integer.parseInt(dayVisitCount); - } -} +package cn.celess.extension.serviceimpl; + +import cn.celess.common.mapper.*; +import cn.celess.common.service.CountService; +import cn.celess.common.util.RedisUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +/** + * @author : xiaohai + * @date : 2019/04/02 22:06 + */ +@Service +public class CountServiceImpl implements CountService { + @Autowired + ArticleMapper articleMapper; + @Autowired + TagMapper tagMapper; + @Autowired + CommentMapper commentMapper; + @Autowired + CategoryMapper categoryMapper; + @Autowired + UserMapper userMapper; + @Autowired + VisitorMapper visitorMapper; + @Autowired + RedisUtil redisUtil; + + @Override + public long getCommentCount() { + return commentMapper.count(); + } + + @Override + public long getArticleCount() { + return articleMapper.count(); + } + + @Override + public long getCategoriesCount() { + return categoryMapper.count(); + } + + @Override + public long getTagsCount() { + return tagMapper.count(); + } + + @Override + public long getUserCount() { + return userMapper.count(); + } + + @Override + public long getVisitorCount() { + return visitorMapper.count(); + } + + @Override + public long getDayVisitCount() { + String dayVisitCount = redisUtil.get("dayVisitCount"); + if (dayVisitCount == null) { + return 1; + } + return Integer.parseInt(dayVisitCount); + } +} diff --git a/src/main/java/cn/celess/blog/service/serviceimpl/MailServiceImpl.java b/blog-extension/src/main/java/cn/celess/extension/serviceimpl/MailServiceImpl.java similarity index 82% rename from src/main/java/cn/celess/blog/service/serviceimpl/MailServiceImpl.java rename to blog-extension/src/main/java/cn/celess/extension/serviceimpl/MailServiceImpl.java index eeab067..b2bab99 100644 --- a/src/main/java/cn/celess/blog/service/serviceimpl/MailServiceImpl.java +++ b/blog-extension/src/main/java/cn/celess/extension/serviceimpl/MailServiceImpl.java @@ -1,41 +1,41 @@ -package cn.celess.blog.service.serviceimpl; - -import cn.celess.blog.service.MailService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.mail.SimpleMailMessage; -import org.springframework.mail.javamail.JavaMailSender; -import org.springframework.scheduling.annotation.Async; -import org.springframework.stereotype.Service; - -import java.io.UnsupportedEncodingException; - -/** - * @author : xiaohai - * @date : 2019/04/22 14:26 - */ -@Service -public class MailServiceImpl implements MailService { - public static final String FROM = ""; - @Autowired - JavaMailSender javaMailSender; - - @Override - @Async - public Boolean AsyncSend(SimpleMailMessage message) { - this.send(message); - return true; - } - - @Override - public Boolean send(SimpleMailMessage message) { - String nick = null; - try { - nick = javax.mail.internet.MimeUtility.encodeText("小海博客"); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } - message.setFrom(nick + FROM); - javaMailSender.send(message); - return true; - } -} +package cn.celess.extension.serviceimpl; + +import cn.celess.common.service.MailService; +import org.springframework.mail.SimpleMailMessage; +import org.springframework.mail.javamail.JavaMailSender; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.io.UnsupportedEncodingException; + +/** + * @author : xiaohai + * @date : 2019/04/22 14:26 + */ +@Service +public class MailServiceImpl implements MailService { + public static final String FROM = ""; + @Resource + JavaMailSender javaMailSender; + + @Override + @Async + public Boolean AsyncSend(SimpleMailMessage message) { + this.send(message); + return true; + } + + @Override + public Boolean send(SimpleMailMessage message) { + String nick = null; + try { + nick = javax.mail.internet.MimeUtility.encodeText("小海博客"); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + message.setFrom(nick + FROM); + javaMailSender.send(message); + return true; + } +} diff --git a/src/main/java/cn/celess/blog/service/serviceimpl/QiniuServiceImpl.java b/blog-extension/src/main/java/cn/celess/extension/serviceimpl/QiniuServiceImpl.java similarity index 92% rename from src/main/java/cn/celess/blog/service/serviceimpl/QiniuServiceImpl.java rename to blog-extension/src/main/java/cn/celess/extension/serviceimpl/QiniuServiceImpl.java index e95d202..37f5994 100644 --- a/src/main/java/cn/celess/blog/service/serviceimpl/QiniuServiceImpl.java +++ b/blog-extension/src/main/java/cn/celess/extension/serviceimpl/QiniuServiceImpl.java @@ -1,87 +1,87 @@ -package cn.celess.blog.service.serviceimpl; - -import cn.celess.blog.entity.model.QiniuResponse; -import cn.celess.blog.service.QiniuService; -import com.qiniu.common.QiniuException; -import com.qiniu.common.Zone; -import com.qiniu.http.Response; -import com.qiniu.storage.BucketManager; -import com.qiniu.storage.Configuration; -import com.qiniu.storage.UploadManager; -import com.qiniu.storage.model.FileInfo; -import com.qiniu.util.Auth; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Service; - -import java.io.InputStream; - -/** - * @author : xiaohai - * @date : 2019/04/25 18:15 - */ -@Service -public class QiniuServiceImpl implements QiniuService { - private static final Configuration cfg = new Configuration(Zone.zone2()); - private static UploadManager uploadManager; - private static BucketManager bucketManager; - private static Auth auth; - - @Value("${qiniu.accessKey}") - private String accessKey; - @Value("${qiniu.secretKey}") - private String secretKey; - @Value("${qiniu.bucket}") - private String bucket; - - private void init() { - if (auth == null || uploadManager == null || bucketManager == null) { - auth = Auth.create(accessKey, secretKey); - uploadManager = new UploadManager(cfg); - bucketManager = new BucketManager(auth, cfg); - } - } - - @Override - public QiniuResponse uploadFile(InputStream is, String fileName) { - init(); - //文件存在则删除文件 - if (continueFile(fileName)) { - try { - System.out.println(bucketManager.delete(bucket, fileName).toString()); - } catch (QiniuException e) { - e.printStackTrace(); - } - } - //上传 - try { - Response response = uploadManager.put(is, fileName, auth.uploadToken(bucket), null, null); - return response.jsonToObject(QiniuResponse.class); - } catch (QiniuException e) { - Response r = e.response; - System.err.println(r.toString()); - return null; - } - } - - @Override - public FileInfo[] getFileList() { - init(); - BucketManager.FileListIterator fileListIterator = bucketManager.createFileListIterator(bucket, "", 1000, ""); - FileInfo[] items = null; - while (fileListIterator.hasNext()) { - //处理获取的file list结果 - items = fileListIterator.next(); - } - return items; - } - - private boolean continueFile(String key) { - FileInfo[] allFile = getFileList(); - for (FileInfo fileInfo : allFile) { - if (key.equals(fileInfo.key)) { - return true; - } - } - return false; - } -} +package cn.celess.extension.serviceimpl; + +import cn.celess.common.entity.vo.QiniuResponse; +import cn.celess.common.service.QiniuService; +import com.qiniu.common.QiniuException; +import com.qiniu.common.Zone; +import com.qiniu.http.Response; +import com.qiniu.storage.BucketManager; +import com.qiniu.storage.Configuration; +import com.qiniu.storage.UploadManager; +import com.qiniu.storage.model.FileInfo; +import com.qiniu.util.Auth; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; + +import java.io.InputStream; + +/** + * @author : xiaohai + * @date : 2019/04/25 18:15 + */ +@Service +public class QiniuServiceImpl implements QiniuService { + private static final Configuration cfg = new Configuration(Zone.zone2()); + private static UploadManager uploadManager; + private static BucketManager bucketManager; + private static Auth auth; + + @Value("${qiniu.accessKey}") + private String accessKey; + @Value("${qiniu.secretKey}") + private String secretKey; + @Value("${qiniu.bucket}") + private String bucket; + + private void init() { + if (auth == null || uploadManager == null || bucketManager == null) { + auth = Auth.create(accessKey, secretKey); + uploadManager = new UploadManager(cfg); + bucketManager = new BucketManager(auth, cfg); + } + } + + @Override + public QiniuResponse uploadFile(InputStream is, String fileName) { + init(); + //文件存在则删除文件 + if (continueFile(fileName)) { + try { + System.out.println(bucketManager.delete(bucket, fileName).toString()); + } catch (QiniuException e) { + e.printStackTrace(); + } + } + //上传 + try { + Response response = uploadManager.put(is, fileName, auth.uploadToken(bucket), null, null); + return response.jsonToObject(QiniuResponse.class); + } catch (QiniuException e) { + Response r = e.response; + System.err.println(r.toString()); + return null; + } + } + + @Override + public FileInfo[] getFileList() { + init(); + BucketManager.FileListIterator fileListIterator = bucketManager.createFileListIterator(bucket, "", 1000, ""); + FileInfo[] items = null; + while (fileListIterator.hasNext()) { + //处理获取的file list结果 + items = fileListIterator.next(); + } + return items; + } + + private boolean continueFile(String key) { + FileInfo[] allFile = getFileList(); + for (FileInfo fileInfo : allFile) { + if (key.equals(fileInfo.key)) { + return true; + } + } + return false; + } +} diff --git a/blog-partnersite/pom.xml b/blog-partnersite/pom.xml new file mode 100644 index 0000000..02bc40d --- /dev/null +++ b/blog-partnersite/pom.xml @@ -0,0 +1,50 @@ + + + + blog + cn.celess + 0.0.1-SNAPSHOT + + 4.0.0 + + blog-partnersite + + + 13 + 13 + + + + cn.celess + blog-common + ${blog-common.version} + + + + org.springframework.boot + spring-boot-starter-web + + + + + com.squareup.okhttp3 + okhttp + 4.9.1 + + + + + + + + + + net.sourceforge.htmlunit + htmlunit + 2.45.0 + + + + \ No newline at end of file diff --git a/src/main/java/cn/celess/blog/controller/LinksController.java b/blog-partnersite/src/main/java/cn/celess/partnersite/controller/PartnerSiteController.java similarity index 81% rename from src/main/java/cn/celess/blog/controller/LinksController.java rename to blog-partnersite/src/main/java/cn/celess/partnersite/controller/PartnerSiteController.java index 3c5db4b..e1382ec 100644 --- a/src/main/java/cn/celess/blog/controller/LinksController.java +++ b/blog-partnersite/src/main/java/cn/celess/partnersite/controller/PartnerSiteController.java @@ -1,69 +1,70 @@ -package cn.celess.blog.controller; - -import cn.celess.blog.entity.PartnerSite; -import cn.celess.blog.entity.Response; -import cn.celess.blog.entity.request.LinkApplyReq; -import cn.celess.blog.entity.request.LinkReq; -import cn.celess.blog.service.MailService; -import cn.celess.blog.service.PartnerSiteService; -import cn.celess.blog.util.RedisUtil; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.*; - -import javax.servlet.http.HttpServletRequest; -import java.util.List; -import java.util.stream.Collectors; - -/** - * @author : xiaohai - * @date : 2019/05/12 13:26 - */ -@RestController -public class LinksController { - @Autowired - PartnerSiteService partnerSiteService; - @Autowired - MailService mailService; - @Autowired - RedisUtil redisUtil; - @Autowired - HttpServletRequest request; - - @PostMapping("/admin/links/create") - public Response create(@RequestBody LinkReq reqBody) { - return Response.success(partnerSiteService.create(reqBody)); - } - - @DeleteMapping("/admin/links/del/{id}") - public Response del(@PathVariable("id") long id) { - return Response.success(partnerSiteService.del(id)); - } - - @PutMapping("/admin/links/update") - public Response update(@RequestBody LinkReq reqBody) { - return Response.success(partnerSiteService.update(reqBody)); - } - - @GetMapping("/links") - public Response allForOpen() { - List sites = partnerSiteService.findAll().stream().peek(partnerSite -> partnerSite.setOpen(null)).collect(Collectors.toList()); - return Response.success(sites); - } - - @GetMapping("/admin/links") - public Response all(@RequestParam("page") int page, - @RequestParam("count") int count, - @RequestParam(value = "deleted", required = false) Boolean deleted) { - return Response.success(partnerSiteService.partnerSitePages(page, count, deleted)); - } - - @PostMapping("/apply") - public Response apply(@RequestBody() LinkApplyReq linkApplyReq) { - return Response.success(partnerSiteService.apply(linkApplyReq)); - } - - @PostMapping("/reapply") - public Response reapply(@RequestParam("key") String key) { - return Response.success(partnerSiteService.reapply(key)); - } -} +package cn.celess.partnersite.controller; + + +import cn.celess.common.entity.PartnerSite; +import cn.celess.common.entity.Response; +import cn.celess.common.entity.dto.LinkApplyReq; +import cn.celess.common.entity.dto.LinkReq; +import cn.celess.common.service.MailService; +import cn.celess.common.service.PartnerSiteService; +import cn.celess.common.util.RedisUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import java.util.List; +import java.util.stream.Collectors; + +/** + * @author : xiaohai + * @date : 2019/05/12 13:26 + */ +@RestController +public class PartnerSiteController { + @Autowired + PartnerSiteService partnerSiteService; + @Autowired + MailService mailService; + @Autowired + RedisUtil redisUtil; + @Autowired + HttpServletRequest request; + + @PostMapping("/admin/links/create") + public Response create(@RequestBody LinkReq reqBody) { + return Response.success(partnerSiteService.create(reqBody)); + } + + @DeleteMapping("/admin/links/del/{id}") + public Response del(@PathVariable("id") long id) { + return Response.success(partnerSiteService.del(id)); + } + + @PutMapping("/admin/links/update") + public Response update(@RequestBody LinkReq reqBody) { + return Response.success(partnerSiteService.update(reqBody)); + } + + @GetMapping("/links") + public Response allForOpen() { + List sites = partnerSiteService.findAll().stream().peek(partnerSite -> partnerSite.setOpen(null)).collect(Collectors.toList()); + return Response.success(sites); + } + + @GetMapping("/admin/links") + public Response all(@RequestParam("page") int page, + @RequestParam("count") int count, + @RequestParam(value = "deleted", required = false) Boolean deleted) { + return Response.success(partnerSiteService.partnerSitePages(page, count, deleted)); + } + + @PostMapping("/apply") + public Response apply(@RequestBody() LinkApplyReq linkApplyReq) { + return Response.success(partnerSiteService.apply(linkApplyReq)); + } + + @PostMapping("/reapply") + public Response reapply(@RequestParam("key") String key) { + return Response.success(partnerSiteService.reapply(key)); + } +} diff --git a/src/main/java/cn/celess/blog/service/serviceimpl/PartnerSiteServiceImpl.java b/blog-partnersite/src/main/java/cn/celess/partnersite/serviceimpl/PartnerSiteServiceImpl.java similarity index 90% rename from src/main/java/cn/celess/blog/service/serviceimpl/PartnerSiteServiceImpl.java rename to blog-partnersite/src/main/java/cn/celess/partnersite/serviceimpl/PartnerSiteServiceImpl.java index 7c79525..a8f4c46 100644 --- a/src/main/java/cn/celess/blog/service/serviceimpl/PartnerSiteServiceImpl.java +++ b/blog-partnersite/src/main/java/cn/celess/partnersite/serviceimpl/PartnerSiteServiceImpl.java @@ -1,228 +1,228 @@ -package cn.celess.blog.service.serviceimpl; - -import cn.celess.blog.enmu.ResponseEnum; -import cn.celess.blog.entity.PartnerSite; -import cn.celess.blog.entity.model.PageData; -import cn.celess.blog.entity.request.LinkApplyReq; -import cn.celess.blog.entity.request.LinkReq; -import cn.celess.blog.exception.MyException; -import cn.celess.blog.mapper.PartnerMapper; -import cn.celess.blog.service.MailService; -import cn.celess.blog.service.PartnerSiteService; -import cn.celess.blog.util.HttpUtil; -import cn.celess.blog.util.RedisUtil; -import cn.celess.blog.util.RegexUtil; -import com.alibaba.druid.util.StringUtils; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.github.pagehelper.PageHelper; -import com.github.pagehelper.PageInfo; -import lombok.SneakyThrows; -import org.springframework.beans.BeanUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.mail.SimpleMailMessage; -import org.springframework.stereotype.Service; - -import java.util.Date; -import java.util.List; -import java.util.UUID; -import java.util.concurrent.TimeUnit; - -/** - * @author : xiaohai - * @date : 2019/05/12 11:43 - */ -@Service -public class PartnerSiteServiceImpl implements PartnerSiteService { - @Autowired - PartnerMapper partnerMapper; - @Autowired - MailService mailService; - @Autowired - RedisUtil redisUtil; - private static final String SITE_NAME = "小海博客"; - private static final String SITE_URL = "celess.cn"; - private static final String SITE_EMAIL = "a@celess.cn"; - - @Override - public PartnerSite create(LinkReq reqBody) { - if (reqBody == null) { - throw new MyException(ResponseEnum.PARAMETERS_ERROR); - } - //判空 - if (reqBody.getName() == null || reqBody.getUrl() == null) { - throw new MyException(ResponseEnum.PARAMETERS_ERROR); - } - //判空 - if (reqBody.getName().replaceAll(" ", "").isEmpty() || reqBody.getUrl().replaceAll(" ", "").isEmpty()) { - throw new MyException(ResponseEnum.PARAMETERS_ERROR); - } - //是否存在 同名 - if (partnerMapper.existsByName(reqBody.getName())) { - throw new MyException(ResponseEnum.DATA_HAS_EXIST); - } - //url是否合法 - if (!RegexUtil.urlMatch(reqBody.getUrl())) { - throw new MyException(ResponseEnum.PARAMETERS_URL_ERROR); - } - PartnerSite partnerSite = new PartnerSite(); - reqBody.setId(0); - if (!reqBody.getUrl().contains("http://") && !reqBody.getUrl().contains("https://")) { - reqBody.setUrl("http://" + reqBody.getUrl()); - } - BeanUtils.copyProperties(reqBody, partnerSite); - if (reqBody.getIconPath() == null) { - partnerSite.setIconPath(""); - } - if (reqBody.getDesc() == null) { - partnerSite.setDesc(""); - } - partnerMapper.insert(partnerSite); - return partnerSite; - } - - @Override - public Boolean del(long id) { - //判断数据是否存在 - if (!partnerMapper.existsById(id)) { - throw new MyException(ResponseEnum.DATA_NOT_EXIST); - } - return partnerMapper.delete(id) == 1; - } - - @Override - public PartnerSite update(LinkReq reqBody) { - PartnerSite partnerSite = partnerMapper.findById(reqBody.getId()); - if (partnerSite == null) { - throw new MyException(ResponseEnum.DATA_NOT_EXIST); - } - if (partnerMapper.existsByName(reqBody.getName()) && !reqBody.getName().equals(partnerSite.getName())) { - throw new MyException(ResponseEnum.DATA_HAS_EXIST); - } - if (!RegexUtil.urlMatch(reqBody.getUrl())) { - throw new MyException(ResponseEnum.PARAMETERS_URL_ERROR); - } - if (!reqBody.getUrl().contains("http://") && !reqBody.getUrl().contains("https://")) { - reqBody.setUrl("http://" + reqBody.getUrl()); - } - if (reqBody.isOpen() != partnerSite.getOpen() && !partnerSite.getNotification() && !StringUtils.isEmpty(partnerSite.getEmail())) { - SimpleMailMessage smm = new SimpleMailMessage(); - smm.setTo(partnerSite.getEmail()); - smm.setText("您的友链申请,已通过"); - smm.setSubject("友链申请通过"); - smm.setSentDate(new Date()); - mailService.send(smm); - partnerSite.setNotification(true); - } - BeanUtils.copyProperties(reqBody, partnerSite); - partnerMapper.update(partnerSite); - partnerSite.setName(reqBody.getName()); - partnerSite.setUrl(reqBody.getUrl()); - partnerSite.setOpen(reqBody.isOpen()); - - return partnerSite; - } - - @Override - public PageData partnerSitePages(int page, int count, Boolean deleted) { - PageHelper.startPage(page, count); - List sitePage = partnerMapper.findAll(deleted); - PageInfo pageInfo = new PageInfo(sitePage); - return new PageData<>(pageInfo, sitePage); - } - - @Override - public List findAll() { - List all = partnerMapper.findAll(); - all.forEach(partnerSite -> partnerSite.setDelete(null)); - return all; - } - - @SneakyThrows - @Override - public PartnerSite apply(LinkApplyReq linkApplyReq) { - // 空值字段 - if (StringUtils.isEmpty(linkApplyReq.getName()) - || StringUtils.isEmpty(linkApplyReq.getUrl()) - || StringUtils.isEmpty(linkApplyReq.getEmail()) - || StringUtils.isEmpty(linkApplyReq.getLinkUrl())) { - throw new MyException(ResponseEnum.PARAMETERS_ERROR); - } - // 链接不合法 - if (!RegexUtil.emailMatch(linkApplyReq.getEmail())) { - throw new MyException(ResponseEnum.PARAMETERS_EMAIL_ERROR); - } - if (!RegexUtil.urlMatch(linkApplyReq.getLinkUrl()) || !RegexUtil.urlMatch(linkApplyReq.getUrl())) { - throw new MyException(ResponseEnum.PARAMETERS_URL_ERROR); - } - if (!StringUtils.isEmpty(linkApplyReq.getIconPath()) && !RegexUtil.urlMatch(linkApplyReq.getIconPath())) { - throw new MyException(ResponseEnum.PARAMETERS_URL_ERROR); - } - // 非强制字段 设置空 - if (StringUtils.isEmpty(linkApplyReq.getIconPath())) { - linkApplyReq.setIconPath(""); - } - // 抓取页面 - String resp = HttpUtil.getAfterRendering(linkApplyReq.getLinkUrl()); - if (resp == null) { - throw new MyException(ResponseEnum.CANNOT_GET_DATA); - } - PartnerSite ps = new PartnerSite(); - if (resp.contains(SITE_URL)) { - //包含站点 - BeanUtils.copyProperties(linkApplyReq, ps); - ps.setNotification(false); - ps.setOpen(false); - boolean exists = partnerMapper.existsByUrl(linkApplyReq.getUrl()); - if (!exists) { - partnerMapper.insert(ps); - } else { - ps.setId(partnerMapper.findByUrl(linkApplyReq.getUrl()).getId()); - } - SimpleMailMessage smm = new SimpleMailMessage(); - smm.setSubject("友链申请"); - smm.setText("有一条友链申请" + (exists ? ",已存在的友链链接" : "") + ",[\n" + linkApplyReq.toString() + "\n]"); - smm.setTo(SITE_EMAIL); - smm.setSentDate(new Date()); - mailService.send(smm); - } else { - // 不包含站点 - String uuid; - ObjectMapper mapper = new ObjectMapper(); - if (redisUtil.hasKey(linkApplyReq.getUrl())) { - uuid = redisUtil.get(linkApplyReq.getUrl()); - if (!redisUtil.hasKey(uuid)) { - redisUtil.setEx(uuid, mapper.writeValueAsString(linkApplyReq), 10, TimeUnit.MINUTES); - } - } else { - uuid = UUID.randomUUID().toString().replaceAll("-", ""); - redisUtil.setEx(uuid, mapper.writeValueAsString(linkApplyReq), 10, TimeUnit.MINUTES); - redisUtil.setEx(linkApplyReq.getUrl(), uuid, 10, TimeUnit.MINUTES); - } - throw new MyException(ResponseEnum.APPLY_LINK_NO_ADD_THIS_SITE, null, uuid); - } - return ps; - } - - @SneakyThrows - @Override - public String reapply(String key) { - if (!redisUtil.hasKey(key)) { - throw new MyException(ResponseEnum.DATA_EXPIRED); - } - String s = redisUtil.get(key); - ObjectMapper mapper = new ObjectMapper(); - LinkApplyReq linkApplyReq = mapper.readValue(s, LinkApplyReq.class); - if (linkApplyReq == null) { - throw new MyException(ResponseEnum.DATA_NOT_EXIST); - } - SimpleMailMessage smm = new SimpleMailMessage(); - smm.setSubject("友链申请"); - smm.setText("有一条未抓取到信息的友链申请,[\n" + linkApplyReq.toString() + "\n]"); - smm.setTo(SITE_EMAIL); - smm.setSentDate(new Date()); - mailService.send(smm); - redisUtil.delete(key); - redisUtil.delete(linkApplyReq.getUrl()); - return "success"; - } -} +package cn.celess.partnersite.serviceimpl; + +import cn.celess.common.enmu.ResponseEnum; +import cn.celess.common.entity.PartnerSite; +import cn.celess.common.entity.dto.LinkApplyReq; +import cn.celess.common.entity.dto.LinkReq; +import cn.celess.common.entity.vo.PageData; +import cn.celess.common.exception.MyException; +import cn.celess.common.mapper.PartnerMapper; +import cn.celess.common.service.MailService; +import cn.celess.common.service.PartnerSiteService; +import cn.celess.common.util.HttpUtil; +import cn.celess.common.util.RedisUtil; +import cn.celess.common.util.RegexUtil; +import com.alibaba.druid.util.StringUtils; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.pagehelper.PageHelper; +import com.github.pagehelper.PageInfo; +import lombok.SneakyThrows; +import org.springframework.beans.BeanUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.mail.SimpleMailMessage; +import org.springframework.stereotype.Service; + +import java.util.Date; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +/** + * @author : xiaohai + * @date : 2019/05/12 11:43 + */ +@Service +public class PartnerSiteServiceImpl implements PartnerSiteService { + @Autowired + PartnerMapper partnerMapper; + @Autowired + MailService mailService; + @Autowired + RedisUtil redisUtil; + private static final String SITE_NAME = "小海博客"; + private static final String SITE_URL = "celess.cn"; + private static final String SITE_EMAIL = "a@celess.cn"; + + @Override + public PartnerSite create(LinkReq reqBody) { + if (reqBody == null) { + throw new MyException(ResponseEnum.PARAMETERS_ERROR); + } + //判空 + if (reqBody.getName() == null || reqBody.getUrl() == null) { + throw new MyException(ResponseEnum.PARAMETERS_ERROR); + } + //判空 + if (reqBody.getName().replaceAll(" ", "").isEmpty() || reqBody.getUrl().replaceAll(" ", "").isEmpty()) { + throw new MyException(ResponseEnum.PARAMETERS_ERROR); + } + //是否存在 同名 + if (partnerMapper.existsByName(reqBody.getName())) { + throw new MyException(ResponseEnum.DATA_HAS_EXIST); + } + //url是否合法 + if (!RegexUtil.urlMatch(reqBody.getUrl())) { + throw new MyException(ResponseEnum.PARAMETERS_URL_ERROR); + } + PartnerSite partnerSite = new PartnerSite(); + reqBody.setId(0); + if (!reqBody.getUrl().contains("http://") && !reqBody.getUrl().contains("https://")) { + reqBody.setUrl("http://" + reqBody.getUrl()); + } + BeanUtils.copyProperties(reqBody, partnerSite); + if (reqBody.getIconPath() == null) { + partnerSite.setIconPath(""); + } + if (reqBody.getDesc() == null) { + partnerSite.setDesc(""); + } + partnerMapper.insert(partnerSite); + return partnerSite; + } + + @Override + public Boolean del(long id) { + //判断数据是否存在 + if (!partnerMapper.existsById(id)) { + throw new MyException(ResponseEnum.DATA_NOT_EXIST); + } + return partnerMapper.delete(id) == 1; + } + + @Override + public PartnerSite update(LinkReq reqBody) { + PartnerSite partnerSite = partnerMapper.findById(reqBody.getId()); + if (partnerSite == null) { + throw new MyException(ResponseEnum.DATA_NOT_EXIST); + } + if (partnerMapper.existsByName(reqBody.getName()) && !reqBody.getName().equals(partnerSite.getName())) { + throw new MyException(ResponseEnum.DATA_HAS_EXIST); + } + if (!RegexUtil.urlMatch(reqBody.getUrl())) { + throw new MyException(ResponseEnum.PARAMETERS_URL_ERROR); + } + if (!reqBody.getUrl().contains("http://") && !reqBody.getUrl().contains("https://")) { + reqBody.setUrl("http://" + reqBody.getUrl()); + } + if (reqBody.isOpen() != partnerSite.getOpen() && !partnerSite.getNotification() && !StringUtils.isEmpty(partnerSite.getEmail())) { + SimpleMailMessage smm = new SimpleMailMessage(); + smm.setTo(partnerSite.getEmail()); + smm.setText("您的友链申请,已通过"); + smm.setSubject("友链申请通过"); + smm.setSentDate(new Date()); + mailService.send(smm); + partnerSite.setNotification(true); + } + BeanUtils.copyProperties(reqBody, partnerSite); + partnerMapper.update(partnerSite); + partnerSite.setName(reqBody.getName()); + partnerSite.setUrl(reqBody.getUrl()); + partnerSite.setOpen(reqBody.isOpen()); + + return partnerSite; + } + + @Override + public PageData partnerSitePages(int page, int count, Boolean deleted) { + PageHelper.startPage(page, count); + List sitePage = partnerMapper.findAll(deleted); + PageInfo pageInfo = new PageInfo(sitePage); + return new PageData<>(pageInfo, sitePage); + } + + @Override + public List findAll() { + List all = partnerMapper.findAll(); + all.forEach(partnerSite -> partnerSite.setDelete(null)); + return all; + } + + @SneakyThrows + @Override + public PartnerSite apply(LinkApplyReq linkApplyReq) { + // 空值字段 + if (StringUtils.isEmpty(linkApplyReq.getName()) + || StringUtils.isEmpty(linkApplyReq.getUrl()) + || StringUtils.isEmpty(linkApplyReq.getEmail()) + || StringUtils.isEmpty(linkApplyReq.getLinkUrl())) { + throw new MyException(ResponseEnum.PARAMETERS_ERROR); + } + // 链接不合法 + if (!RegexUtil.emailMatch(linkApplyReq.getEmail())) { + throw new MyException(ResponseEnum.PARAMETERS_EMAIL_ERROR); + } + if (!RegexUtil.urlMatch(linkApplyReq.getLinkUrl()) || !RegexUtil.urlMatch(linkApplyReq.getUrl())) { + throw new MyException(ResponseEnum.PARAMETERS_URL_ERROR); + } + if (!StringUtils.isEmpty(linkApplyReq.getIconPath()) && !RegexUtil.urlMatch(linkApplyReq.getIconPath())) { + throw new MyException(ResponseEnum.PARAMETERS_URL_ERROR); + } + // 非强制字段 设置空 + if (StringUtils.isEmpty(linkApplyReq.getIconPath())) { + linkApplyReq.setIconPath(""); + } + // 抓取页面 + String resp = HttpUtil.getAfterRendering(linkApplyReq.getLinkUrl()); + if (resp == null) { + throw new MyException(ResponseEnum.CANNOT_GET_DATA); + } + PartnerSite ps = new PartnerSite(); + if (resp.contains(SITE_URL)) { + //包含站点 + BeanUtils.copyProperties(linkApplyReq, ps); + ps.setNotification(false); + ps.setOpen(false); + boolean exists = partnerMapper.existsByUrl(linkApplyReq.getUrl()); + if (!exists) { + partnerMapper.insert(ps); + } else { + ps.setId(partnerMapper.findByUrl(linkApplyReq.getUrl()).getId()); + } + SimpleMailMessage smm = new SimpleMailMessage(); + smm.setSubject("友链申请"); + smm.setText("有一条友链申请" + (exists ? ",已存在的友链链接" : "") + ",[\n" + linkApplyReq + "\n]"); + smm.setTo(SITE_EMAIL); + smm.setSentDate(new Date()); + mailService.send(smm); + } else { + // 不包含站点 + String uuid; + ObjectMapper mapper = new ObjectMapper(); + if (redisUtil.hasKey(linkApplyReq.getUrl())) { + uuid = redisUtil.get(linkApplyReq.getUrl()); + if (!redisUtil.hasKey(uuid)) { + redisUtil.setEx(uuid, mapper.writeValueAsString(linkApplyReq), 10, TimeUnit.MINUTES); + } + } else { + uuid = UUID.randomUUID().toString().replaceAll("-", ""); + redisUtil.setEx(uuid, mapper.writeValueAsString(linkApplyReq), 10, TimeUnit.MINUTES); + redisUtil.setEx(linkApplyReq.getUrl(), uuid, 10, TimeUnit.MINUTES); + } + throw new MyException(ResponseEnum.APPLY_LINK_NO_ADD_THIS_SITE, null, uuid); + } + return ps; + } + + @SneakyThrows + @Override + public String reapply(String key) { + if (!redisUtil.hasKey(key)) { + throw new MyException(ResponseEnum.DATA_EXPIRED); + } + String s = redisUtil.get(key); + ObjectMapper mapper = new ObjectMapper(); + LinkApplyReq linkApplyReq = mapper.readValue(s, LinkApplyReq.class); + if (linkApplyReq == null) { + throw new MyException(ResponseEnum.DATA_NOT_EXIST); + } + SimpleMailMessage smm = new SimpleMailMessage(); + smm.setSubject("友链申请"); + smm.setText("有一条未抓取到信息的友链申请,[\n" + linkApplyReq + "\n]"); + smm.setTo(SITE_EMAIL); + smm.setSentDate(new Date()); + mailService.send(smm); + redisUtil.delete(key); + redisUtil.delete(linkApplyReq.getUrl()); + return "success"; + } +} diff --git a/blog-siteinfo/pom.xml b/blog-siteinfo/pom.xml new file mode 100644 index 0000000..0770e81 --- /dev/null +++ b/blog-siteinfo/pom.xml @@ -0,0 +1,30 @@ + + + + blog + cn.celess + 0.0.1-SNAPSHOT + + 4.0.0 + + blog-siteinfo + + + 13 + 13 + + + + cn.celess + blog-common + ${blog-common.version} + + + + org.springframework.boot + spring-boot-starter-web + + + \ No newline at end of file diff --git a/src/main/java/cn/celess/blog/controller/WebUpdateInfoController.java b/blog-siteinfo/src/main/java/cn/celess/siteinfo/controller/WebUpdateInfoController.java similarity index 88% rename from src/main/java/cn/celess/blog/controller/WebUpdateInfoController.java rename to blog-siteinfo/src/main/java/cn/celess/siteinfo/controller/WebUpdateInfoController.java index 03e4baa..9cf2b83 100644 --- a/src/main/java/cn/celess/blog/controller/WebUpdateInfoController.java +++ b/blog-siteinfo/src/main/java/cn/celess/siteinfo/controller/WebUpdateInfoController.java @@ -1,48 +1,48 @@ -package cn.celess.blog.controller; - -import cn.celess.blog.entity.Response; -import cn.celess.blog.service.WebUpdateInfoService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.*; - -/** - * @author : xiaohai - * @date : 2019/05/12 13:09 - */ -@RestController -public class WebUpdateInfoController { - @Autowired - WebUpdateInfoService webUpdateInfoService; - - @PostMapping("/admin/webUpdate/create") - public Response create(@RequestParam("info") String info) { - return Response.success(webUpdateInfoService.create(info)); - } - - @DeleteMapping("/admin/webUpdate/del/{id}") - public Response del(@PathVariable("id") long id) { - return Response.success(webUpdateInfoService.del(id)); - } - - @PutMapping("/admin/webUpdate/update") - public Response update(@RequestParam("id") long id, @RequestParam("info") String info) { - return Response.success(webUpdateInfoService.update(id, info)); - } - - @GetMapping("/webUpdate") - public Response findAll() { - return Response.success(webUpdateInfoService.findAll()); - } - - @GetMapping("/webUpdate/pages") - public Response page(@RequestParam("page") int page, @RequestParam("count") int count) { - return Response.success(webUpdateInfoService.pages(count, page)); - } - - @GetMapping("/lastestUpdate") - public Response lastestUpdateTime() { - return Response.success(webUpdateInfoService.getLastestUpdateTime()); - } - - -} +package cn.celess.siteinfo.controller; + +import cn.celess.common.entity.Response; +import cn.celess.common.service.WebUpdateInfoService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +/** + * @author : xiaohai + * @date : 2019/05/12 13:09 + */ +@RestController +public class WebUpdateInfoController { + @Autowired + WebUpdateInfoService webUpdateInfoService; + + @PostMapping("/admin/webUpdate/create") + public Response create(@RequestParam("info") String info) { + return Response.success(webUpdateInfoService.create(info)); + } + + @DeleteMapping("/admin/webUpdate/del/{id}") + public Response del(@PathVariable("id") long id) { + return Response.success(webUpdateInfoService.del(id)); + } + + @PutMapping("/admin/webUpdate/update") + public Response update(@RequestParam("id") long id, @RequestParam("info") String info) { + return Response.success(webUpdateInfoService.update(id, info)); + } + + @GetMapping("/webUpdate") + public Response findAll() { + return Response.success(webUpdateInfoService.findAll()); + } + + @GetMapping("/webUpdate/pages") + public Response page(@RequestParam("page") int page, @RequestParam("count") int count) { + return Response.success(webUpdateInfoService.pages(count, page)); + } + + @GetMapping("/lastestUpdate") + public Response lastestUpdateTime() { + return Response.success(webUpdateInfoService.getLastestUpdateTime()); + } + + +} diff --git a/src/main/java/cn/celess/blog/service/serviceimpl/WebUpdateInfoServiceImpl.java b/blog-siteinfo/src/main/java/cn/celess/siteinfo/serviceimpl/WebUpdateInfoServiceImpl.java similarity index 88% rename from src/main/java/cn/celess/blog/service/serviceimpl/WebUpdateInfoServiceImpl.java rename to blog-siteinfo/src/main/java/cn/celess/siteinfo/serviceimpl/WebUpdateInfoServiceImpl.java index 44240e6..dff34d4 100644 --- a/src/main/java/cn/celess/blog/service/serviceimpl/WebUpdateInfoServiceImpl.java +++ b/blog-siteinfo/src/main/java/cn/celess/siteinfo/serviceimpl/WebUpdateInfoServiceImpl.java @@ -1,15 +1,15 @@ -package cn.celess.blog.service.serviceimpl; +package cn.celess.siteinfo.serviceimpl; -import cn.celess.blog.enmu.ResponseEnum; -import cn.celess.blog.entity.WebUpdate; -import cn.celess.blog.entity.model.PageData; -import cn.celess.blog.entity.model.WebUpdateModel; -import cn.celess.blog.exception.MyException; -import cn.celess.blog.mapper.WebUpdateInfoMapper; -import cn.celess.blog.service.WebUpdateInfoService; -import cn.celess.blog.util.DateFormatUtil; -import cn.celess.blog.util.HttpUtil; -import cn.celess.blog.util.ModalTrans; +import cn.celess.common.enmu.ResponseEnum; +import cn.celess.common.entity.WebUpdate; +import cn.celess.common.entity.vo.PageData; +import cn.celess.common.entity.vo.WebUpdateModel; +import cn.celess.common.exception.MyException; +import cn.celess.common.mapper.WebUpdateInfoMapper; +import cn.celess.common.service.WebUpdateInfoService; +import cn.celess.common.util.DateFormatUtil; +import cn.celess.common.util.HttpUtil; +import cn.celess.common.util.ModalTrans; import com.alibaba.druid.util.StringUtils; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; diff --git a/blog-user/pom.xml b/blog-user/pom.xml new file mode 100644 index 0000000..8dff103 --- /dev/null +++ b/blog-user/pom.xml @@ -0,0 +1,37 @@ + + + + blog + cn.celess + 0.0.1-SNAPSHOT + + 4.0.0 + + blog-user + + + 13 + 13 + + + + cn.celess + blog-common + ${blog-common.version} + + + + org.springframework.boot + spring-boot-starter-web + + + + + io.jsonwebtoken + jjwt + 0.9.1 + + + \ No newline at end of file diff --git a/src/main/java/cn/celess/blog/controller/UserController.java b/blog-user/src/main/java/cn/celess/user/controller/UserController.java similarity index 88% rename from src/main/java/cn/celess/blog/controller/UserController.java rename to blog-user/src/main/java/cn/celess/user/controller/UserController.java index 5bbe04d..ade6b71 100644 --- a/src/main/java/cn/celess/blog/controller/UserController.java +++ b/blog-user/src/main/java/cn/celess/user/controller/UserController.java @@ -1,129 +1,129 @@ -package cn.celess.blog.controller; - -import cn.celess.blog.entity.Response; -import cn.celess.blog.entity.request.LoginReq; -import cn.celess.blog.entity.request.UserReq; -import cn.celess.blog.service.UserService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.*; -import org.springframework.web.multipart.MultipartFile; - -import java.io.IOException; - -/** - * @author : xiaohai - * @date : 2019/03/30 20:37 - */ -@RestController -public class UserController { - @Autowired - UserService userService; - - - @PostMapping("/login") - public Response login(@RequestBody LoginReq loginReq) { - return Response.success(userService.login(loginReq)); - } - - @PostMapping("/registration") - public Response registration(@RequestParam("email") String email, - @RequestParam("password") String password) { - return Response.success(userService.registration(email, password)); - } - - @GetMapping("/logout") - public Response logout() { - return Response.success(userService.logout()); - } - - @PutMapping("/user/userInfo/update") - public Response updateInfo(String desc, String displayName) { - return Response.success(userService.update(desc, displayName)); - } - - @GetMapping("/user/userInfo") - public Response getUserInfo() { - return Response.success(userService.getUserInfoBySession()); - } - - /** - * 更新头像 - * - * @param file file - * @return - * @throws IOException - */ - @PostMapping("/user/imgUpload") - @ResponseBody - public Response upload(@RequestParam("file") MultipartFile file) throws IOException { - if (file.isEmpty()) { - return Response.failure("上传失败,请选择文件"); - } - String fileName = file.getOriginalFilename(); - String mime = fileName.substring(fileName.lastIndexOf(".")); - if (".png".equals(mime.toLowerCase()) || ".jpg".equals(mime.toLowerCase()) || - ".jpeg".equals(mime.toLowerCase()) || ".bmp".equals(mime.toLowerCase())) { - return (Response) userService.updateUserAavatarImg(file.getInputStream(), mime); - } - return Response.failure("请上传图片文件"); - } - - @PostMapping("/sendResetPwdEmail") - public Response sendResetPwdEmail(@RequestParam("email") String email) { - return Response.success(userService.sendResetPwdEmail(email)); - } - - @PostMapping("/sendVerifyEmail") - public Response sendVerifyEmail(@RequestParam("email") String email) { - return Response.success(userService.sendVerifyEmail(email)); - } - - - @PostMapping("/emailVerify") - public Response emailVerify(@RequestParam("verifyId") String verifyId, - @RequestParam("email") String mail) { - return Response.success(userService.verifyEmail(verifyId, mail)); - } - - @PostMapping("/resetPwd") - public Response resetPwd(@RequestParam("verifyId") String verifyId, - @RequestParam("email") String email, - @RequestParam("pwd") String pwd) { - return Response.success(userService.reSetPwd(verifyId, email, pwd)); - } - - @PostMapping("/user/setPwd") - public Response setPwd(@RequestParam("pwd") String pwd, - @RequestParam("newPwd") String newPwd, - @RequestParam("confirmPwd") String confirmPwd) { - return Response.success(userService.setPwd(pwd, newPwd, confirmPwd)); - } - - - @DeleteMapping("/admin/user/delete") - public Response multipleDelete(@RequestBody Integer[] ids) { - return Response.success(userService.deleteUser(ids)); - } - - @DeleteMapping("/admin/user/delete/{id}") - public Response delete(@PathVariable("id") Integer id) { - return Response.success(userService.deleteUser(new Integer[]{id})); - } - - @PutMapping("/admin/user") - public Response updateInfoByAdmin(@RequestBody UserReq user) { - return Response.success(userService.adminUpdate(user)); - } - - @GetMapping("/admin/users") - public Response getAllUser(@RequestParam("page") int pageNum, @RequestParam("count") int count, @RequestParam(name = "status", required = false) Integer status) { - return Response.success(userService.getUserList(pageNum, count, status)); - } - - @GetMapping("/emailStatus/{email}") - public Response getEmailStatus(@PathVariable("email") String email) { - return Response.success(userService.getStatusOfEmail(email)); - } - - -} +package cn.celess.user.controller; + +import cn.celess.common.entity.Response; +import cn.celess.common.entity.dto.LoginReq; +import cn.celess.common.entity.dto.UserReq; +import cn.celess.common.service.UserService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +import java.io.IOException; + +/** + * @author : xiaohai + * @date : 2019/03/30 20:37 + */ +@RestController +public class UserController { + @Autowired + UserService userService; + + + @PostMapping("/login") + public Response login(@RequestBody LoginReq loginReq) { + return Response.success(userService.login(loginReq)); + } + + @PostMapping("/registration") + public Response registration(@RequestParam("email") String email, + @RequestParam("password") String password) { + return Response.success(userService.registration(email, password)); + } + + @GetMapping("/logout") + public Response logout() { + return Response.success(userService.logout()); + } + + @PutMapping("/user/userInfo/update") + public Response updateInfo(String desc, String displayName) { + return Response.success(userService.update(desc, displayName)); + } + + @GetMapping("/user/userInfo") + public Response getUserInfo() { + return Response.success(userService.getUserInfoBySession()); + } + + /** + * 更新头像 + * + * @param file file + * @return + * @throws IOException + */ + @PostMapping("/user/imgUpload") + @ResponseBody + public Response upload(@RequestParam("file") MultipartFile file) throws IOException { + if (file.isEmpty()) { + return Response.failure("上传失败,请选择文件"); + } + String fileName = file.getOriginalFilename(); + String mime = fileName.substring(fileName.lastIndexOf(".")); + if (".png".equalsIgnoreCase(mime) || ".jpg".equalsIgnoreCase(mime) || + ".jpeg".equalsIgnoreCase(mime) || ".bmp".equalsIgnoreCase(mime)) { + return (Response) userService.updateUserAavatarImg(file.getInputStream(), mime); + } + return Response.failure("请上传图片文件"); + } + + @PostMapping("/sendResetPwdEmail") + public Response sendResetPwdEmail(@RequestParam("email") String email) { + return Response.success(userService.sendResetPwdEmail(email)); + } + + @PostMapping("/sendVerifyEmail") + public Response sendVerifyEmail(@RequestParam("email") String email) { + return Response.success(userService.sendVerifyEmail(email)); + } + + + @PostMapping("/emailVerify") + public Response emailVerify(@RequestParam("verifyId") String verifyId, + @RequestParam("email") String mail) { + return Response.success(userService.verifyEmail(verifyId, mail)); + } + + @PostMapping("/resetPwd") + public Response resetPwd(@RequestParam("verifyId") String verifyId, + @RequestParam("email") String email, + @RequestParam("pwd") String pwd) { + return Response.success(userService.reSetPwd(verifyId, email, pwd)); + } + + @PostMapping("/user/setPwd") + public Response setPwd(@RequestParam("pwd") String pwd, + @RequestParam("newPwd") String newPwd, + @RequestParam("confirmPwd") String confirmPwd) { + return Response.success(userService.setPwd(pwd, newPwd, confirmPwd)); + } + + + @DeleteMapping("/admin/user/delete") + public Response multipleDelete(@RequestBody Integer[] ids) { + return Response.success(userService.deleteUser(ids)); + } + + @DeleteMapping("/admin/user/delete/{id}") + public Response delete(@PathVariable("id") Integer id) { + return Response.success(userService.deleteUser(new Integer[]{id})); + } + + @PutMapping("/admin/user") + public Response updateInfoByAdmin(@RequestBody UserReq user) { + return Response.success(userService.adminUpdate(user)); + } + + @GetMapping("/admin/users") + public Response getAllUser(@RequestParam("page") int pageNum, @RequestParam("count") int count, @RequestParam(name = "status", required = false) Integer status) { + return Response.success(userService.getUserList(pageNum, count, status)); + } + + @GetMapping("/emailStatus/{email}") + public Response getEmailStatus(@PathVariable("email") String email) { + return Response.success(userService.getStatusOfEmail(email)); + } + + +} diff --git a/src/main/java/cn/celess/blog/service/serviceimpl/UserServiceImpl.java b/blog-user/src/main/java/cn/celess/user/serviceimpl/UserServiceImpl.java similarity index 93% rename from src/main/java/cn/celess/blog/service/serviceimpl/UserServiceImpl.java rename to blog-user/src/main/java/cn/celess/user/serviceimpl/UserServiceImpl.java index 1cae19c..bde3d0d 100644 --- a/src/main/java/cn/celess/blog/service/serviceimpl/UserServiceImpl.java +++ b/blog-user/src/main/java/cn/celess/user/serviceimpl/UserServiceImpl.java @@ -1,423 +1,428 @@ -package cn.celess.blog.service.serviceimpl; - -import cn.celess.blog.enmu.ResponseEnum; -import cn.celess.blog.enmu.RoleEnum; -import cn.celess.blog.enmu.UserAccountStatusEnum; -import cn.celess.blog.entity.Response; -import cn.celess.blog.entity.User; -import cn.celess.blog.entity.model.PageData; -import cn.celess.blog.entity.model.QiniuResponse; -import cn.celess.blog.entity.model.UserModel; -import cn.celess.blog.entity.request.LoginReq; -import cn.celess.blog.entity.request.UserReq; -import cn.celess.blog.exception.MyException; -import cn.celess.blog.mapper.UserMapper; -import cn.celess.blog.service.MailService; -import cn.celess.blog.service.QiniuService; -import cn.celess.blog.service.UserService; -import cn.celess.blog.util.*; -import com.github.pagehelper.PageHelper; -import com.github.pagehelper.PageInfo; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.mail.SimpleMailMessage; -import org.springframework.stereotype.Service; - -import javax.servlet.http.HttpServletRequest; -import java.beans.Transient; -import java.io.InputStream; -import java.util.*; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; - -/** - * @author : xiaohai - * @date : 2019/03/30 18:41 - */ -@Service -public class UserServiceImpl implements UserService { - private final static Logger logger = LoggerFactory.getLogger(UserServiceImpl.class); - - @Autowired - UserMapper userMapper; - @Autowired - HttpServletRequest request; - @Autowired - MailService mailService; - @Autowired - QiniuService qiniuService; - @Autowired - RedisUtil redisUtil; - @Autowired - JwtUtil jwtUtil; - @Autowired - RedisUserUtil redisUserUtil; - - @Override - @Transient - public Boolean registration(String email, String password) { - if (password.length() < 6 || password.length() > 16) { - throw new MyException(ResponseEnum.PASSWORD_TOO_SHORT_OR_LONG); - } - if (!RegexUtil.emailMatch(email)) { - throw new MyException(ResponseEnum.PARAMETERS_EMAIL_ERROR); - } - if (!RegexUtil.pwdMatch(password)) { - throw new MyException(ResponseEnum.PARAMETERS_PWD_ERROR); - } - //验证码验证状态 - Boolean verifyStatus = (Boolean) request.getSession().getAttribute("verImgCodeStatus"); - if (verifyStatus == null || !verifyStatus) { - throw new MyException(ResponseEnum.IMG_CODE_DIDNOTVERIFY); - } - if (userMapper.existsByEmail(email)) { - throw new MyException(ResponseEnum.USERNAME_HAS_EXIST); - } - User user = new User(email, MD5Util.getMD5(password)); - boolean b = userMapper.addUser(user) == 1; - if (b) { - String verifyId = UUID.randomUUID().toString().replaceAll("-", ""); - redisUtil.setEx(email + "-verify", verifyId, 2, TimeUnit.DAYS); - SimpleMailMessage mailMessage = new SimpleMailMessage(); - mailMessage.setTo(email); - mailMessage.setSubject("邮箱验证"); - mailMessage.setText("欢迎注册小海博客,点击下面链接进行邮箱验证:\n https://www.celess.cn/emailVerify?email=" + email + "&verifyId=" + - verifyId + "\n该链接两日内有效,若失效了,请登录后台进行重新激活。"); - mailService.send(mailMessage); - } - return b; - } - - @Override - public UserModel login(LoginReq loginReq) { - if (loginReq == null) { - throw new MyException(ResponseEnum.PARAMETERS_ERROR); - } - if (!RegexUtil.emailMatch(loginReq.getEmail())) { - throw new MyException(ResponseEnum.PARAMETERS_EMAIL_ERROR); - } - if (!RegexUtil.pwdMatch(loginReq.getPassword())) { - throw new MyException(ResponseEnum.PARAMETERS_PWD_ERROR); - } - - User user = userMapper.findByEmail(loginReq.getEmail()); - if (user == null) { - // 用户不存在 - throw new MyException(ResponseEnum.USER_NOT_EXIST); - } - if (user.getStatus() != UserAccountStatusEnum.NORMAL.getCode()) { - throw new MyException(ResponseEnum.CAN_NOT_USE, UserAccountStatusEnum.get(user.getStatus())); - } - - //获取redis缓存中登录失败次数 - String s = redisUtil.get(loginReq.getEmail() + "-passwordWrongTime"); - if (s != null) { - if (Integer.parseInt(s) == 5) { - throw new MyException(ResponseEnum.LOGIN_LATER, loginReq.getEmail()); - } - } - - String token; - // 密码比对 - if (user.getPwd().equals(MD5Util.getMD5(loginReq.getPassword()))) { - logger.info("====> {} 进行权限认证 状态:登录成功 <====", loginReq.getEmail()); - userMapper.updateLoginTime(loginReq.getEmail()); - redisUtil.delete(loginReq.getEmail() + "-passwordWrongTime"); - // redis 标记 - redisUserUtil.set(user, loginReq.getIsRememberMe()); - token = jwtUtil.generateToken(user, loginReq.getIsRememberMe()); - } else { - logger.info("====> {} 进行权限认证 状态:登录失败 <====", loginReq.getEmail()); - request.getSession().removeAttribute("code"); - //登录失败 - //设置登录失败的缓存 - if (s == null) { - redisUtil.setEx(loginReq.getEmail() + "-passwordWrongTime", "1", 2, TimeUnit.HOURS); - s = "0"; - } - int count = Integer.parseInt(s); - //登录次数++ - count++; - //更新登录失败的次数 - redisUtil.setEx(loginReq.getEmail() + "-passwordWrongTime", count + "", 2, TimeUnit.HOURS); - throw new MyException(ResponseEnum.LOGIN_FAILURE); - } - UserModel trans = ModalTrans.userFullInfo(user); - trans.setToken(token); - return trans; - - } - - @Override - public Object logout() { - String token = request.getHeader("Authorization"); - if (token == null || token.isEmpty()) { - return "注销登录成功"; - } - String email = jwtUtil.getUsernameFromToken(token); - if (redisUtil.hasKey(email + "-login")) { - redisUtil.delete(email + "-login"); - } - return "注销登录成功"; - } - - @Override - public UserModel update(String desc, String displayName) { - User user = redisUserUtil.get(); - user.setDesc(desc); - user.setDisplayName(displayName); - - userMapper.updateInfo(desc, displayName, user.getId()); - redisUserUtil.set(user); - return ModalTrans.userFullInfo(user); - } - - @Override - public String getUserRoleByEmail(String email) { - String role = userMapper.getRoleByEmail(email); - if (role == null) { - throw new MyException(ResponseEnum.USER_NOT_EXIST); - } - return role; - } - - @Override - public Object updateUserAavatarImg(InputStream is, String mime) { - User user = redisUserUtil.get(); - QiniuResponse upload = qiniuService.uploadFile(is, user.getEmail() + "_" + user.getId() + mime.toLowerCase()); - user.setAvatarImgUrl(upload.key); - userMapper.updateAvatarImgUrl(upload.key, user.getId()); - redisUserUtil.set(user); - return Response.success(user.getAvatarImgUrl()); - } - - @Override - public UserModel getUserInfoBySession() { - User user = redisUserUtil.get(); - return ModalTrans.userFullInfo(user); - } - - @Override - public boolean isExistOfEmail(String email) { - return userMapper.existsByEmail(email); - } - - /** - * 找回密码 - */ - @Override - public Object sendResetPwdEmail(String email) { - if (!RegexUtil.emailMatch(email)) { - throw new MyException(ResponseEnum.PARAMETERS_EMAIL_ERROR); - } - - User user = userMapper.findByEmail(email); - if (user == null) { - return "发送成功!"; - } - - if (!user.getEmailStatus()) { - throw new MyException(ResponseEnum.USEREMAIL_NOT_VERIFY); - } - - String verifyId = UUID.randomUUID().toString().replaceAll("-", ""); - - redisUtil.setEx(user.getEmail() + "-resetPwd", verifyId, 2, TimeUnit.DAYS); - - SimpleMailMessage mailMessage = new SimpleMailMessage(); - mailMessage.setTo(email); - mailMessage.setSubject("密码重置"); - mailMessage.setText("点击下面链接进行重置密码:\n https://www.celess.cn/resetPwd?email=" + email + "&verifyId=" + verifyId); - - mailService.send(mailMessage); - return "发送成功!"; - } - - @Override - public Object sendVerifyEmail(String email) { - if (!RegexUtil.emailMatch(email)) { - throw new MyException(ResponseEnum.PARAMETERS_EMAIL_ERROR); - } - - User user = userMapper.findByEmail(email); - if (user == null) { - return "发送成功!"; - } - - if (user.getEmailStatus()) { - return "已经验证过了!"; - } - - String verifyId = UUID.randomUUID().toString().replaceAll("-", ""); - - redisUtil.setEx(user.getEmail() + "-verify", verifyId, 2, TimeUnit.DAYS); - - SimpleMailMessage mailMessage = new SimpleMailMessage(); - mailMessage.setTo(email); - mailMessage.setSubject("邮箱验证"); - mailMessage.setText("点击下面链接进行邮箱验证:\n https://www.celess.cn/emailVerify?email=" + email + "&verifyId=" + verifyId); - mailService.send(mailMessage); - return "发送成功!"; - } - - @Override - public Object verifyEmail(String verifyId, String email) { - User user = userMapper.findByEmail(email); - if (user == null) { - throw new MyException(ResponseEnum.FAILURE); - } - if (user.getEmailStatus()) { - throw new MyException(ResponseEnum.FAILURE.getCode(), "邮箱已验证过了"); - } - String verifyIdFromCache = redisUtil.get(user.getEmail() + "-verify"); - if (verifyIdFromCache == null) { - throw new MyException(ResponseEnum.FAILURE.getCode(), "验证链接无效"); - } - if (verifyIdFromCache.equals(verifyId)) { - userMapper.updateEmailStatus(email, true); - redisUtil.delete(user.getEmail() + "-verify"); - user.setEmailStatus(true); - redisUserUtil.set(user); - return "验证成功"; - } else { - throw new MyException(ResponseEnum.FAILURE); - } - } - - @Override - public Object reSetPwd(String verifyId, String email, String pwd) { - User user = userMapper.findByEmail(email); - if (user == null) { - throw new MyException(ResponseEnum.USER_NOT_EXIST); - } - if (!RegexUtil.pwdMatch(pwd)) { - throw new MyException(ResponseEnum.PARAMETERS_PWD_ERROR); - } - if (!user.getEmailStatus()) { - throw new MyException(ResponseEnum.USEREMAIL_NOT_VERIFY); - } - String resetPwdIdFromCache = redisUtil.get(user.getEmail() + "-resetPwd"); - if (resetPwdIdFromCache == null) { - throw new MyException(ResponseEnum.FAILURE.getCode(), "请先获取重置密码的邮件"); - } - if (resetPwdIdFromCache.equals(verifyId)) { - if (MD5Util.getMD5(pwd).equals(user.getPwd())) { - throw new MyException(ResponseEnum.PWD_SAME); - } - userMapper.updatePwd(email, MD5Util.getMD5(pwd)); - redisUtil.delete(user.getEmail() + "-resetPwd"); - return "验证成功"; - } else { - throw new MyException(ResponseEnum.FAILURE.getCode(), "标识码不一致"); - } - } - - @Override - public Object deleteUser(Integer[] id) { - List> status = new ArrayList<>(); - if (id == null || id.length == 0) { - return null; - } - for (Integer integer : id) { - String role = userMapper.getRoleById(integer); - int deleteResult = 0; - Map deleteStatus = new HashMap<>(3); - deleteStatus.put("id", integer); - // 管理员账户不可删 - if ("admin".equals(role)) { - deleteStatus.put("msg", "用户为管理员,不可删除"); - deleteStatus.put("status", false); - status.add(deleteStatus); - logger.info("删除用户id为{}的用户,删除状态{}, 原因:用户为管理员,不可删除", integer, false); - continue; - } - // 非管理员账户 - deleteResult = userMapper.delete(integer); - deleteStatus.put("status", deleteResult == 1); - logger.info("删除用户id为{}的用户,删除状态{}", integer, deleteResult == 1); - if (deleteResult == 0) { - deleteStatus.put("msg", "用户不存在"); - } - status.add(deleteStatus); - } - return status; - } - - @Override - public PageData getUserList(Integer page, Integer count, Integer status) { - PageHelper.startPage(page, count); - List all = userMapper.findAll(status); - List modelList = all.stream().map(ModalTrans::userFullInfo).collect(Collectors.toList()); - return new PageData<>(PageInfo.of(all), modelList); - } - - @Override - public UserModel adminUpdate(UserReq userReq) { - if (userReq == null || userReq.getId() == null) { - throw new MyException(ResponseEnum.PARAMETERS_ERROR); - } - User user = userMapper.findById(userReq.getId()); - // 设置数据 - if (userReq.getDesc() != null) { - user.setDesc(userReq.getDesc()); - } - if (userReq.getDisplayName() != null) { - user.setDisplayName(userReq.getDisplayName()); - } - if (userReq.getEmailStatus() != null) { - user.setEmailStatus(userReq.getEmailStatus()); - } - if (userReq.getPwd() != null) { - if (userReq.getPwd().length() < 6 || userReq.getPwd().length() > 16) { - throw new MyException(ResponseEnum.PASSWORD_TOO_SHORT_OR_LONG); - } - if (!RegexUtil.pwdMatch(userReq.getPwd())) { - throw new MyException(ResponseEnum.PARAMETERS_PWD_ERROR); - } - user.setPwd(MD5Util.getMD5(userReq.getPwd())); - } - if (userReq.getRole() != null) { - if (RoleEnum.USER_ROLE.getRoleName().equals(userReq.getRole()) || RoleEnum.ADMIN_ROLE.getRoleName().equals(userReq.getRole())) { - user.setRole(userReq.getRole()); - } else { - throw new MyException(ResponseEnum.PARAMETERS_ERROR); - } - } - if (userReq.getEmail() != null) { - if (!RegexUtil.emailMatch(userReq.getEmail())) { - throw new MyException(ResponseEnum.PARAMETERS_EMAIL_ERROR); - } - user.setEmail(userReq.getEmail()); - } - // 数据写入 - int updateResult = userMapper.update(user); - if (updateResult == 0) { - throw new MyException(ResponseEnum.FAILURE); - } - if (redisUserUtil.get().getId().equals(userReq.getId())) { - redisUserUtil.set(user); - } - logger.info("修改了用户 [id={}] 的用户的资料", userReq.getId()); - return ModalTrans.userFullInfo(user); - } - - @Override - public boolean getStatusOfEmail(String email) { - return userMapper.existsByEmail(email); - } - - @Override - public UserModel setPwd(String pwd, String newPwd, String confirmPwd) { - User user = redisUserUtil.get(); - String pwd1 = userMapper.getPwd(user.getEmail()); - if (!MD5Util.getMD5(pwd).equals(pwd1)) { - throw new MyException(ResponseEnum.PWD_WRONG); - } - if (!newPwd.equals(confirmPwd)) { - throw new MyException(ResponseEnum.PWD_NOT_SAME); - } - userMapper.updatePwd(user.getEmail(), MD5Util.getMD5(newPwd)); - return ModalTrans.userFullInfo(userMapper.findByEmail(user.getEmail())); - } -} +package cn.celess.user.serviceimpl; + +import cn.celess.common.enmu.ResponseEnum; +import cn.celess.common.enmu.RoleEnum; +import cn.celess.common.enmu.UserAccountStatusEnum; +import cn.celess.common.entity.Response; +import cn.celess.common.entity.User; +import cn.celess.common.entity.dto.LoginReq; +import cn.celess.common.entity.dto.UserReq; +import cn.celess.common.entity.vo.PageData; +import cn.celess.common.entity.vo.QiniuResponse; +import cn.celess.common.entity.vo.UserModel; +import cn.celess.common.exception.MyException; +import cn.celess.common.mapper.UserMapper; +import cn.celess.common.service.MailService; +import cn.celess.common.service.QiniuService; +import cn.celess.common.service.UserService; +import cn.celess.common.util.MD5Util; +import cn.celess.common.util.ModalTrans; +import cn.celess.common.util.RedisUtil; +import cn.celess.common.util.RegexUtil; +import cn.celess.user.util.JwtUtil; +import cn.celess.user.util.RedisUserUtil; +import com.github.pagehelper.PageHelper; +import com.github.pagehelper.PageInfo; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.mail.SimpleMailMessage; +import org.springframework.stereotype.Service; + +import javax.servlet.http.HttpServletRequest; +import java.beans.Transient; +import java.io.InputStream; +import java.util.*; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; + +/** + * @author : xiaohai + * @date : 2019/03/30 18:41 + */ +@Service +public class UserServiceImpl implements UserService { + private final static Logger logger = LoggerFactory.getLogger(UserServiceImpl.class); + + @Autowired + UserMapper userMapper; + @Autowired + HttpServletRequest request; + @Autowired + MailService mailService; + @Autowired + QiniuService qiniuService; + @Autowired + RedisUtil redisUtil; + @Autowired + JwtUtil jwtUtil; + @Autowired + RedisUserUtil redisUserUtil; + + @Override + @Transient + public Boolean registration(String email, String password) { + if (password.length() < 6 || password.length() > 16) { + throw new MyException(ResponseEnum.PASSWORD_TOO_SHORT_OR_LONG); + } + if (!RegexUtil.emailMatch(email)) { + throw new MyException(ResponseEnum.PARAMETERS_EMAIL_ERROR); + } + if (!RegexUtil.pwdMatch(password)) { + throw new MyException(ResponseEnum.PARAMETERS_PWD_ERROR); + } + //验证码验证状态 + Boolean verifyStatus = (Boolean) request.getSession().getAttribute("verImgCodeStatus"); + if (verifyStatus == null || !verifyStatus) { + throw new MyException(ResponseEnum.IMG_CODE_DIDNOTVERIFY); + } + if (userMapper.existsByEmail(email)) { + throw new MyException(ResponseEnum.USERNAME_HAS_EXIST); + } + User user = new User(email, MD5Util.getMD5(password)); + boolean b = userMapper.addUser(user) == 1; + if (b) { + String verifyId = UUID.randomUUID().toString().replaceAll("-", ""); + redisUtil.setEx(email + "-verify", verifyId, 2, TimeUnit.DAYS); + SimpleMailMessage mailMessage = new SimpleMailMessage(); + mailMessage.setTo(email); + mailMessage.setSubject("邮箱验证"); + mailMessage.setText("欢迎注册小海博客,点击下面链接进行邮箱验证:\n https://www.celess.cn/emailVerify?email=" + email + "&verifyId=" + + verifyId + "\n该链接两日内有效,若失效了,请登录后台进行重新激活。"); + mailService.send(mailMessage); + } + return b; + } + + @Override + public UserModel login(LoginReq loginReq) { + if (loginReq == null) { + throw new MyException(ResponseEnum.PARAMETERS_ERROR); + } + if (!RegexUtil.emailMatch(loginReq.getEmail())) { + throw new MyException(ResponseEnum.PARAMETERS_EMAIL_ERROR); + } + if (!RegexUtil.pwdMatch(loginReq.getPassword())) { + throw new MyException(ResponseEnum.PARAMETERS_PWD_ERROR); + } + + User user = userMapper.findByEmail(loginReq.getEmail()); + if (user == null) { + // 用户不存在 + throw new MyException(ResponseEnum.USER_NOT_EXIST); + } + if (user.getStatus() != UserAccountStatusEnum.NORMAL.getCode()) { + throw new MyException(ResponseEnum.CAN_NOT_USE, UserAccountStatusEnum.get(user.getStatus())); + } + + //获取redis缓存中登录失败次数 + String s = redisUtil.get(loginReq.getEmail() + "-passwordWrongTime"); + if (s != null) { + if (Integer.parseInt(s) == 5) { + throw new MyException(ResponseEnum.LOGIN_LATER, loginReq.getEmail()); + } + } + + String token; + // 密码比对 + if (user.getPwd().equals(MD5Util.getMD5(loginReq.getPassword()))) { + logger.info("====> {} 进行权限认证 状态:登录成功 <====", loginReq.getEmail()); + userMapper.updateLoginTime(loginReq.getEmail()); + redisUtil.delete(loginReq.getEmail() + "-passwordWrongTime"); + // redis 标记 + redisUserUtil.set(user, loginReq.getIsRememberMe()); + token = jwtUtil.generateToken(user, loginReq.getIsRememberMe()); + } else { + logger.info("====> {} 进行权限认证 状态:登录失败 <====", loginReq.getEmail()); + request.getSession().removeAttribute("code"); + //登录失败 + //设置登录失败的缓存 + if (s == null) { + redisUtil.setEx(loginReq.getEmail() + "-passwordWrongTime", "1", 2, TimeUnit.HOURS); + s = "0"; + } + int count = Integer.parseInt(s); + //登录次数++ + count++; + //更新登录失败的次数 + redisUtil.setEx(loginReq.getEmail() + "-passwordWrongTime", count + "", 2, TimeUnit.HOURS); + throw new MyException(ResponseEnum.LOGIN_FAILURE); + } + UserModel trans = ModalTrans.userFullInfo(user); + trans.setToken(token); + return trans; + + } + + @Override + public Object logout() { + String token = request.getHeader("Authorization"); + if (token == null || token.isEmpty()) { + return "注销登录成功"; + } + String email = jwtUtil.getUsernameFromToken(token); + if (redisUtil.hasKey(email + "-login")) { + redisUtil.delete(email + "-login"); + } + return "注销登录成功"; + } + + @Override + public UserModel update(String desc, String displayName) { + User user = redisUserUtil.get(); + user.setDesc(desc); + user.setDisplayName(displayName); + + userMapper.updateInfo(desc, displayName, user.getId()); + redisUserUtil.set(user); + return ModalTrans.userFullInfo(user); + } + + @Override + public String getUserRoleByEmail(String email) { + String role = userMapper.getRoleByEmail(email); + if (role == null) { + throw new MyException(ResponseEnum.USER_NOT_EXIST); + } + return role; + } + + @Override + public Object updateUserAavatarImg(InputStream is, String mime) { + User user = redisUserUtil.get(); + QiniuResponse upload = qiniuService.uploadFile(is, user.getEmail() + "_" + user.getId() + mime.toLowerCase()); + user.setAvatarImgUrl(upload.key); + userMapper.updateAvatarImgUrl(upload.key, user.getId()); + redisUserUtil.set(user); + return Response.success(user.getAvatarImgUrl()); + } + + @Override + public UserModel getUserInfoBySession() { + User user = redisUserUtil.get(); + return ModalTrans.userFullInfo(user); + } + + @Override + public boolean isExistOfEmail(String email) { + return userMapper.existsByEmail(email); + } + + /** + * 找回密码 + */ + @Override + public Object sendResetPwdEmail(String email) { + if (!RegexUtil.emailMatch(email)) { + throw new MyException(ResponseEnum.PARAMETERS_EMAIL_ERROR); + } + + User user = userMapper.findByEmail(email); + if (user == null) { + return "发送成功!"; + } + + if (!user.getEmailStatus()) { + throw new MyException(ResponseEnum.USEREMAIL_NOT_VERIFY); + } + + String verifyId = UUID.randomUUID().toString().replaceAll("-", ""); + + redisUtil.setEx(user.getEmail() + "-resetPwd", verifyId, 2, TimeUnit.DAYS); + + SimpleMailMessage mailMessage = new SimpleMailMessage(); + mailMessage.setTo(email); + mailMessage.setSubject("密码重置"); + mailMessage.setText("点击下面链接进行重置密码:\n https://www.celess.cn/resetPwd?email=" + email + "&verifyId=" + verifyId); + + mailService.send(mailMessage); + return "发送成功!"; + } + + @Override + public Object sendVerifyEmail(String email) { + if (!RegexUtil.emailMatch(email)) { + throw new MyException(ResponseEnum.PARAMETERS_EMAIL_ERROR); + } + + User user = userMapper.findByEmail(email); + if (user == null) { + return "发送成功!"; + } + + if (user.getEmailStatus()) { + return "已经验证过了!"; + } + + String verifyId = UUID.randomUUID().toString().replaceAll("-", ""); + + redisUtil.setEx(user.getEmail() + "-verify", verifyId, 2, TimeUnit.DAYS); + + SimpleMailMessage mailMessage = new SimpleMailMessage(); + mailMessage.setTo(email); + mailMessage.setSubject("邮箱验证"); + mailMessage.setText("点击下面链接进行邮箱验证:\n https://www.celess.cn/emailVerify?email=" + email + "&verifyId=" + verifyId); + mailService.send(mailMessage); + return "发送成功!"; + } + + @Override + public Object verifyEmail(String verifyId, String email) { + User user = userMapper.findByEmail(email); + if (user == null) { + throw new MyException(ResponseEnum.FAILURE); + } + if (user.getEmailStatus()) { + throw new MyException(ResponseEnum.FAILURE.getCode(), "邮箱已验证过了"); + } + String verifyIdFromCache = redisUtil.get(user.getEmail() + "-verify"); + if (verifyIdFromCache == null) { + throw new MyException(ResponseEnum.FAILURE.getCode(), "验证链接无效"); + } + if (verifyIdFromCache.equals(verifyId)) { + userMapper.updateEmailStatus(email, true); + redisUtil.delete(user.getEmail() + "-verify"); + user.setEmailStatus(true); + redisUserUtil.set(user); + return "验证成功"; + } else { + throw new MyException(ResponseEnum.FAILURE); + } + } + + @Override + public Object reSetPwd(String verifyId, String email, String pwd) { + User user = userMapper.findByEmail(email); + if (user == null) { + throw new MyException(ResponseEnum.USER_NOT_EXIST); + } + if (!RegexUtil.pwdMatch(pwd)) { + throw new MyException(ResponseEnum.PARAMETERS_PWD_ERROR); + } + if (!user.getEmailStatus()) { + throw new MyException(ResponseEnum.USEREMAIL_NOT_VERIFY); + } + String resetPwdIdFromCache = redisUtil.get(user.getEmail() + "-resetPwd"); + if (resetPwdIdFromCache == null) { + throw new MyException(ResponseEnum.FAILURE.getCode(), "请先获取重置密码的邮件"); + } + if (resetPwdIdFromCache.equals(verifyId)) { + if (MD5Util.getMD5(pwd).equals(user.getPwd())) { + throw new MyException(ResponseEnum.PWD_SAME); + } + userMapper.updatePwd(email, MD5Util.getMD5(pwd)); + redisUtil.delete(user.getEmail() + "-resetPwd"); + return "验证成功"; + } else { + throw new MyException(ResponseEnum.FAILURE.getCode(), "标识码不一致"); + } + } + + @Override + public Object deleteUser(Integer[] id) { + List> status = new ArrayList<>(); + if (id == null || id.length == 0) { + return null; + } + for (Integer integer : id) { + String role = userMapper.getRoleById(integer); + int deleteResult = 0; + Map deleteStatus = new HashMap<>(3); + deleteStatus.put("id", integer); + // 管理员账户不可删 + if ("admin".equals(role)) { + deleteStatus.put("msg", "用户为管理员,不可删除"); + deleteStatus.put("status", false); + status.add(deleteStatus); + logger.info("删除用户id为{}的用户,删除状态{}, 原因:用户为管理员,不可删除", integer, false); + continue; + } + // 非管理员账户 + deleteResult = userMapper.delete(integer); + deleteStatus.put("status", deleteResult == 1); + logger.info("删除用户id为{}的用户,删除状态{}", integer, deleteResult == 1); + if (deleteResult == 0) { + deleteStatus.put("msg", "用户不存在"); + } + status.add(deleteStatus); + } + return status; + } + + @Override + public PageData getUserList(Integer page, Integer count, Integer status) { + PageHelper.startPage(page, count); + List all = userMapper.findAll(status); + List modelList = all.stream().map(ModalTrans::userFullInfo).collect(Collectors.toList()); + return new PageData<>(PageInfo.of(all), modelList); + } + + @Override + public UserModel adminUpdate(UserReq userReq) { + if (userReq == null || userReq.getId() == null) { + throw new MyException(ResponseEnum.PARAMETERS_ERROR); + } + User user = userMapper.findById(userReq.getId()); + // 设置数据 + if (userReq.getDesc() != null) { + user.setDesc(userReq.getDesc()); + } + if (userReq.getDisplayName() != null) { + user.setDisplayName(userReq.getDisplayName()); + } + if (userReq.getEmailStatus() != null) { + user.setEmailStatus(userReq.getEmailStatus()); + } + if (userReq.getPwd() != null) { + if (userReq.getPwd().length() < 6 || userReq.getPwd().length() > 16) { + throw new MyException(ResponseEnum.PASSWORD_TOO_SHORT_OR_LONG); + } + if (!RegexUtil.pwdMatch(userReq.getPwd())) { + throw new MyException(ResponseEnum.PARAMETERS_PWD_ERROR); + } + user.setPwd(MD5Util.getMD5(userReq.getPwd())); + } + if (userReq.getRole() != null) { + if (RoleEnum.USER_ROLE.getRoleName().equals(userReq.getRole()) || RoleEnum.ADMIN_ROLE.getRoleName().equals(userReq.getRole())) { + user.setRole(userReq.getRole()); + } else { + throw new MyException(ResponseEnum.PARAMETERS_ERROR); + } + } + if (userReq.getEmail() != null) { + if (!RegexUtil.emailMatch(userReq.getEmail())) { + throw new MyException(ResponseEnum.PARAMETERS_EMAIL_ERROR); + } + user.setEmail(userReq.getEmail()); + } + // 数据写入 + int updateResult = userMapper.update(user); + if (updateResult == 0) { + throw new MyException(ResponseEnum.FAILURE); + } + if (redisUserUtil.get().getId().equals(userReq.getId())) { + redisUserUtil.set(user); + } + logger.info("修改了用户 [id={}] 的用户的资料", userReq.getId()); + return ModalTrans.userFullInfo(user); + } + + @Override + public boolean getStatusOfEmail(String email) { + return userMapper.existsByEmail(email); + } + + @Override + public UserModel setPwd(String pwd, String newPwd, String confirmPwd) { + User user = redisUserUtil.get(); + String pwd1 = userMapper.getPwd(user.getEmail()); + if (!MD5Util.getMD5(pwd).equals(pwd1)) { + throw new MyException(ResponseEnum.PWD_WRONG); + } + if (!newPwd.equals(confirmPwd)) { + throw new MyException(ResponseEnum.PWD_NOT_SAME); + } + userMapper.updatePwd(user.getEmail(), MD5Util.getMD5(newPwd)); + return ModalTrans.userFullInfo(userMapper.findByEmail(user.getEmail())); + } +} diff --git a/src/main/java/cn/celess/blog/util/JwtUtil.java b/blog-user/src/main/java/cn/celess/user/util/JwtUtil.java similarity index 89% rename from src/main/java/cn/celess/blog/util/JwtUtil.java rename to blog-user/src/main/java/cn/celess/user/util/JwtUtil.java index 94b790c..5639404 100644 --- a/src/main/java/cn/celess/blog/util/JwtUtil.java +++ b/blog-user/src/main/java/cn/celess/user/util/JwtUtil.java @@ -1,117 +1,114 @@ -package cn.celess.blog.util; - -import cn.celess.blog.enmu.ResponseEnum; -import cn.celess.blog.entity.User; -import cn.celess.blog.exception.MyException; -import io.jsonwebtoken.*; -import lombok.extern.log4j.Log4j2; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Component; - -import java.time.Instant; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; - -/** - * @Author: 小海 - * @Date: 2019/11/16 11:26 - * @Description: JWT工具类 - */ -@Component -@Log4j2 -public class JwtUtil { - /** - * 5天(毫秒) - */ - public static final long EXPIRATION_LONG_TIME = 432000000; - /** - * 两小时(毫秒) - */ - public static final long EXPIRATION_SHORT_TIME = 7200000; - private static final String CLAIM_KEY_USERNAME = "sub"; - private static final String BEARER_PREFIX_UPPER = "Bearer"; - private static final String BEARER_PREFIX_LOWER = "bearer"; - /** - * JWT 秘钥需自行设置不可泄露 - */ - @Value("${jwt.secret}") - private String SECRET; - - public String generateToken(User user, boolean isRemember) { - Map claims = new HashMap<>(16); - claims.put(CLAIM_KEY_USERNAME, user.getEmail()); - - return Jwts.builder() - .setClaims(claims) - .setExpiration(new Date(Instant.now().toEpochMilli() + (isRemember ? EXPIRATION_LONG_TIME : EXPIRATION_SHORT_TIME))) - .signWith(SignatureAlgorithm.HS512, SECRET) - .compact(); - } - - public String updateTokenDate(String token) { - Claims claims = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(getJwtString(token)).getBody(); - return Jwts.builder() - .setClaims(claims) - .setExpiration(new Date(claims.getExpiration().getTime() + EXPIRATION_SHORT_TIME)) - .signWith(SignatureAlgorithm.HS512, SECRET) - .compact(); - } - - /** - * 获取token是否过期 - */ - public Boolean isTokenExpired(String token) { - Date expiration = getExpirationDateFromToken(getJwtString(token)); - return expiration == null || expiration.before(new Date()); - } - - /** - * 根据token获取username - */ - public String getUsernameFromToken(String token) { - Claims claims = getClaimsFromToken(getJwtString(token)); - return claims == null ? null : claims.getSubject(); - } - - /** - * 获取token的过期时间 - */ - public Date getExpirationDateFromToken(String token) { - Claims claims = getClaimsFromToken(getJwtString(token)); - return claims == null ? null : claims.getExpiration(); - } - - /** - * 解析JWT - */ - private Claims getClaimsFromToken(String token) { - Claims claims = null; - try { - claims = Jwts.parser() - .setSigningKey(SECRET) - .parseClaimsJws(getJwtString(token)) - .getBody(); - } catch (ExpiredJwtException e) { - log.info("JWT令牌过期"); - } catch (UnsupportedJwtException e) { - log.info("不支持的JWT令牌"); - throw new MyException(ResponseEnum.JWT_NOT_SUPPORT); - } catch (MalformedJwtException e) { - log.info("JWT令牌格式错误"); - throw new MyException(ResponseEnum.JWT_MALFORMED); - } catch (SignatureException e) { - log.info("JWT签名错误"); - throw new MyException(ResponseEnum.JWT_SIGNATURE); - } catch (IllegalArgumentException e) { - log.debug("JWT非法参数"); - } - return claims; - } - - private String getJwtString(String token) { - if (token == null) return token; - return token.replaceFirst(BEARER_PREFIX_UPPER, "").replace(BEARER_PREFIX_LOWER, ""); - } - -} +package cn.celess.user.util; + +import cn.celess.common.enmu.ResponseEnum; +import cn.celess.common.entity.User; +import cn.celess.common.exception.MyException; +import io.jsonwebtoken.*; +import lombok.extern.log4j.Log4j2; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import java.time.Instant; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +/** + * @Author: 小海 + * @Date: 2019/11/16 11:26 + * @Description: JWT工具类 + */ +@Component +@Log4j2 +public class JwtUtil { + /** + * 5天(毫秒) + */ + public static final long EXPIRATION_LONG_TIME = 432000000; + /** + * 两小时(毫秒) + */ + public static final long EXPIRATION_SHORT_TIME = 7200000; + private static final String CLAIM_KEY_USERNAME = "sub"; + private static final String BEARER_PREFIX_UPPER = "Bearer"; + private static final String BEARER_PREFIX_LOWER = "bearer"; + /** + * JWT 秘钥需自行设置不可泄露 + */ + @Value("${jwt.secret}") + private String SECRET; + + public String generateToken(User user, boolean isRemember) { + Map claims = new HashMap<>(16); + claims.put(CLAIM_KEY_USERNAME, user.getEmail()); + + return Jwts.builder() + .setClaims(claims) + .setExpiration(new Date(Instant.now().toEpochMilli() + (isRemember ? EXPIRATION_LONG_TIME : EXPIRATION_SHORT_TIME))) + .signWith(SignatureAlgorithm.HS512, SECRET) + .compact(); + } + + public String updateTokenDate(String token) { + Claims claims = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(getJwtString(token)).getBody(); + return Jwts.builder() + .setClaims(claims) + .setExpiration(new Date(claims.getExpiration().getTime() + EXPIRATION_SHORT_TIME)) + .signWith(SignatureAlgorithm.HS512, SECRET) + .compact(); + } + + /** + * 获取token是否过期 + */ + public Boolean isTokenExpired(String token) { + Date expiration = getExpirationDateFromToken(getJwtString(token)); + return expiration == null || expiration.before(new Date()); + } + + /** + * 根据token获取username + */ + public String getUsernameFromToken(String token) { + Claims claims = getClaimsFromToken(getJwtString(token)); + return claims == null ? null : claims.getSubject(); + } + + /** + * 获取token的过期时间 + */ + public Date getExpirationDateFromToken(String token) { + Claims claims = getClaimsFromToken(getJwtString(token)); + return claims == null ? null : claims.getExpiration(); + } + + /** + * 解析JWT + */ + private Claims getClaimsFromToken(String token) { + Claims claims = null; + try { + claims = Jwts.parser() + .setSigningKey(SECRET) + .parseClaimsJws(getJwtString(token)) + .getBody(); + } catch (ExpiredJwtException e) { + log.info("JWT令牌过期"); + } catch (UnsupportedJwtException e) { + log.info("不支持的JWT令牌"); + throw new MyException(ResponseEnum.JWT_NOT_SUPPORT); + } catch (MalformedJwtException e) { + log.info("JWT令牌格式错误"); + throw new MyException(ResponseEnum.JWT_MALFORMED); + } catch (IllegalArgumentException e) { + log.debug("JWT非法参数"); + } + return claims; + } + + private String getJwtString(String token) { + if (token == null) return token; + return token.replaceFirst(BEARER_PREFIX_UPPER, "").replace(BEARER_PREFIX_LOWER, ""); + } + +} diff --git a/src/main/java/cn/celess/blog/util/RedisUserUtil.java b/blog-user/src/main/java/cn/celess/user/util/RedisUserUtil.java similarity index 89% rename from src/main/java/cn/celess/blog/util/RedisUserUtil.java rename to blog-user/src/main/java/cn/celess/user/util/RedisUserUtil.java index 3233998..7c53a13 100644 --- a/src/main/java/cn/celess/blog/util/RedisUserUtil.java +++ b/blog-user/src/main/java/cn/celess/user/util/RedisUserUtil.java @@ -1,60 +1,61 @@ -package cn.celess.blog.util; - -import cn.celess.blog.enmu.ResponseEnum; -import cn.celess.blog.entity.User; -import cn.celess.blog.exception.MyException; -import com.fasterxml.jackson.databind.ObjectMapper; -import lombok.SneakyThrows; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import javax.servlet.http.HttpServletRequest; -import java.util.concurrent.TimeUnit; - -/** - * @author : xiaohai - * @date : 2019/03/08 15:06 - */ -@Component -public class RedisUserUtil { - @Autowired - RedisUtil redisUtil; - @Autowired - JwtUtil jwtUtil; - @Autowired - HttpServletRequest request; - - public User get() { - User user = getWithOutExc(); - if (user == null) { - throw new MyException(ResponseEnum.HAVE_NOT_LOG_IN); - } - return user; - } - - @SneakyThrows - public User getWithOutExc() { - String token = request.getHeader("Authorization"); - if (token == null || token.isEmpty()) { - return null; - } - String email = jwtUtil.getUsernameFromToken(token); - return new ObjectMapper().readValue(redisUtil.get(email + "-login"), User.class); - } - - @SneakyThrows - public User set(User user) { - Long expire = redisUtil.getExpire(user.getEmail() + "-login"); - redisUtil.setEx(user.getEmail() + "-login", new ObjectMapper().writeValueAsString(user), - expire > 0 ? expire : JwtUtil.EXPIRATION_SHORT_TIME, TimeUnit.MILLISECONDS); - return user; - } - - @SneakyThrows - public User set(User user, boolean isRemember) { - redisUtil.setEx(user.getEmail() + "-login", new ObjectMapper().writeValueAsString(user), - isRemember ? JwtUtil.EXPIRATION_LONG_TIME : JwtUtil.EXPIRATION_SHORT_TIME, TimeUnit.MILLISECONDS); - request.getSession().setAttribute("email", user.getEmail()); - return user; - } -} +package cn.celess.user.util; + +import cn.celess.common.enmu.ResponseEnum; +import cn.celess.common.entity.User; +import cn.celess.common.exception.MyException; +import cn.celess.common.util.RedisUtil; +import com.fasterxml.jackson.databind.ObjectMapper; +import lombok.SneakyThrows; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import javax.servlet.http.HttpServletRequest; +import java.util.concurrent.TimeUnit; + +/** + * @author : xiaohai + * @date : 2019/03/08 15:06 + */ +@Component +public class RedisUserUtil { + @Autowired + RedisUtil redisUtil; + @Autowired + JwtUtil jwtUtil; + @Autowired + HttpServletRequest request; + + public User get() { + User user = getWithOutExc(); + if (user == null) { + throw new MyException(ResponseEnum.HAVE_NOT_LOG_IN); + } + return user; + } + + @SneakyThrows + public User getWithOutExc() { + String token = request.getHeader("Authorization"); + if (token == null || token.isEmpty()) { + return null; + } + String email = jwtUtil.getUsernameFromToken(token); + return new ObjectMapper().readValue(redisUtil.get(email + "-login"), User.class); + } + + @SneakyThrows + public User set(User user) { + Long expire = redisUtil.getExpire(user.getEmail() + "-login"); + redisUtil.setEx(user.getEmail() + "-login", new ObjectMapper().writeValueAsString(user), + expire > 0 ? expire : JwtUtil.EXPIRATION_SHORT_TIME, TimeUnit.MILLISECONDS); + return user; + } + + @SneakyThrows + public User set(User user, boolean isRemember) { + redisUtil.setEx(user.getEmail() + "-login", new ObjectMapper().writeValueAsString(user), + isRemember ? JwtUtil.EXPIRATION_LONG_TIME : JwtUtil.EXPIRATION_SHORT_TIME, TimeUnit.MILLISECONDS); + request.getSession().setAttribute("email", user.getEmail()); + return user; + } +} diff --git a/blog-visitor/pom.xml b/blog-visitor/pom.xml new file mode 100644 index 0000000..06e35a2 --- /dev/null +++ b/blog-visitor/pom.xml @@ -0,0 +1,44 @@ + + + + blog + cn.celess + 0.0.1-SNAPSHOT + + 4.0.0 + + blog-visitor + + + 13 + 13 + + + + cn.celess + blog-common + ${blog-common.version} + + + + org.springframework.boot + spring-boot-starter-web + + + + + eu.bitwalker + UserAgentUtils + 1.21 + + + + + org.lionsoul + ip2region + 1.7.2 + + + \ No newline at end of file diff --git a/src/main/java/cn/celess/blog/controller/VisitorController.java b/blog-visitor/src/main/java/cn/celess/visitor/controller/VisitorController.java similarity index 88% rename from src/main/java/cn/celess/blog/controller/VisitorController.java rename to blog-visitor/src/main/java/cn/celess/visitor/controller/VisitorController.java index a0fdb00..407af11 100644 --- a/src/main/java/cn/celess/blog/controller/VisitorController.java +++ b/blog-visitor/src/main/java/cn/celess/visitor/controller/VisitorController.java @@ -1,59 +1,59 @@ -package cn.celess.blog.controller; - -import cn.celess.blog.entity.Response; -import cn.celess.blog.service.CountService; -import cn.celess.blog.service.VisitorService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.*; - -import javax.servlet.http.HttpServletRequest; - -/** - * @author : xiaohai - * @date : 2019/04/02 23:09 - */ -@RestController -public class VisitorController { - @Autowired - VisitorService visitorService; - @Autowired - CountService countService; - - @GetMapping("/visitor/count") - public Response getVisitorCount() { - return Response.success(countService.getVisitorCount()); - } - - @GetMapping("/admin/visitor/page") - public Response page(@RequestParam(value = "count", required = false, defaultValue = "10") int count, - @RequestParam(value = "page", required = false, defaultValue = "1") int page, - @RequestParam(value = "showLocation", required = false, defaultValue = "true") boolean showLocation) { - return Response.success(visitorService.visitorPage(page, count, showLocation)); - } - - @PostMapping("/visit") - public Response add(HttpServletRequest request) { - return Response.success(visitorService.addVisitor(request)); - } - - @GetMapping("/dayVisitCount") - public Response dayVisitCount() { - return Response.success(countService.getDayVisitCount()); - } - - @GetMapping("/ip/{ip}") - public Response ipLocation(@PathVariable("ip") String ip) { - return Response.success(visitorService.location(ip)); - } - - /** - * 获取本地访问者的ip - * - * @param request - * @return - */ - @GetMapping("/ip") - public Response getIp(HttpServletRequest request) { - return Response.success(request.getRemoteAddr()); - } -} +package cn.celess.visitor.controller; + +import cn.celess.common.entity.Response; +import cn.celess.common.service.CountService; +import cn.celess.common.service.VisitorService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; + +/** + * @author : xiaohai + * @date : 2019/04/02 23:09 + */ +@RestController +public class VisitorController { + @Autowired + VisitorService visitorService; + @Autowired + CountService countService; + + @GetMapping("/visitor/count") + public Response getVisitorCount() { + return Response.success(countService.getVisitorCount()); + } + + @GetMapping("/admin/visitor/page") + public Response page(@RequestParam(value = "count", required = false, defaultValue = "10") int count, + @RequestParam(value = "page", required = false, defaultValue = "1") int page, + @RequestParam(value = "showLocation", required = false, defaultValue = "true") boolean showLocation) { + return Response.success(visitorService.visitorPage(page, count, showLocation)); + } + + @PostMapping("/visit") + public Response add(HttpServletRequest request) { + return Response.success(visitorService.addVisitor(request)); + } + + @GetMapping("/dayVisitCount") + public Response dayVisitCount() { + return Response.success(countService.getDayVisitCount()); + } + + @GetMapping("/ip/{ip}") + public Response ipLocation(@PathVariable("ip") String ip) { + return Response.success(visitorService.location(ip)); + } + + /** + * 获取本地访问者的ip + * + * @param request + * @return + */ + @GetMapping("/ip") + public Response getIp(HttpServletRequest request) { + return Response.success(request.getRemoteAddr()); + } +} diff --git a/src/main/java/cn/celess/blog/service/serviceimpl/VisitorServiceImpl.java b/blog-visitor/src/main/java/cn/celess/visitor/serviceimpl/VisitorServiceImpl.java similarity index 83% rename from src/main/java/cn/celess/blog/service/serviceimpl/VisitorServiceImpl.java rename to blog-visitor/src/main/java/cn/celess/visitor/serviceimpl/VisitorServiceImpl.java index ee5e1a4..c8015be 100644 --- a/src/main/java/cn/celess/blog/service/serviceimpl/VisitorServiceImpl.java +++ b/blog-visitor/src/main/java/cn/celess/visitor/serviceimpl/VisitorServiceImpl.java @@ -1,159 +1,155 @@ -package cn.celess.blog.service.serviceimpl; - -import cn.celess.blog.enmu.ResponseEnum; -import cn.celess.blog.entity.Visitor; -import cn.celess.blog.entity.model.PageData; -import cn.celess.blog.entity.model.VisitorModel; -import cn.celess.blog.exception.MyException; -import cn.celess.blog.mapper.VisitorMapper; -import cn.celess.blog.service.VisitorService; -import cn.celess.blog.util.AddressUtil; -import cn.celess.blog.util.DateFormatUtil; -import cn.celess.blog.util.RedisUtil; -import com.github.pagehelper.PageHelper; -import com.github.pagehelper.PageInfo; -import eu.bitwalker.useragentutils.Browser; -import eu.bitwalker.useragentutils.OperatingSystem; -import eu.bitwalker.useragentutils.UserAgent; -import eu.bitwalker.useragentutils.Version; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.json.JsonParserFactory; -import org.springframework.stereotype.Service; - -import javax.servlet.http.HttpServletRequest; -import java.io.BufferedReader; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.net.HttpURLConnection; -import java.net.URL; -import java.time.LocalDateTime; -import java.time.temporal.ChronoUnit; -import java.util.*; -import java.util.concurrent.TimeUnit; - -/** - * @author : xiaohai - * @date : 2019/04/02 23:04 - */ -@Service -public class VisitorServiceImpl implements VisitorService { - @Autowired - VisitorMapper visitorMapper; - @Autowired - RedisUtil redisUtil; - - @Override - public String location(String ip) { - return getLocation(ip); - } - - @Override - public PageData visitorPage(int page, int count, boolean showLocation) { - PageHelper.startPage(page, count); - List visitorList = visitorMapper.findAll(); - return new PageData<>(new PageInfo<>(visitorList), list2List(visitorList, showLocation)); - } - - @Override - public VisitorModel addVisitor(HttpServletRequest request) { - //新session - if (!request.getSession().isNew()) { - return null; - } - if (isSpiderBot(request.getHeader("User-Agent"))) { - return null; - } - Visitor visitor = new Visitor(); - visitor.setIp(request.getRemoteAddr()); - visitor.setDate(new Date()); - visitor.setUa(request.getHeader("User-Agent")); - //记录当日的访问 - String dayVisitCount = redisUtil.get("dayVisitCount"); - - LocalDateTime midnight = LocalDateTime.now().plusDays(1).withHour(0).withMinute(0).withSecond(0).withNano(0); - long secondsLeftToday = ChronoUnit.SECONDS.between(LocalDateTime.now(), midnight); - if (dayVisitCount == null) { - redisUtil.setEx("dayVisitCount", "1", secondsLeftToday, TimeUnit.SECONDS); - } else { - int count = Integer.parseInt(dayVisitCount) + 1; - redisUtil.setEx("dayVisitCount", count + "", secondsLeftToday, TimeUnit.SECONDS); - } - if (visitorMapper.insert(visitor) == 0) { - throw new MyException(ResponseEnum.FAILURE); - } - return trans(visitor); - } - - - /** - * 数据修改 - * - * @return - */ - private List list2List(List visitorList, boolean showLocation) { - List visitorModelList = new ArrayList<>(); - for (Visitor v : visitorList) { - VisitorModel trans = trans(v); - if (showLocation) { - trans.setLocation(getLocation(v.getIp())); - } - visitorModelList.add(trans); - } - return visitorModelList; - } - - /*** - * 转化为model - * - * @param v - * @return - */ - private VisitorModel trans(Visitor v) { - UserAgent userAgent = UserAgent.parseUserAgentString(v.getUa()); - VisitorModel visitor = new VisitorModel(); - visitor.setId(v.getId()); - visitor.setDate(DateFormatUtil.get(v.getDate())); - visitor.setIp(v.getIp()); - Browser browser = userAgent.getBrowser(); - visitor.setBrowserName(browser == null ? "" : browser.getName()); - OperatingSystem operatingSystem = userAgent.getOperatingSystem(); - visitor.setOSName(operatingSystem == null ? "" : operatingSystem.getName()); - Version browserVersion = userAgent.getBrowserVersion(); - visitor.setBrowserVersion(browserVersion == null ? "" : browserVersion.getVersion()); - return visitor; - } - - /** - * 根据ua判断是不是爬虫 - * - * @param ua ua - * @return true:爬虫 false :不是爬虫 - */ - private boolean isSpiderBot(String ua) { - if (ua == null) { - return false; - } - //服务器端的缓存抓取 - if (ua.contains("https://github.com/prerender/prerender")) { - return true; - } - //搜索引擎得爬虫ua一般有链接 - if (ua.contains("http://")) { - return true; - } - //防止没有匹配到http - return ua.toLowerCase().contains("spider"); - } - - /** - * 获取ip的地址 - * - * @param ip - * @return - */ - private String getLocation(String ip) { - return AddressUtil.getCityInfo(ip); - } - - -} +package cn.celess.visitor.serviceimpl; + +import cn.celess.common.enmu.ResponseEnum; +import cn.celess.common.entity.Visitor; +import cn.celess.common.entity.vo.PageData; +import cn.celess.common.entity.vo.VisitorModel; +import cn.celess.common.exception.MyException; +import cn.celess.common.mapper.VisitorMapper; +import cn.celess.common.service.VisitorService; +import cn.celess.common.util.DateFormatUtil; +import cn.celess.common.util.RedisUtil; +import cn.celess.visitor.util.AddressUtil; +import com.github.pagehelper.PageHelper; +import com.github.pagehelper.PageInfo; +import eu.bitwalker.useragentutils.Browser; +import eu.bitwalker.useragentutils.OperatingSystem; +import eu.bitwalker.useragentutils.UserAgent; +import eu.bitwalker.useragentutils.Version; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import javax.servlet.http.HttpServletRequest; +import java.time.LocalDateTime; +import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.concurrent.TimeUnit; + +/** + * @author : xiaohai + * @date : 2019/04/02 23:04 + */ +@Service +public class VisitorServiceImpl implements VisitorService { + @Autowired + VisitorMapper visitorMapper; + @Autowired + RedisUtil redisUtil; + + @Override + public String location(String ip) { + return getLocation(ip); + } + + @Override + public PageData visitorPage(int page, int count, boolean showLocation) { + PageHelper.startPage(page, count); + List visitorList = visitorMapper.findAll(); + return new PageData<>(new PageInfo<>(visitorList), list2List(visitorList, showLocation)); + } + + @Override + public VisitorModel addVisitor(HttpServletRequest request) { + //新session + if (!request.getSession().isNew()) { + return null; + } + if (isSpiderBot(request.getHeader("User-Agent"))) { + return null; + } + Visitor visitor = new Visitor(); + visitor.setIp(request.getRemoteAddr()); + visitor.setDate(new Date()); + visitor.setUa(request.getHeader("User-Agent")); + //记录当日的访问 + String dayVisitCount = redisUtil.get("dayVisitCount"); + + LocalDateTime midnight = LocalDateTime.now().plusDays(1).withHour(0).withMinute(0).withSecond(0).withNano(0); + long secondsLeftToday = ChronoUnit.SECONDS.between(LocalDateTime.now(), midnight); + if (dayVisitCount == null) { + redisUtil.setEx("dayVisitCount", "1", secondsLeftToday, TimeUnit.SECONDS); + } else { + int count = Integer.parseInt(dayVisitCount) + 1; + redisUtil.setEx("dayVisitCount", count + "", secondsLeftToday, TimeUnit.SECONDS); + } + if (visitorMapper.insert(visitor) == 0) { + throw new MyException(ResponseEnum.FAILURE); + } + return trans(visitor); + } + + + /** + * 数据修改 + * + * @return + */ + private List list2List(List visitorList, boolean showLocation) { + List visitorModelList = new ArrayList<>(); + for (Visitor v : visitorList) { + VisitorModel trans = trans(v); + if (showLocation) { + trans.setLocation(getLocation(v.getIp())); + } + visitorModelList.add(trans); + } + return visitorModelList; + } + + /*** + * 转化为model + * + * @param v + * @return + */ + private VisitorModel trans(Visitor v) { + UserAgent userAgent = UserAgent.parseUserAgentString(v.getUa()); + VisitorModel visitor = new VisitorModel(); + visitor.setId(v.getId()); + visitor.setDate(DateFormatUtil.get(v.getDate())); + visitor.setIp(v.getIp()); + Browser browser = userAgent.getBrowser(); + visitor.setBrowserName(browser == null ? "" : browser.getName()); + OperatingSystem operatingSystem = userAgent.getOperatingSystem(); + visitor.setOSName(operatingSystem == null ? "" : operatingSystem.getName()); + Version browserVersion = userAgent.getBrowserVersion(); + visitor.setBrowserVersion(browserVersion == null ? "" : browserVersion.getVersion()); + return visitor; + } + + /** + * 根据ua判断是不是爬虫 + * + * @param ua ua + * @return true:爬虫 false :不是爬虫 + */ + private boolean isSpiderBot(String ua) { + if (ua == null) { + return false; + } + //服务器端的缓存抓取 + if (ua.contains("https://github.com/prerender/prerender")) { + return true; + } + //搜索引擎得爬虫ua一般有链接 + if (ua.contains("http://")) { + return true; + } + //防止没有匹配到http + return ua.toLowerCase().contains("spider"); + } + + /** + * 获取ip的地址 + * + * @param ip + * @return + */ + private String getLocation(String ip) { + return AddressUtil.getCityInfo(ip); + } + + +} diff --git a/src/main/java/cn/celess/blog/util/AddressUtil.java b/blog-visitor/src/main/java/cn/celess/visitor/util/AddressUtil.java similarity index 88% rename from src/main/java/cn/celess/blog/util/AddressUtil.java rename to blog-visitor/src/main/java/cn/celess/visitor/util/AddressUtil.java index 2168e8c..46a9b5f 100644 --- a/src/main/java/cn/celess/blog/util/AddressUtil.java +++ b/blog-visitor/src/main/java/cn/celess/visitor/util/AddressUtil.java @@ -1,13 +1,14 @@ -package cn.celess.blog.util; +package cn.celess.visitor.util; import lombok.extern.slf4j.Slf4j; -import org.apache.commons.io.FileUtils; import org.lionsoul.ip2region.DataBlock; import org.lionsoul.ip2region.DbConfig; import org.lionsoul.ip2region.DbSearcher; import org.lionsoul.ip2region.Util; +import org.springframework.util.FileCopyUtils; import java.io.File; +import java.io.FileOutputStream; import java.lang.reflect.Method; import java.util.Objects; @@ -29,7 +30,7 @@ public class AddressUtil { String tmpDir = System.getProperties().getProperty("java.io.tmpdir"); dbPath = tmpDir + "ip.db"; file = new File(dbPath); - FileUtils.copyInputStreamToFile(Objects.requireNonNull(AddressUtil.class.getClassLoader().getResourceAsStream("classpath:ip2region/ip2region.db")), file); + FileCopyUtils.copy(Objects.requireNonNull(AddressUtil.class.getClassLoader().getResourceAsStream("classpath:ip2region/ip2region.db")), new FileOutputStream(file)); } //查询算法 //B-tree diff --git a/pom.xml b/pom.xml index 0d4205b..22c4b4a 100644 --- a/pom.xml +++ b/pom.xml @@ -2,6 +2,19 @@ 4.0.0 + pom + + blog-common + blog-article + blog-categorytag + blog-user + blog-comment + blog-partnersite + blog-visitor + blog-siteinfo + blog-extension + blog-deploy + org.springframework.boot spring-boot-starter-parent @@ -16,214 +29,31 @@ 1.8 + 0.0.1-SNAPSHOT + 0.0.1-SNAPSHOT + 0.0.1-SNAPSHOT + 0.0.1-SNAPSHOT + 0.0.1-SNAPSHOT + 0.0.1-SNAPSHOT + 0.0.1-SNAPSHOT + 0.0.1-SNAPSHOT + 0.0.1-SNAPSHOT - - - org.springframework.boot - spring-boot-starter-web - - - - mysql - mysql-connector-java - runtime - - - org.springframework.boot - spring-boot-starter-test - test - - - - - com.alibaba - druid - 1.2.6 - - org.projectlombok lombok 1.18.20 - - - - - io.springfox - springfox-swagger2 - 2.9.2 - - - com.github.xiaoymin - swagger-bootstrap-ui - 1.9.6 - - - - - com.youbenzi - MDTool - 1.2.4 - - - net.minidev - json-smart - 2.4.7 - compile - - - - - com.qiniu - qiniu-java-sdk - [7.2.0, 7.2.99] - - - - - org.springframework.boot - spring-boot-starter-mail - - - - - org.springframework.boot - spring-boot-starter-data-redis - - - - - org.mybatis.spring.boot - mybatis-spring-boot-starter - 2.2.0 - - - - - com.github.pagehelper - pagehelper-spring-boot-starter - 1.3.0 - - - - - com.dyuproject.protostuff - protostuff-core - 1.1.6 - - - com.dyuproject.protostuff - protostuff-runtime - 1.1.6 - - - - - eu.bitwalker - UserAgentUtils - 1.21 - - - - junit - junit - 4.13.1 - - - - - io.jsonwebtoken - jjwt - 0.9.1 - - - - - com.squareup.okhttp3 - okhttp - 4.9.1 - - - org.jetbrains.kotlin - kotlin-stdlib - 1.4.20 - compile - - - - - net.sourceforge.htmlunit - htmlunit - 2.45.0 - - - - - com.h2database - h2 - 1.4.200 - - - com.github.kstyrc - embedded-redis - 0.6 - test - - - - - javax.xml.bind - jaxb-api - 2.3.1 - - - com.sun.xml.bind - jaxb-impl - 3.0.0 - - - com.sun.xml.bind - jaxb-core - 2.3.0.1 - - - javax.activation - activation - 1.1.1 - - - - - org.lionsoul - ip2region - 1.7.2 - - - org.springframework.boot spring-boot-maven-plugin - - - org.jetbrains.kotlin - kotlin-maven-plugin - 1.5.10 - - - compile - process-sources - - compile - - - + 2.1.3.RELEASE