Compare commits

..

12 Commits

Author SHA1 Message Date
禾几海
6e12331e61 feat: 添加文件上传接口 2020-10-09 18:56:59 +08:00
禾几海
7e7332694e docs: typo 2020-09-07 12:28:07 +08:00
禾几海
8db690a55f Update issue templates 2020-09-07 12:23:44 +08:00
禾几海
0b40522e93 feat: 默认返回位置信息 2020-09-05 16:35:45 +08:00
禾几海
9026ba0732 refactor: 简化代码 2020-09-05 15:43:43 +08:00
禾几海
f5f2437fa4 refactor: 简化代码 2020-09-05 15:42:03 +08:00
禾几海
0bcca091e1 refactor: 简化代码 2020-09-04 13:02:36 +08:00
禾几海
3c69baa4ad Merge branch 'feature-ip2region' 2020-09-04 12:29:18 +08:00
禾几海
baf5b1bbb7 feat: 添加对jdk8以上环境的支持 2020-09-04 12:23:15 +08:00
禾几海
38621bcfa4 refactor: 换用ip2region 2020-09-04 12:11:14 +08:00
禾几海
cf435a588f refactor: 添加ip2region 2020-09-04 09:42:55 +08:00
禾几海
feab26f4f7 docs: add some badge 2020-09-01 08:30:26 +08:00
19 changed files with 315 additions and 150 deletions

38
.github/ISSUE_TEMPLATE/bug_report.md vendored Normal file
View File

@@ -0,0 +1,38 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Desktop (please complete the following information):**
- OS: [e.g. iOS]
- Browser [e.g. chrome, safari]
- Version [e.g. 22]
**Smartphone (please complete the following information):**
- Device: [e.g. iPhone6]
- OS: [e.g. iOS8.1]
- Browser [e.g. stock browser, safari]
- Version [e.g. 22]
**Additional context**
Add any other context about the problem here.

View File

@@ -8,7 +8,11 @@
[![Build](https://github.com/xiaohai2271/blog-backEnd/workflows/Build/badge.svg)](https://github.com/xiaohai2271/blog-backEnd) [![Build](https://github.com/xiaohai2271/blog-backEnd/workflows/Build/badge.svg)](https://github.com/xiaohai2271/blog-backEnd)
[![Test](https://github.com/xiaohai2271/blog-backEnd/workflows/Test/badge.svg)](https://github.com/xiaohai2271/blog-backEnd) [![Test](https://github.com/xiaohai2271/blog-backEnd/workflows/Test/badge.svg)](https://github.com/xiaohai2271/blog-backEnd)
[![GitHub tag (latest SemVer)](https://img.shields.io/github/v/tag/xiaohai2271/blog-backEnd)](https://github.com/xiaohai2271/blog-backEnd)
[![GitHub](https://img.shields.io/github/license/xiaohai2271/blog-backEnd)](https://github.com/xiaohai2271/blog-backEnd) [![GitHub](https://img.shields.io/github/license/xiaohai2271/blog-backEnd)](https://github.com/xiaohai2271/blog-backEnd)
[![GitHub top language](https://img.shields.io/github/languages/top/xiaohai2271/blog-backEnd)](https://github.com/xiaohai2271/blog-backEnd)
[![GitHub commit activity](https://img.shields.io/github/commit-activity/m/xiaohai2271/blog-backEnd)](https://github.com/xiaohai2271/blog-backEnd)
[![GitHub last commit](https://img.shields.io/github/last-commit/xiaohai2271/blog-backEnd)](https://github.com/xiaohai2271/blog-backEnd)
[![Website](https://img.shields.io/website?up_message=%E5%B0%8F%E6%B5%B7%E5%8D%9A%E5%AE%A2&url=https%3A%2F%2Fwww.celess.cn)](https://www.celess.cn) [![Website](https://img.shields.io/website?up_message=%E5%B0%8F%E6%B5%B7%E5%8D%9A%E5%AE%A2&url=https%3A%2F%2Fwww.celess.cn)](https://www.celess.cn)
</div> </div>

View File

@@ -9,7 +9,8 @@
### 2. 拉取项目到本地 ### 2. 拉取项目到本地
``` shell script ``` shell script
git clone https://github.com/xiaohai2271/blog-backEnd.git git clone https://github.com/xiaohai2271/blog-backEnd.git
git clone git@github.com:xiaohai2271/blog-backEnd.git #
git clone git@github.com:xiaohai2271/blog-backEnd.git
``` ```
### 3. maven构建 ### 3. maven构建
@@ -26,7 +27,7 @@ java -jar target/blog-0.0.1-SNAPSHOT.jar
```shell script ```shell script
mvn clean # 清理项目资源 mvn clean # 清理项目资源
mvn clean package # 清理项目资源并重新打包 mvn clean package # 清理项目资源并重新打包
mvn clean package -DskipTest # 清理项目资源,重新打包并跳过测试 mvn clean package -DskipTests # 清理项目资源,重新打包并跳过测试
mvn test # 运行测试 mvn test # 运行测试
..... #待添加 ..... #待添加
``` ```

28
pom.xml
View File

@@ -175,6 +175,34 @@
</dependency> </dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>org.lionsoul</groupId>
<artifactId>ip2region</artifactId>
<version>1.7.2</version>
</dependency>
</dependencies> </dependencies>
<build> <build>

View File

@@ -7,6 +7,7 @@ import cn.celess.blog.exception.MyException;
import cn.celess.blog.service.CountService; import cn.celess.blog.service.CountService;
import cn.celess.blog.service.QiniuService; import cn.celess.blog.service.QiniuService;
import cn.celess.blog.util.HttpUtil; import cn.celess.blog.util.HttpUtil;
import cn.celess.blog.util.RedisUserUtil;
import cn.celess.blog.util.RedisUtil; import cn.celess.blog.util.RedisUtil;
import cn.celess.blog.util.VeriCodeUtil; import cn.celess.blog.util.VeriCodeUtil;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
@@ -27,9 +28,7 @@ import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import java.util.Enumeration; import java.util.*;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
/** /**
@@ -47,7 +46,7 @@ public class CommonController {
@Autowired @Autowired
RedisUtil redisUtil; RedisUtil redisUtil;
@Autowired @Autowired
HttpServletRequest request; RedisUserUtil redisUserUtil;
@GetMapping("/counts") @GetMapping("/counts")
@@ -89,7 +88,7 @@ public class CommonController {
* @throws IOException IOException * @throws IOException IOException
*/ */
@GetMapping(value = "/imgCode", produces = MediaType.IMAGE_PNG_VALUE) @GetMapping(value = "/imgCode", produces = MediaType.IMAGE_PNG_VALUE)
public void getImg(HttpServletResponse response) throws IOException { public void getImg(HttpServletRequest request, HttpServletResponse response) throws IOException {
Object[] obj = VeriCodeUtil.createImage(); Object[] obj = VeriCodeUtil.createImage();
request.getSession().setAttribute("code", obj[0]); request.getSession().setAttribute("code", obj[0]);
//将图片输出给浏览器 //将图片输出给浏览器
@@ -133,9 +132,10 @@ public class CommonController {
* FIXME :: 单张图片多次上传的问题 * FIXME :: 单张图片多次上传的问题
* editor.md图片上传的接口 * editor.md图片上传的接口
* FUCK !!! * FUCK !!!
* * !! 推荐使用 fileUpload(/fileUpload) 接口
* @param file 文件 * @param file 文件
*/ */
@Deprecated
@PostMapping("/imgUpload") @PostMapping("/imgUpload")
public void upload(HttpServletRequest request, HttpServletResponse response, @RequestParam("editormd-image-file") MultipartFile file) throws IOException { public void upload(HttpServletRequest request, HttpServletResponse response, @RequestParam("editormd-image-file") MultipartFile file) throws IOException {
Map<String, Object> map = new HashMap<>(); Map<String, Object> map = new HashMap<>();
@@ -186,4 +186,37 @@ public class CommonController {
JsonNode images = root.get("images").elements().next(); JsonNode images = root.get("images").elements().next();
return Response.success("https://cn.bing.com" + images.get("url").asText()); return Response.success("https://cn.bing.com" + images.get("url").asText());
} }
@PostMapping("/fileUpload")
public Response<List<Map<String, Object>>> fileUpload(@RequestParam("file[]") MultipartFile[] files) throws IOException {
List<Map<String, Object>> result = new ArrayList<>();
String uploadTimesStr = redisUtil.get(redisUserUtil.get().getEmail() + "-fileUploadTimes");
int uploadTimes = 0;
if (uploadTimesStr != null) {
uploadTimes = Integer.parseInt(uploadTimesStr);
}
if (uploadTimes == 10) {
throw new MyException(ResponseEnum.FAILURE.getCode(), "上传次数已达10次请2小时后在上传");
}
if (files.length == 0) {
throw new MyException(ResponseEnum.NO_FILE);
}
for (MultipartFile file : files) {
Map<String, Object> resp = new HashMap<>(4);
String fileName = file.getOriginalFilename();
assert fileName != null;
String mime = fileName.substring(fileName.lastIndexOf("."));
String name = fileName.replace(mime, "").replaceAll(" ", "");
QiniuResponse qiniuResponse = qiniuService.uploadFile(file.getInputStream(), "file_" + name + '_' + System.currentTimeMillis() + mime);
resp.put("originalFilename", fileName);
resp.put("success", qiniuResponse != null);
if (qiniuResponse != null) {
resp.put("host", "http://cdn.celess.cn/");
resp.put("path", qiniuResponse.key);
}
result.add(resp);
}
return Response.success(result);
}
} }

View File

@@ -27,7 +27,7 @@ public class VisitorController {
@GetMapping("/admin/visitor/page") @GetMapping("/admin/visitor/page")
public Response page(@RequestParam(value = "count", required = false, defaultValue = "10") int count, public Response page(@RequestParam(value = "count", required = false, defaultValue = "10") int count,
@RequestParam(value = "page", required = false, defaultValue = "1") int page, @RequestParam(value = "page", required = false, defaultValue = "1") int page,
@RequestParam(value = "showLocation", required = false, defaultValue = "false") boolean showLocation) { @RequestParam(value = "showLocation", required = false, defaultValue = "true") boolean showLocation) {
return Response.success(visitorService.visitorPage(page, count, showLocation)); return Response.success(visitorService.visitorPage(page, count, showLocation));
} }

View File

@@ -62,6 +62,8 @@ public enum ResponseEnum {
APPLY_LINK_NO_ADD_THIS_SITE(7200, "暂未在您的网站中抓取到本站链接"), APPLY_LINK_NO_ADD_THIS_SITE(7200, "暂未在您的网站中抓取到本站链接"),
DATA_EXPIRED(7300, "数据过期"), DATA_EXPIRED(7300, "数据过期"),
CANNOT_GET_DATA(7400, "暂无法获取到数据"), CANNOT_GET_DATA(7400, "暂无法获取到数据"),
NO_FILE(7500, "未选择文件,请重新选择"),
//提交更新之前,没有获取数据/, //提交更新之前,没有获取数据/,
DID_NOT_GET_THE_DATA(8020, "非法访问"), DID_NOT_GET_THE_DATA(8020, "非法访问"),

View File

@@ -32,8 +32,8 @@ public class Response<T> implements Serializable {
* @param result 结果 * @param result 结果
* @return Response * @return Response
*/ */
public static Response success(Object result) { public static <T> Response<T> success(T result) {
return new Response(ResponseEnum.SUCCESS.getCode(), ResponseEnum.SUCCESS.getMsg(), result); return new Response<T>(ResponseEnum.SUCCESS.getCode(), ResponseEnum.SUCCESS.getMsg(), result);
} }
/** /**
@@ -42,8 +42,8 @@ public class Response<T> implements Serializable {
* @param result 结果 * @param result 结果
* @return Response * @return Response
*/ */
public static Response failure(String result) { public static Response<String> failure(String result) {
return new Response(ResponseEnum.FAILURE.getCode(), ResponseEnum.FAILURE.getMsg(), result); return new Response<String>(ResponseEnum.FAILURE.getCode(), ResponseEnum.FAILURE.getMsg(), result);
} }
/** /**
@@ -53,8 +53,8 @@ public class Response<T> implements Serializable {
* @param result 结果 * @param result 结果
* @return Response * @return Response
*/ */
public static Response response(ResponseEnum r, String result) { public static <T> Response<T> response(ResponseEnum r, T result) {
return new Response(r.getCode(), r.getMsg(), result); return new Response<T>(r.getCode(), r.getMsg(), result);
} }
@SneakyThrows @SneakyThrows

View File

@@ -304,16 +304,12 @@ public class ArticleServiceImpl implements ArticleService {
public PageData<ArticleModel> retrievePageForOpen(int count, int page) { public PageData<ArticleModel> retrievePageForOpen(int count, int page) {
PageHelper.startPage(page, count); PageHelper.startPage(page, count);
List<Article> articleList = articleMapper.findAllByOpen(true); List<Article> articleList = articleMapper.findAllByOpen(true);
PageData<ArticleModel> pageData = new PageData<>(new PageInfo<Article>(articleList)); PageData<ArticleModel> pageData = new PageData<>(new PageInfo<>(articleList));
List<ArticleModel> articleModelList = new ArrayList<>();
articleList.forEach(article -> {
ArticleModel model = ModalTrans.article(article, true);
setPreAndNextArticle(model);
articleModelList.add(model);
});
List<ArticleModel> articleModelList = articleList
.stream()
.map(article -> setPreAndNextArticle(ModalTrans.article(article, true)))
.collect(Collectors.toList());
pageData.setList(articleModelList); pageData.setList(articleModelList);
return pageData; return pageData;
} }
@@ -327,17 +323,14 @@ public class ArticleServiceImpl implements ArticleService {
PageHelper.startPage(page, count); PageHelper.startPage(page, count);
List<Article> open = articleMapper.findAllByCategoryIdAndOpen(category.getId()); List<Article> open = articleMapper.findAllByCategoryIdAndOpen(category.getId());
List<ArticleModel> modelList = new ArrayList<>(); List<ArticleModel> modelList = open.stream()
.map(article -> ModalTrans.article(article, true))
open.forEach(article -> { .peek(articleModel -> {
ArticleModel model = ModalTrans.article(article, true); articleModel.setNextArticle(null);
model.setTags(null); articleModel.setPreArticle(null);
// setPreAndNextArticle(model); })
model.setNextArticle(null); .collect(Collectors.toList());
model.setPreArticle(null); return new PageData<>(new PageInfo<>(open), modelList);
modelList.add(model);
});
return new PageData<ArticleModel>(new PageInfo<Article>(open), modelList);
} }
@Override @Override
@@ -348,21 +341,22 @@ public class ArticleServiceImpl implements ArticleService {
} }
PageHelper.startPage(page, count); PageHelper.startPage(page, count);
List<ArticleTag> articleByTag = articleTagMapper.findArticleByTagAndOpen(tag.getId()); List<ArticleTag> articleByTag = articleTagMapper.findArticleByTagAndOpen(tag.getId());
List<ArticleModel> modelList = new ArrayList<>(); List<ArticleModel> modelList = articleByTag
articleByTag.forEach(articleTag -> { .stream()
ArticleModel model = ModalTrans.article(articleTag.getArticle(), true); .map(articleTag -> ModalTrans.article(articleTag.getArticle(), true))
model.setNextArticle(null); .peek(articleModel -> {
model.setPreArticle(null); articleModel.setNextArticle(null);
modelList.add(model); articleModel.setPreArticle(null);
}); }).collect(Collectors.toList());
return new PageData<ArticleModel>(new PageInfo<ArticleTag>(articleByTag), modelList); return new PageData<>(new PageInfo<>(articleByTag), modelList);
} }
private void setPreAndNextArticle(ArticleModel articleModel) { private ArticleModel setPreAndNextArticle(ArticleModel articleModel) {
if (articleModel == null) { if (articleModel == null) {
return; return null;
} }
articleModel.setPreArticle(ModalTrans.article(articleMapper.getPreArticle(articleModel.getId()), true)); articleModel.setPreArticle(ModalTrans.article(articleMapper.getPreArticle(articleModel.getId()), true));
articleModel.setNextArticle(ModalTrans.article(articleMapper.getNextArticle(articleModel.getId()), true)); articleModel.setNextArticle(ModalTrans.article(articleMapper.getNextArticle(articleModel.getId()), true));
return articleModel;
} }
} }

View File

@@ -17,8 +17,8 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.stream.Collectors;
/** /**
* @author : xiaohai * @author : xiaohai
@@ -68,22 +68,25 @@ public class CategoryServiceImpl implements CategoryService {
public PageData<CategoryModel> retrievePage(int page, int count) { public PageData<CategoryModel> retrievePage(int page, int count) {
PageHelper.startPage(page, count); PageHelper.startPage(page, count);
List<Category> all = categoryMapper.findAll(); List<Category> all = categoryMapper.findAll();
List<CategoryModel> modelList = new ArrayList<>(); // 遍历没一个category
all.forEach(e -> { List<CategoryModel> modelList = all
CategoryModel model = ModalTrans.category(e); .stream()
List<Article> allByCategoryId = articleMapper.findAllByCategoryId(e.getId()); .map(ModalTrans::category)
List<ArticleModel> articleModelList = new ArrayList<>(); .peek(categoryModel -> {
allByCategoryId.forEach(article -> { // 根据category去查article并赋值给categoryModel
ArticleModel articleModel = ModalTrans.article(article, true); List<Article> allByCategoryId = articleMapper.findAllByCategoryId(categoryModel.getId());
articleModel.setPreArticle(null); List<ArticleModel> articleModelList = allByCategoryId
articleModel.setNextArticle(null); .stream()
articleModel.setTags(null); .map(article -> ModalTrans.article(article, true))
articleModelList.add(articleModel); .peek(articleModel -> {
}); // 去除不必要的字段
model.setArticles(articleModelList); articleModel.setPreArticle(null);
modelList.add(model); articleModel.setNextArticle(null);
}); articleModel.setTags(null);
})
return new PageData<CategoryModel>(new PageInfo<Category>(all), modelList); .collect(Collectors.toList());
categoryModel.setArticles(articleModelList);
}).collect(Collectors.toList());
return new PageData<>(new PageInfo<>(all), modelList);
} }
} }

View File

@@ -23,6 +23,7 @@ import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.stream.Collectors;
/** /**
* @author : xiaohai * @author : xiaohai
@@ -107,14 +108,11 @@ public class CommentServiceImpl implements CommentService {
@Override @Override
public List<CommentModel> retrievePageByPid(long pid) { public List<CommentModel> retrievePageByPid(long pid) {
List<Comment> allByPagePath = commentMapper.findAllByPid(pid); List<Comment> allByPagePath = commentMapper.findAllByPid(pid);
List<CommentModel> commentModels = new ArrayList<>(); return allByPagePath
allByPagePath.forEach(comment -> { .stream()
if (comment.getStatus() != CommentStatusEnum.DELETED.getCode()) { .filter(comment -> comment.getStatus() != CommentStatusEnum.DELETED.getCode())
commentModels.add(ModalTrans.comment(comment)); .map(ModalTrans::comment)
} .collect(Collectors.toList());
});
return commentModels;
} }
@Override @Override
@@ -145,14 +143,11 @@ public class CommentServiceImpl implements CommentService {
private PageData<CommentModel> pageTrans(List<Comment> commentList, boolean noResponseList) { private PageData<CommentModel> pageTrans(List<Comment> commentList, boolean noResponseList) {
PageInfo<Comment> p = PageInfo.of(commentList); PageInfo<Comment> p = PageInfo.of(commentList);
List<CommentModel> modelList = new ArrayList<>(); List<CommentModel> modelList = commentList
commentList.forEach(l -> { .stream()
CommentModel model = ModalTrans.comment(l); .map(ModalTrans::comment)
if (!noResponseList) { .peek(commentModel -> commentModel.setRespComment(this.retrievePageByPid(commentModel.getId())))
model.setRespComment(this.retrievePageByPid(model.getId())); .collect(Collectors.toList());
} return new PageData<>(p, modelList);
modelList.add(model);
});
return new PageData<CommentModel>(p, modelList);
} }
} }

View File

@@ -21,6 +21,7 @@ import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.stream.Collectors;
/** /**
* @author : xiaohai * @author : xiaohai
@@ -81,20 +82,22 @@ public class TagServiceImpl implements TagService {
List<Tag> tagList = tagMapper.findAll(); List<Tag> tagList = tagMapper.findAll();
List<TagModel> modelList = new ArrayList<>(); List<TagModel> modelList = new ArrayList<>();
tagList.forEach(tag -> modelList.add(ModalTrans.tag(tag))); tagList.forEach(tag -> modelList.add(ModalTrans.tag(tag)));
return new PageData<TagModel>(new PageInfo<Tag>(tagList), modelList); return new PageData<>(new PageInfo<>(tagList), modelList);
} }
@Override @Override
public List<TagModel> findAll() { public List<TagModel> findAll() {
List<TagModel> list = new ArrayList<>(); return tagMapper.findAll().stream()
tagMapper.findAll().forEach(e -> { .map(ModalTrans::tag)
TagModel model = ModalTrans.tag(e); .peek(tagModel -> {
List<ArticleTag> articleByTagAndOpen = articleTagMapper.findArticleByTagAndOpen(e.getId()); List<ArticleTag> articleByTagAndOpen = articleTagMapper.findArticleByTagAndOpen(tagModel.getId());
List<ArticleModel> articleModelList = new ArrayList<>(); tagModel.setArticles(
articleByTagAndOpen.forEach(articleTag -> articleModelList.add(ModalTrans.article(articleTag.getArticle(), true))); articleByTagAndOpen
model.setArticles(articleModelList); .stream()
list.add(model); .map(articleTag -> ModalTrans.article(articleTag.getArticle(), true))
}); .collect(Collectors.toList())
return list; );
})
.collect(Collectors.toList());
} }
} }

View File

@@ -7,6 +7,7 @@ import cn.celess.blog.entity.model.VisitorModel;
import cn.celess.blog.exception.MyException; import cn.celess.blog.exception.MyException;
import cn.celess.blog.mapper.VisitorMapper; import cn.celess.blog.mapper.VisitorMapper;
import cn.celess.blog.service.VisitorService; import cn.celess.blog.service.VisitorService;
import cn.celess.blog.util.AddressUtil;
import cn.celess.blog.util.DateFormatUtil; import cn.celess.blog.util.DateFormatUtil;
import cn.celess.blog.util.RedisUtil; import cn.celess.blog.util.RedisUtil;
import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageHelper;
@@ -50,7 +51,7 @@ public class VisitorServiceImpl implements VisitorService {
public PageData<VisitorModel> visitorPage(int page, int count, boolean showLocation) { public PageData<VisitorModel> visitorPage(int page, int count, boolean showLocation) {
PageHelper.startPage(page, count); PageHelper.startPage(page, count);
List<Visitor> visitorList = visitorMapper.findAll(); List<Visitor> visitorList = visitorMapper.findAll();
return new PageData<VisitorModel>(new PageInfo<Visitor>(visitorList), list2List(visitorList, showLocation)); return new PageData<>(new PageInfo<>(visitorList), list2List(visitorList, showLocation));
} }
@Override @Override
@@ -151,60 +152,7 @@ public class VisitorServiceImpl implements VisitorService {
* @return * @return
*/ */
private String getLocation(String ip) { private String getLocation(String ip) {
StringBuilder result = new StringBuilder(); return AddressUtil.getCityInfo(ip);
URL url;
HttpURLConnection conn = null;
InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader bufferedReader = null;
try {
url = new URL("http://ip.taobao.com/service/getIpInfo.php?ip=" + ip);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(3000);
conn.setDoInput(true);
conn.setRequestMethod("GET");
inputStream = conn.getInputStream();
inputStreamReader = new InputStreamReader(inputStream);
bufferedReader = new BufferedReader(inputStreamReader);
String tmp;
while ((tmp = bufferedReader.readLine()) != null) {
result.append(tmp);
}
} catch (Exception e) {
// ignore
} finally {
try {
if (conn != null) {
conn.disconnect();
}
if (inputStream != null) {
inputStream.close();
}
if (inputStreamReader != null) {
inputStreamReader.close();
}
if (bufferedReader != null) {
bufferedReader.close();
}
} catch (Exception e) {
// ignore
}
}
StringBuilder sb = new StringBuilder();
if ("".equals(result.toString())) {
throw new MyException(ResponseEnum.FAILURE);
}
Map<String, Object> stringObjectMap = JsonParserFactory.getJsonParser().parseMap(result.toString());
if ((Integer) stringObjectMap.get("code") == 0) {
LinkedHashMap data = (LinkedHashMap) stringObjectMap.get("data");
sb.append(data.get("country"))
.append("-")
.append(data.get("region"))
.append("-")
.append(data.get("city"));
}
return sb.toString();
} }

View File

@@ -22,6 +22,7 @@ import org.springframework.stereotype.Service;
import java.io.IOException; import java.io.IOException;
import java.time.Instant; import java.time.Instant;
import java.util.*; import java.util.*;
import java.util.stream.Collectors;
/** /**
* @author : xiaohai * @author : xiaohai
@@ -72,7 +73,7 @@ public class WebUpdateInfoServiceImpl implements WebUpdateInfoService {
public PageData<WebUpdateModel> pages(int count, int page) { public PageData<WebUpdateModel> pages(int count, int page) {
PageHelper.startPage(page, count); PageHelper.startPage(page, count);
List<WebUpdate> updateList = webUpdateInfoMapper.findAll(); List<WebUpdate> updateList = webUpdateInfoMapper.findAll();
return new PageData<WebUpdateModel>(new PageInfo<WebUpdate>(updateList), list2List(updateList)); return new PageData<>(new PageInfo<>(updateList), list2List(updateList));
} }
@Override @Override
@@ -108,8 +109,6 @@ public class WebUpdateInfoServiceImpl implements WebUpdateInfoService {
} }
private List<WebUpdateModel> list2List(List<WebUpdate> webUpdates) { private List<WebUpdateModel> list2List(List<WebUpdate> webUpdates) {
List<WebUpdateModel> webUpdateModels = new ArrayList<>(); return webUpdates.stream().map(ModalTrans::webUpdate).collect(Collectors.toList());
webUpdates.forEach(update -> webUpdateModels.add(ModalTrans.webUpdate(update)));
return webUpdateModels;
} }
} }

View File

@@ -0,0 +1,71 @@
package cn.celess.blog.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 java.io.File;
import java.lang.reflect.Method;
import java.util.Objects;
/**
* @author : xiaohai
* @date : 2020/09/04 9:36
*/
@Slf4j
public class AddressUtil {
public static String getCityInfo(String ip) {
File file;
try {
//db
String dbPath = AddressUtil.class.getResource("/ip2region/ip2region.db").getPath();
file = new File(dbPath);
if (!file.exists()) {
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);
}
//查询算法
//B-tree
int algorithm = DbSearcher.BTREE_ALGORITHM;
try {
DbConfig config = new DbConfig();
DbSearcher searcher = new DbSearcher(config, dbPath);
Method method = null;
switch (algorithm) {
case DbSearcher.BTREE_ALGORITHM:
method = searcher.getClass().getMethod("btreeSearch", String.class);
break;
case DbSearcher.BINARY_ALGORITHM:
method = searcher.getClass().getMethod("binarySearch", String.class);
break;
case DbSearcher.MEMORY_ALGORITYM:
method = searcher.getClass().getMethod("memorySearch", String.class);
break;
}
DataBlock dataBlock;
if (!Util.isIpAddress(ip)) {
System.out.println("Error: Invalid ip address");
}
dataBlock = (DataBlock) method.invoke(searcher, ip);
return dataBlock.getRegion();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}

Binary file not shown.

View File

@@ -31,6 +31,7 @@ public class VisitorControllerTest extends BaseTest {
public void page() throws Exception { public void page() throws Exception {
int count = 10; int count = 10;
int page = 1; int page = 1;
// 默认显示location
getMockData(get("/admin/visitor/page?count=" + count + "&page=" + page), adminLogin()).andDo(result -> { getMockData(get("/admin/visitor/page?count=" + count + "&page=" + page), adminLogin()).andDo(result -> {
Response<PageData<VisitorModel>> response = getResponse(result, VISITOR_PAGE_TYPE); Response<PageData<VisitorModel>> response = getResponse(result, VISITOR_PAGE_TYPE);
assertEquals(SUCCESS.getCode(), response.getCode()); assertEquals(SUCCESS.getCode(), response.getCode());
@@ -41,6 +42,7 @@ public class VisitorControllerTest extends BaseTest {
for (VisitorModel v : pageData.getList()) { for (VisitorModel v : pageData.getList()) {
assertNotEquals(0, v.getId()); assertNotEquals(0, v.getId());
assertNotNull(v.getDate()); assertNotNull(v.getDate());
assertNotNull(v.getLocation());
} }
}); });
} }

View File

@@ -0,0 +1,29 @@
package cn.celess.blog.service;
import cn.celess.blog.BaseTest;
import cn.celess.blog.entity.model.PageData;
import cn.celess.blog.entity.model.VisitorModel;
import com.alibaba.druid.util.StringUtils;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import static org.junit.Assert.*;
public class VisitorServiceTest extends BaseTest {
@Autowired
VisitorService visitorService;
@Test
public void location() {
assertEquals("0|0|0|内网IP|内网IP", visitorService.location("127.0.0.1"));
}
@Test
public void visitorPage() {
long start = System.currentTimeMillis();
PageData<VisitorModel> visitorModelPageData = visitorService.visitorPage(1, 10, true);
assertTrue(System.currentTimeMillis() - start <= 1500);
assertTrue(visitorModelPageData.getList().stream().noneMatch(visitor -> StringUtils.isEmpty(visitor.getLocation())));
}
}

View File

@@ -0,0 +1,15 @@
package cn.celess.blog.util;
import cn.celess.blog.BaseTest;
import org.junit.Test;
import static org.junit.Assert.*;
public class AddressUtilTest extends BaseTest {
@Test
public void getCityInfo() {
assertEquals("0|0|0|内网IP|内网IP", AddressUtil.getCityInfo("127.0.0.1"));
assertEquals("中国|0|上海|上海市|阿里云", AddressUtil.getCityInfo("106.15.205.190"));
}
}