🎨 代码优化

pull/73/head
ruibaby 2018-12-29 15:34:41 +08:00
parent 1d23670b5d
commit 09c6822640
57 changed files with 571 additions and 498 deletions

View File

@ -120,7 +120,7 @@ public class WebMvcAutoConfiguration implements WebMvcConfigurer {
*/ */
@Bean @Bean
public LocaleResolver localeResolver() { public LocaleResolver localeResolver() {
SessionLocaleResolver slr = new SessionLocaleResolver(); final SessionLocaleResolver slr = new SessionLocaleResolver();
slr.setDefaultLocale(Locale.CHINA); slr.setDefaultLocale(Locale.CHINA);
return slr; return slr;
} }
@ -132,7 +132,7 @@ public class WebMvcAutoConfiguration implements WebMvcConfigurer {
*/ */
@Bean @Bean
public LocaleChangeInterceptor localeChangeInterceptor() { public LocaleChangeInterceptor localeChangeInterceptor() {
LocaleChangeInterceptor lci = new LocaleChangeInterceptor(); final LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
lci.setParamName("lang"); lci.setParamName("lang");
return lci; return lci;
} }

View File

@ -56,7 +56,7 @@ public class StartedListener implements ApplicationListener<ApplicationStartedEv
* *
*/ */
private void loadActiveTheme() throws TemplateModelException { private void loadActiveTheme() throws TemplateModelException {
String themeValue = optionsService.findOneOption(BlogPropertiesEnum.THEME.getProp()); final String themeValue = optionsService.findOneOption(BlogPropertiesEnum.THEME.getProp());
if (StrUtil.isNotEmpty(themeValue) && !StrUtil.equals(themeValue, null)) { if (StrUtil.isNotEmpty(themeValue) && !StrUtil.equals(themeValue, null)) {
BaseController.THEME = themeValue; BaseController.THEME = themeValue;
} else { } else {
@ -70,7 +70,7 @@ public class StartedListener implements ApplicationListener<ApplicationStartedEv
* *
*/ */
private void loadOptions() { private void loadOptions() {
Map<String, String> options = optionsService.findAllOptions(); final Map<String, String> options = optionsService.findAllOptions();
if (options != null && !options.isEmpty()) { if (options != null && !options.isEmpty()) {
HaloConst.OPTIONS = options; HaloConst.OPTIONS = options;
} }
@ -81,7 +81,7 @@ public class StartedListener implements ApplicationListener<ApplicationStartedEv
*/ */
private void loadThemes() { private void loadThemes() {
HaloConst.THEMES.clear(); HaloConst.THEMES.clear();
List<Theme> themes = HaloUtils.getThemes(); final List<Theme> themes = HaloUtils.getThemes();
if (null != themes) { if (null != themes) {
HaloConst.THEMES = themes; HaloConst.THEMES = themes;
} }
@ -91,7 +91,7 @@ public class StartedListener implements ApplicationListener<ApplicationStartedEv
* OwO * OwO
*/ */
private void loadOwo() { private void loadOwo() {
Map<String, String> map = new HashMap<>(135); final Map<String, String> map = new HashMap<>(135);
map.put("@[nico]", "<img src='/static/halo-common/OwO/paopao/nico.png' alt='nico.png' style='vertical-align: middle;'>"); map.put("@[nico]", "<img src='/static/halo-common/OwO/paopao/nico.png' alt='nico.png' style='vertical-align: middle;'>");
map.put("@[OK]", "<img src='/static/halo-common/OwO/paopao/OK.png' alt='OK.png' style='vertical-align: middle;'>"); map.put("@[OK]", "<img src='/static/halo-common/OwO/paopao/OK.png' alt='OK.png' style='vertical-align: middle;'>");
map.put("@[what]", "<img src='/static/halo-common/OwO/paopao/what.png' alt='what.png' style='vertical-align: middle;'>"); map.put("@[what]", "<img src='/static/halo-common/OwO/paopao/what.png' alt='what.png' style='vertical-align: middle;'>");

View File

@ -29,7 +29,7 @@ public class ArticleTagDirective implements TemplateDirectiveModel {
@Override @Override
public void execute(Environment environment, Map map, TemplateModel[] templateModels, TemplateDirectiveBody templateDirectiveBody) throws TemplateException, IOException { public void execute(Environment environment, Map map, TemplateModel[] templateModels, TemplateDirectiveBody templateDirectiveBody) throws TemplateException, IOException {
DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_25); final DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_25);
if (map.containsKey(METHOD_KEY)) { if (map.containsKey(METHOD_KEY)) {
String method = map.get(METHOD_KEY).toString(); String method = map.get(METHOD_KEY).toString();
switch (method) { switch (method) {

View File

@ -39,7 +39,7 @@ public class CommonTagDirective implements TemplateDirectiveModel {
@Override @Override
public void execute(Environment environment, Map map, TemplateModel[] templateModels, TemplateDirectiveBody templateDirectiveBody) throws TemplateException, IOException { public void execute(Environment environment, Map map, TemplateModel[] templateModels, TemplateDirectiveBody templateDirectiveBody) throws TemplateException, IOException {
DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_25); final DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_25);
if (map.containsKey(METHOD_KEY)) { if (map.containsKey(METHOD_KEY)) {
String method = map.get(METHOD_KEY).toString(); String method = map.get(METHOD_KEY).toString();
switch (method) { switch (method) {

View File

@ -157,17 +157,17 @@ public class AttachmentServiceImpl implements AttachmentService {
*/ */
@Override @Override
public Map<String, String> attachUpload(MultipartFile file, HttpServletRequest request) { public Map<String, String> attachUpload(MultipartFile file, HttpServletRequest request) {
Map<String, String> resultMap = new HashMap<>(6); final Map<String, String> resultMap = new HashMap<>(6);
String dateString = DateUtil.format(DateUtil.date(), "yyyyMMddHHmmss"); final String dateString = DateUtil.format(DateUtil.date(), "yyyyMMddHHmmss");
try { try {
//用户目录 //用户目录
StrBuilder uploadPath = new StrBuilder(System.getProperties().getProperty("user.home")); final StrBuilder uploadPath = new StrBuilder(System.getProperties().getProperty("user.home"));
uploadPath.append("/halo/"); uploadPath.append("/halo/");
uploadPath.append("upload/"); uploadPath.append("upload/");
//获取当前年月以创建目录,如果没有该目录则创建 //获取当前年月以创建目录,如果没有该目录则创建
uploadPath.append(DateUtil.thisYear()).append("/").append(DateUtil.thisMonth()).append("/"); uploadPath.append(DateUtil.thisYear()).append("/").append(DateUtil.thisMonth()).append("/");
File mediaPath = new File(uploadPath.toString()); final File mediaPath = new File(uploadPath.toString());
if (!mediaPath.exists()) { if (!mediaPath.exists()) {
if (!mediaPath.mkdirs()) { if (!mediaPath.mkdirs()) {
resultMap.put("success", "0"); resultMap.put("success", "0");
@ -176,27 +176,27 @@ public class AttachmentServiceImpl implements AttachmentService {
} }
//不带后缀 //不带后缀
StrBuilder nameWithOutSuffix = new StrBuilder(file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf('.')).replaceAll(" ", "_").replaceAll(",", "")); final StrBuilder nameWithOutSuffix = new StrBuilder(file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf('.')).replaceAll(" ", "_").replaceAll(",", ""));
nameWithOutSuffix.append(dateString); nameWithOutSuffix.append(dateString);
nameWithOutSuffix.append(new Random().nextInt(1000)); nameWithOutSuffix.append(new Random().nextInt(1000));
//文件后缀 //文件后缀
String fileSuffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.') + 1); final String fileSuffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.') + 1);
//带后缀 //带后缀
StrBuilder fileName = new StrBuilder(nameWithOutSuffix); final StrBuilder fileName = new StrBuilder(nameWithOutSuffix);
fileName.append("."); fileName.append(".");
fileName.append(fileSuffix); fileName.append(fileSuffix);
file.transferTo(new File(mediaPath.getAbsoluteFile(), fileName.toString())); file.transferTo(new File(mediaPath.getAbsoluteFile(), fileName.toString()));
//文件原路径 //文件原路径
StrBuilder fullPath = new StrBuilder(mediaPath.getAbsolutePath()); final StrBuilder fullPath = new StrBuilder(mediaPath.getAbsolutePath());
fullPath.append("/"); fullPath.append("/");
fullPath.append(fileName); fullPath.append(fileName);
//压缩文件路径 //压缩文件路径
StrBuilder fullSmallPath = new StrBuilder(mediaPath.getAbsolutePath()); final StrBuilder fullSmallPath = new StrBuilder(mediaPath.getAbsolutePath());
fullSmallPath.append("/"); fullSmallPath.append("/");
fullSmallPath.append(nameWithOutSuffix); fullSmallPath.append(nameWithOutSuffix);
fullSmallPath.append("_small."); fullSmallPath.append("_small.");
@ -206,7 +206,7 @@ public class AttachmentServiceImpl implements AttachmentService {
Thumbnails.of(fullPath.toString()).size(256, 256).keepAspectRatio(false).toFile(fullSmallPath.toString()); Thumbnails.of(fullPath.toString()).size(256, 256).keepAspectRatio(false).toFile(fullSmallPath.toString());
//映射路径 //映射路径
StrBuilder filePath = new StrBuilder("/upload/"); final StrBuilder filePath = new StrBuilder("/upload/");
filePath.append(DateUtil.thisYear()); filePath.append(DateUtil.thisYear());
filePath.append("/"); filePath.append("/");
filePath.append(DateUtil.thisMonth()); filePath.append(DateUtil.thisMonth());
@ -214,7 +214,7 @@ public class AttachmentServiceImpl implements AttachmentService {
filePath.append(fileName); filePath.append(fileName);
//缩略图映射路径 //缩略图映射路径
StrBuilder fileSmallPath = new StrBuilder("/upload/"); final StrBuilder fileSmallPath = new StrBuilder("/upload/");
fileSmallPath.append(DateUtil.thisYear()); fileSmallPath.append(DateUtil.thisYear());
fileSmallPath.append("/"); fileSmallPath.append("/");
fileSmallPath.append(DateUtil.thisMonth()); fileSmallPath.append(DateUtil.thisMonth());
@ -223,8 +223,8 @@ public class AttachmentServiceImpl implements AttachmentService {
fileSmallPath.append("_small."); fileSmallPath.append("_small.");
fileSmallPath.append(fileSuffix); fileSmallPath.append(fileSuffix);
String size = HaloUtils.parseSize(new File(fullPath.toString()).length()); final String size = HaloUtils.parseSize(new File(fullPath.toString()).length());
String wh = HaloUtils.getImageWh(new File(fullPath.toString())); final String wh = HaloUtils.getImageWh(new File(fullPath.toString()));
resultMap.put("fileName", fileName.toString()); resultMap.put("fileName", fileName.toString());
resultMap.put("filePath", filePath.toString()); resultMap.put("filePath", filePath.toString());
@ -248,32 +248,32 @@ public class AttachmentServiceImpl implements AttachmentService {
*/ */
@Override @Override
public Map<String, String> attachQiNiuUpload(MultipartFile file, HttpServletRequest request) { public Map<String, String> attachQiNiuUpload(MultipartFile file, HttpServletRequest request) {
Map<String, String> resultMap = new HashMap<>(6); final Map<String, String> resultMap = new HashMap<>(6);
try { try {
Configuration cfg = new Configuration(Zone.zone0()); final Configuration cfg = new Configuration(Zone.zone0());
String key = Md5Util.getMD5Checksum(file); final String key = Md5Util.getMD5Checksum(file);
String accessKey = HaloConst.OPTIONS.get("qiniu_access_key"); final String accessKey = HaloConst.OPTIONS.get("qiniu_access_key");
String secretKey = HaloConst.OPTIONS.get("qiniu_secret_key"); final String secretKey = HaloConst.OPTIONS.get("qiniu_secret_key");
String domain = HaloConst.OPTIONS.get("qiniu_domain"); final String domain = HaloConst.OPTIONS.get("qiniu_domain");
String bucket = HaloConst.OPTIONS.get("qiniu_bucket"); final String bucket = HaloConst.OPTIONS.get("qiniu_bucket");
String smallUrl = HaloConst.OPTIONS.get("qiniu_small_url"); final String smallUrl = HaloConst.OPTIONS.get("qiniu_small_url");
if (StrUtil.isEmpty(accessKey) || StrUtil.isEmpty(secretKey) || StrUtil.isEmpty(domain) || StrUtil.isEmpty(bucket)) { if (StrUtil.isEmpty(accessKey) || StrUtil.isEmpty(secretKey) || StrUtil.isEmpty(domain) || StrUtil.isEmpty(bucket)) {
return resultMap; return resultMap;
} }
Auth auth = Auth.create(accessKey, secretKey); final Auth auth = Auth.create(accessKey, secretKey);
StringMap putPolicy = new StringMap(); final StringMap putPolicy = new StringMap();
putPolicy.put("returnBody", "{\"size\":$(fsize),\"w\":$(imageInfo.width),\"h\":$(imageInfo.height)}"); putPolicy.put("returnBody", "{\"size\":$(fsize),\"w\":$(imageInfo.width),\"h\":$(imageInfo.height)}");
String upToken = auth.uploadToken(bucket, null, 3600, putPolicy); final String upToken = auth.uploadToken(bucket, null, 3600, putPolicy);
String localTempDir = Paths.get(System.getenv("java.io.tmpdir"), bucket).toString(); final String localTempDir = Paths.get(System.getenv("java.io.tmpdir"), bucket).toString();
QiNiuPutSet putSet = new QiNiuPutSet(); QiNiuPutSet putSet = new QiNiuPutSet();
try { try {
FileRecorder fileRecorder = new FileRecorder(localTempDir); final FileRecorder fileRecorder = new FileRecorder(localTempDir);
UploadManager uploadManager = new UploadManager(cfg, fileRecorder); final UploadManager uploadManager = new UploadManager(cfg, fileRecorder);
Response response = uploadManager.put(file.getInputStream(), key, upToken, null, null); final Response response = uploadManager.put(file.getInputStream(), key, upToken, null, null);
//解析上传成功的结果 //解析上传成功的结果
putSet = new Gson().fromJson(response.bodyString(), QiNiuPutSet.class); putSet = new Gson().fromJson(response.bodyString(), QiNiuPutSet.class);
} catch (QiniuException e) { } catch (QiniuException e) {
Response r = e.response; final Response r = e.response;
System.err.println(r.toString()); System.err.println(r.toString());
try { try {
System.err.println(r.bodyString()); System.err.println(r.bodyString());
@ -285,7 +285,7 @@ public class AttachmentServiceImpl implements AttachmentService {
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
String filePath = domain.trim() + "/" + key; final String filePath = domain.trim() + "/" + key;
resultMap.put("fileName", file.getOriginalFilename()); resultMap.put("fileName", file.getOriginalFilename());
resultMap.put("filePath", filePath.trim()); resultMap.put("filePath", filePath.trim());
resultMap.put("smallPath", smallUrl == null ? filePath.trim() : (filePath + smallUrl).trim()); resultMap.put("smallPath", smallUrl == null ? filePath.trim() : (filePath + smallUrl).trim());
@ -308,31 +308,31 @@ public class AttachmentServiceImpl implements AttachmentService {
*/ */
@Override @Override
public Map<String, String> attachUpYunUpload(MultipartFile file, HttpServletRequest request) { public Map<String, String> attachUpYunUpload(MultipartFile file, HttpServletRequest request) {
Map<String, String> resultMap = new HashMap<>(6); final Map<String, String> resultMap = new HashMap<>(6);
try { try {
String key = Md5Util.getMD5Checksum(file); final String key = Md5Util.getMD5Checksum(file);
String ossSrc = HaloConst.OPTIONS.get("upyun_oss_src"); final String ossSrc = HaloConst.OPTIONS.get("upyun_oss_src");
String ossPwd = HaloConst.OPTIONS.get("upyun_oss_pwd"); final String ossPwd = HaloConst.OPTIONS.get("upyun_oss_pwd");
String bucket = HaloConst.OPTIONS.get("upyun_oss_bucket"); final String bucket = HaloConst.OPTIONS.get("upyun_oss_bucket");
String domain = HaloConst.OPTIONS.get("upyun_oss_domain"); final String domain = HaloConst.OPTIONS.get("upyun_oss_domain");
String operator = HaloConst.OPTIONS.get("upyun_oss_operator"); final String operator = HaloConst.OPTIONS.get("upyun_oss_operator");
String smallUrl = HaloConst.OPTIONS.get("upyun_oss_small"); final String smallUrl = HaloConst.OPTIONS.get("upyun_oss_small");
if (StrUtil.isEmpty(ossSrc) || StrUtil.isEmpty(ossPwd) || StrUtil.isEmpty(domain) || StrUtil.isEmpty(bucket) || StrUtil.isEmpty(operator)) { if (StrUtil.isEmpty(ossSrc) || StrUtil.isEmpty(ossPwd) || StrUtil.isEmpty(domain) || StrUtil.isEmpty(bucket) || StrUtil.isEmpty(operator)) {
return resultMap; return resultMap;
} }
String fileName = file.getOriginalFilename(); final String fileName = file.getOriginalFilename();
String fileSuffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.')); final String fileSuffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.'));
UpYun upYun = new UpYun(bucket, operator, ossPwd); final UpYun upYun = new UpYun(bucket, operator, ossPwd);
upYun.setTimeout(60); upYun.setTimeout(60);
upYun.setApiDomain(UpYun.ED_AUTO); upYun.setApiDomain(UpYun.ED_AUTO);
upYun.setDebug(true); upYun.setDebug(true);
upYun.writeFile(ossSrc + key + fileSuffix, file.getBytes(), true, null); upYun.writeFile(ossSrc + key + fileSuffix, file.getBytes(), true, null);
String filePath = domain.trim() + ossSrc + key + fileSuffix; final String filePath = domain.trim() + ossSrc + key + fileSuffix;
String smallPath = filePath; String smallPath = filePath;
if (smallUrl != null) { if (smallUrl != null) {
smallPath += smallUrl; smallPath += smallUrl;
} }
BufferedImage image = ImageIO.read(file.getInputStream()); final BufferedImage image = ImageIO.read(file.getInputStream());
if (image != null) { if (image != null) {
resultMap.put("wh", image.getWidth() + "x" + image.getHeight()); resultMap.put("wh", image.getWidth() + "x" + image.getHeight());
} }
@ -358,15 +358,15 @@ public class AttachmentServiceImpl implements AttachmentService {
@Override @Override
public boolean deleteQiNiuAttachment(String key) { public boolean deleteQiNiuAttachment(String key) {
boolean flag = true; boolean flag = true;
Configuration cfg = new Configuration(Zone.zone0()); final Configuration cfg = new Configuration(Zone.zone0());
String accessKey = HaloConst.OPTIONS.get("qiniu_access_key"); final String accessKey = HaloConst.OPTIONS.get("qiniu_access_key");
String secretKey = HaloConst.OPTIONS.get("qiniu_secret_key"); final String secretKey = HaloConst.OPTIONS.get("qiniu_secret_key");
String bucket = HaloConst.OPTIONS.get("qiniu_bucket"); final String bucket = HaloConst.OPTIONS.get("qiniu_bucket");
if (StrUtil.isEmpty(accessKey) || StrUtil.isEmpty(secretKey) || StrUtil.isEmpty(bucket)) { if (StrUtil.isEmpty(accessKey) || StrUtil.isEmpty(secretKey) || StrUtil.isEmpty(bucket)) {
return false; return false;
} }
Auth auth = Auth.create(accessKey, secretKey); final Auth auth = Auth.create(accessKey, secretKey);
BucketManager bucketManager = new BucketManager(auth, cfg); final BucketManager bucketManager = new BucketManager(auth, cfg);
try { try {
bucketManager.delete(bucket, key); bucketManager.delete(bucket, key);
} catch (QiniuException ex) { } catch (QiniuException ex) {
@ -386,14 +386,14 @@ public class AttachmentServiceImpl implements AttachmentService {
@Override @Override
public boolean deleteUpYunAttachment(String fileName) { public boolean deleteUpYunAttachment(String fileName) {
boolean flag = true; boolean flag = true;
String ossSrc = HaloConst.OPTIONS.get("upyun_oss_src"); final String ossSrc = HaloConst.OPTIONS.get("upyun_oss_src");
String ossPwd = HaloConst.OPTIONS.get("upyun_oss_pwd"); final String ossPwd = HaloConst.OPTIONS.get("upyun_oss_pwd");
String bucket = HaloConst.OPTIONS.get("upyun_oss_bucket"); final String bucket = HaloConst.OPTIONS.get("upyun_oss_bucket");
String operator = HaloConst.OPTIONS.get("upyun_oss_operator"); final String operator = HaloConst.OPTIONS.get("upyun_oss_operator");
if (StrUtil.isEmpty(ossSrc) || StrUtil.isEmpty(ossPwd) || StrUtil.isEmpty(bucket) || StrUtil.isEmpty(operator)) { if (StrUtil.isEmpty(ossSrc) || StrUtil.isEmpty(ossPwd) || StrUtil.isEmpty(bucket) || StrUtil.isEmpty(operator)) {
return false; return false;
} }
UpYun upYun = new UpYun(bucket, operator, ossPwd); final UpYun upYun = new UpYun(bucket, operator, ossPwd);
upYun.setApiDomain(UpYun.ED_AUTO); upYun.setApiDomain(UpYun.ED_AUTO);
try { try {
flag = upYun.deleteFile(ossSrc + fileName); flag = upYun.deleteFile(ossSrc + fileName);

View File

@ -48,7 +48,7 @@ public class CategoryServiceImpl implements CategoryService {
@Override @Override
@CacheEvict(value = POSTS_CACHE_NAME, allEntries = true, beforeInvocation = true) @CacheEvict(value = POSTS_CACHE_NAME, allEntries = true, beforeInvocation = true)
public Category remove(Long cateId) { public Category remove(Long cateId) {
Optional<Category> category = this.findByCateId(cateId); final Optional<Category> category = this.findByCateId(cateId);
categoryRepository.delete(category.get()); categoryRepository.delete(category.get());
return category.get(); return category.get();
} }
@ -107,7 +107,7 @@ public class CategoryServiceImpl implements CategoryService {
if (null == strings) { if (null == strings) {
return null; return null;
} }
List<Category> categories = new ArrayList<>(); final List<Category> categories = new ArrayList<>();
Optional<Category> category = null; Optional<Category> category = null;
for (String str : strings) { for (String str : strings) {
category = findByCateId(Long.parseLong(str)); category = findByCateId(Long.parseLong(str));

View File

@ -53,7 +53,7 @@ public class CommentServiceImpl implements CommentService {
@Override @Override
@CacheEvict(value = {COMMENTS_CACHE_NAME, POSTS_CACHE_NAME}, allEntries = true, beforeInvocation = true) @CacheEvict(value = {COMMENTS_CACHE_NAME, POSTS_CACHE_NAME}, allEntries = true, beforeInvocation = true)
public Optional<Comment> remove(Long commentId) { public Optional<Comment> remove(Long commentId) {
Optional<Comment> comment = this.findCommentById(commentId); final Optional<Comment> comment = this.findCommentById(commentId);
commentRepository.delete(comment.get()); commentRepository.delete(comment.get());
return comment; return comment;
} }
@ -102,7 +102,7 @@ public class CommentServiceImpl implements CommentService {
@Override @Override
@CacheEvict(value = COMMENTS_CACHE_NAME, allEntries = true, beforeInvocation = true) @CacheEvict(value = COMMENTS_CACHE_NAME, allEntries = true, beforeInvocation = true)
public Comment updateCommentStatus(Long commentId, Integer status) { public Comment updateCommentStatus(Long commentId, Integer status) {
Optional<Comment> comment = findCommentById(commentId); final Optional<Comment> comment = findCommentById(commentId);
comment.get().setCommentStatus(status); comment.get().setCommentStatus(status);
return commentRepository.save(comment.get()); return commentRepository.save(comment.get());
} }

View File

@ -50,7 +50,7 @@ public class GalleryServiceImpl implements GalleryService {
@Override @Override
@CacheEvict(value = GALLERIES_CACHE_NAME, allEntries = true, beforeInvocation = true) @CacheEvict(value = GALLERIES_CACHE_NAME, allEntries = true, beforeInvocation = true)
public Gallery remove(Long galleryId) { public Gallery remove(Long galleryId) {
Optional<Gallery> gallery = this.findByGalleryId(galleryId); final Optional<Gallery> gallery = this.findByGalleryId(galleryId);
galleryRepository.delete(gallery.get()); galleryRepository.delete(gallery.get());
return gallery.get(); return gallery.get();
} }

View File

@ -50,7 +50,7 @@ public class LinkServiceImpl implements LinkService {
@Override @Override
@CacheEvict(value = LINKS_CACHE_NAME, allEntries = true, beforeInvocation = true) @CacheEvict(value = LINKS_CACHE_NAME, allEntries = true, beforeInvocation = true)
public Link remove(Long linkId) { public Link remove(Long linkId) {
Optional<Link> link = this.findByLinkId(linkId); final Optional<Link> link = this.findByLinkId(linkId);
linkRepository.delete(link.get()); linkRepository.delete(link.get());
return link.get(); return link.get();
} }

View File

@ -36,7 +36,7 @@ public class LogsServiceImpl implements LogsService {
*/ */
@Override @Override
public void save(String logTitle, String logContent, HttpServletRequest request) { public void save(String logTitle, String logContent, HttpServletRequest request) {
Logs logs = new Logs(); final Logs logs = new Logs();
logs.setLogTitle(logTitle); logs.setLogTitle(logTitle);
logs.setLogContent(logContent); logs.setLogContent(logContent);
logs.setLogCreated(new Date()); logs.setLogCreated(new Date());

View File

@ -70,7 +70,7 @@ public class MailServiceImpl implements MailService {
HaloConst.OPTIONS.get(BlogPropertiesEnum.MAIL_SMTP_PASSWORD.getProp())); HaloConst.OPTIONS.get(BlogPropertiesEnum.MAIL_SMTP_PASSWORD.getProp()));
String text = ""; String text = "";
try { try {
Template template = freeMarker.getConfiguration().getTemplate(templateName); final Template template = freeMarker.getConfiguration().getTemplate(templateName);
text = FreeMarkerTemplateUtils.processTemplateIntoString(template, content); text = FreeMarkerTemplateUtils.processTemplateIntoString(template, content);
OhMyEmail.subject(subject) OhMyEmail.subject(subject)
.from(HaloConst.OPTIONS.get(BlogPropertiesEnum.MAIL_FROM_NAME.getProp())) .from(HaloConst.OPTIONS.get(BlogPropertiesEnum.MAIL_FROM_NAME.getProp()))
@ -101,7 +101,7 @@ public class MailServiceImpl implements MailService {
File file = new File(attachSrc); File file = new File(attachSrc);
String text = ""; String text = "";
try { try {
Template template = freeMarker.getConfiguration().getTemplate(templateName); final Template template = freeMarker.getConfiguration().getTemplate(templateName);
text = FreeMarkerTemplateUtils.processTemplateIntoString(template, content); text = FreeMarkerTemplateUtils.processTemplateIntoString(template, content);
OhMyEmail.subject(subject) OhMyEmail.subject(subject)
.from(HaloConst.OPTIONS.get(BlogPropertiesEnum.MAIL_FROM_NAME.getProp())) .from(HaloConst.OPTIONS.get(BlogPropertiesEnum.MAIL_FROM_NAME.getProp()))

View File

@ -61,7 +61,7 @@ public class MenuServiceImpl implements MenuService {
@Override @Override
@CacheEvict(value = MENUS_CACHE_NAME, allEntries = true, beforeInvocation = true) @CacheEvict(value = MENUS_CACHE_NAME, allEntries = true, beforeInvocation = true)
public Menu remove(Long menuId) { public Menu remove(Long menuId) {
Optional<Menu> menu = this.findByMenuId(menuId); final Optional<Menu> menu = this.findByMenuId(menuId);
menuRepository.delete(menu.get()); menuRepository.delete(menu.get());
return menu.get(); return menu.get();
} }

View File

@ -88,8 +88,8 @@ public class OptionsServiceImpl implements OptionsService {
*/ */
@Override @Override
public Map<String, String> findAllOptions() { public Map<String, String> findAllOptions() {
Map<String, String> options = new HashMap<>(); final Map<String, String> options = new HashMap<>();
List<Options> optionsList = optionsRepository.findAll(); final List<Options> optionsList = optionsRepository.findAll();
if (null != optionsList) { if (null != optionsList) {
optionsList.forEach(option -> options.put(option.getOptionName(), option.getOptionValue())); optionsList.forEach(option -> options.put(option.getOptionName(), option.getOptionValue()));
} }
@ -104,7 +104,7 @@ public class OptionsServiceImpl implements OptionsService {
*/ */
@Override @Override
public String findOneOption(String key) { public String findOneOption(String key) {
Options options = optionsRepository.findOptionsByOptionName(key); final Options options = optionsRepository.findOptionsByOptionName(key);
if (null != options) { if (null != options) {
return options.getOptionValue(); return options.getOptionValue();
} }

View File

@ -72,7 +72,7 @@ public class PostServiceImpl implements PostService {
@Override @Override
@CacheEvict(value = {POSTS_CACHE_NAME, COMMENTS_CACHE_NAME}, allEntries = true, beforeInvocation = true) @CacheEvict(value = {POSTS_CACHE_NAME, COMMENTS_CACHE_NAME}, allEntries = true, beforeInvocation = true)
public Post remove(Long postId) { public Post remove(Long postId) {
Optional<Post> post = this.findByPostId(postId); final Optional<Post> post = this.findByPostId(postId);
postRepository.delete(post.get()); postRepository.delete(post.get());
return post.get(); return post.get();
} }
@ -87,7 +87,7 @@ public class PostServiceImpl implements PostService {
@Override @Override
@CacheEvict(value = POSTS_CACHE_NAME, allEntries = true, beforeInvocation = true) @CacheEvict(value = POSTS_CACHE_NAME, allEntries = true, beforeInvocation = true)
public Post updatePostStatus(Long postId, Integer status) { public Post updatePostStatus(Long postId, Integer status) {
Optional<Post> post = this.findByPostId(postId); final Optional<Post> post = this.findByPostId(postId);
post.get().setPostStatus(status); post.get().setPostStatus(status);
return postRepository.save(post.get()); return postRepository.save(post.get());
} }
@ -100,7 +100,7 @@ public class PostServiceImpl implements PostService {
@Override @Override
@CacheEvict(value = POSTS_CACHE_NAME, allEntries = true, beforeInvocation = true) @CacheEvict(value = POSTS_CACHE_NAME, allEntries = true, beforeInvocation = true)
public void updateAllSummary(Integer postSummary) { public void updateAllSummary(Integer postSummary) {
List<Post> posts = this.findAll(PostTypeEnum.POST_TYPE_POST.getDesc()); final List<Post> posts = this.findAll(PostTypeEnum.POST_TYPE_POST.getDesc());
for (Post post : posts) { for (Post post : posts) {
String text = StrUtil.cleanBlank(HtmlUtil.cleanHtmlTag(post.getPostContent())); String text = StrUtil.cleanBlank(HtmlUtil.cleanHtmlTag(post.getPostContent()));
if (text.length() > postSummary) { if (text.length() > postSummary) {
@ -251,8 +251,8 @@ public class PostServiceImpl implements PostService {
@Override @Override
@Cacheable(value = POSTS_CACHE_NAME, key = "'archives_year_month'") @Cacheable(value = POSTS_CACHE_NAME, key = "'archives_year_month'")
public List<Archive> findPostGroupByYearAndMonth() { public List<Archive> findPostGroupByYearAndMonth() {
List<Object[]> objects = postRepository.findPostGroupByYearAndMonth(); final List<Object[]> objects = postRepository.findPostGroupByYearAndMonth();
List<Archive> archives = new ArrayList<>(); final List<Archive> archives = new ArrayList<>();
Archive archive = null; Archive archive = null;
for (Object[] obj : objects) { for (Object[] obj : objects) {
archive = new Archive(); archive = new Archive();
@ -273,8 +273,8 @@ public class PostServiceImpl implements PostService {
@Override @Override
@Cacheable(value = POSTS_CACHE_NAME, key = "'archives_year'") @Cacheable(value = POSTS_CACHE_NAME, key = "'archives_year'")
public List<Archive> findPostGroupByYear() { public List<Archive> findPostGroupByYear() {
List<Object[]> objects = postRepository.findPostGroupByYear(); final List<Object[]> objects = postRepository.findPostGroupByYear();
List<Archive> archives = new ArrayList<>(); final List<Archive> archives = new ArrayList<>();
Archive archive = null; Archive archive = null;
for (Object[] obj : objects) { for (Object[] obj : objects) {
archive = new Archive(); archive = new Archive();
@ -385,15 +385,15 @@ public class PostServiceImpl implements PostService {
@CachePut(value = POSTS_CACHE_NAME, key = "'posts_related_'+#post.getPostId()") @CachePut(value = POSTS_CACHE_NAME, key = "'posts_related_'+#post.getPostId()")
public List<Post> relatedPosts(Post post) { public List<Post> relatedPosts(Post post) {
//获取当前文章的所有标签 //获取当前文章的所有标签
List<Tag> tags = post.getTags(); final List<Tag> tags = post.getTags();
List<Post> tempPosts = new ArrayList<>(); final List<Post> tempPosts = new ArrayList<>();
for (Tag tag : tags) { for (Tag tag : tags) {
tempPosts.addAll(postRepository.findPostsByTags(tag)); tempPosts.addAll(postRepository.findPostsByTags(tag));
} }
//去掉当前的文章 //去掉当前的文章
tempPosts.remove(post); tempPosts.remove(post);
//去掉重复的文章 //去掉重复的文章
List<Post> allPosts = new ArrayList<>(); final List<Post> allPosts = new ArrayList<>();
for (int i = 0; i < tempPosts.size(); i++) { for (int i = 0; i < tempPosts.size(); i++) {
if (!allPosts.contains(tempPosts.get(i))) { if (!allPosts.contains(tempPosts.get(i))) {
allPosts.add(tempPosts.get(i)); allPosts.add(tempPosts.get(i));
@ -475,10 +475,10 @@ public class PostServiceImpl implements PostService {
*/ */
@Override @Override
public Post buildCategoriesAndTags(Post post, List<String> cateList, String tagList) { public Post buildCategoriesAndTags(Post post, List<String> cateList, String tagList) {
List<Category> categories = categoryService.strListToCateList(cateList); final List<Category> categories = categoryService.strListToCateList(cateList);
post.setCategories(categories); post.setCategories(categories);
if (StrUtil.isNotEmpty(tagList)) { if (StrUtil.isNotEmpty(tagList)) {
List<Tag> tags = tagService.strListToTagList(StrUtil.trim(tagList)); final List<Tag> tags = tagService.strListToTagList(StrUtil.trim(tagList));
post.setTags(tags); post.setTags(tags);
} }
return post; return post;

View File

@ -48,7 +48,7 @@ public class TagServiceImpl implements TagService {
@Override @Override
@CacheEvict(value = POSTS_CACHE_NAME, allEntries = true, beforeInvocation = true) @CacheEvict(value = POSTS_CACHE_NAME, allEntries = true, beforeInvocation = true)
public Tag remove(Long tagId) { public Tag remove(Long tagId) {
Optional<Tag> tag = findByTagId(tagId); final Optional<Tag> tag = findByTagId(tagId);
tagRepository.delete(tag.get()); tagRepository.delete(tag.get());
return tag.get(); return tag.get();
} }
@ -104,10 +104,10 @@ public class TagServiceImpl implements TagService {
*/ */
@Override @Override
public List<Tag> strListToTagList(String tagList) { public List<Tag> strListToTagList(String tagList) {
String[] tags = tagList.split(","); final String[] tags = tagList.split(",");
List<Tag> tagsList = new ArrayList<>(); final List<Tag> tagsList = new ArrayList<>();
for (String tag : tags) { for (String tag : tags) {
Tag t = findTagByTagName(tag); final Tag t = findTagByTagName(tag);
Tag nt = null; Tag nt = null;
if (null != t) { if (null != t) {
tagsList.add(t); tagsList.add(t);

View File

@ -65,7 +65,7 @@ public class UserServiceImpl implements UserService {
*/ */
@Override @Override
public User findUser() { public User findUser() {
List<User> users = userRepository.findAll(); final List<User> users = userRepository.findAll();
if (users != null && users.size() > 0) { if (users != null && users.size() > 0) {
return users.get(0); return users.get(0);
} else { } else {
@ -92,7 +92,7 @@ public class UserServiceImpl implements UserService {
*/ */
@Override @Override
public void updateUserLoginEnable(String enable) { public void updateUserLoginEnable(String enable) {
User user = this.findUser(); final User user = this.findUser();
user.setLoginEnable(enable); user.setLoginEnable(enable);
userRepository.save(user); userRepository.save(user);
} }
@ -105,7 +105,7 @@ public class UserServiceImpl implements UserService {
*/ */
@Override @Override
public User updateUserLoginLast(Date lastDate) { public User updateUserLoginLast(Date lastDate) {
User user = this.findUser(); final User user = this.findUser();
user.setLoginLast(lastDate); user.setLoginLast(lastDate);
userRepository.save(user); userRepository.save(user);
return user; return user;
@ -118,7 +118,7 @@ public class UserServiceImpl implements UserService {
*/ */
@Override @Override
public Integer updateUserLoginError() { public Integer updateUserLoginError() {
User user = this.findUser(); final User user = this.findUser();
user.setLoginError((user.getLoginError() == null ? 0 : user.getLoginError()) + 1); user.setLoginError((user.getLoginError() == null ? 0 : user.getLoginError()) + 1);
userRepository.save(user); userRepository.save(user);
return user.getLoginError(); return user.getLoginError();
@ -131,7 +131,7 @@ public class UserServiceImpl implements UserService {
*/ */
@Override @Override
public User updateUserNormal() { public User updateUserNormal() {
User user = this.findUser(); final User user = this.findUser();
user.setLoginEnable(TrueFalseEnum.TRUE.getDesc()); user.setLoginEnable(TrueFalseEnum.TRUE.getDesc());
user.setLoginError(0); user.setLoginError(0);
user.setLoginLast(new Date()); user.setLoginLast(new Date());

View File

@ -17,7 +17,7 @@ public class PostSyncTask {
* *
*/ */
public void postSync() { public void postSync() {
PostService postService = SpringUtil.getBean(PostService.class); final PostService postService = SpringUtil.getBean(PostService.class);
Post post = null; Post post = null;
int count = 0; int count = 0;
for (Long key : HaloConst.POSTS_VIEWS.keySet()) { for (Long key : HaloConst.POSTS_VIEWS.keySet()) {

View File

@ -29,7 +29,7 @@ public class CommentUtil {
return Collections.emptyList(); return Collections.emptyList();
} }
List<Comment> commentsResult = new ArrayList<>(); final List<Comment> commentsResult = new ArrayList<>();
for (Comment comment : commentsRoot) { for (Comment comment : commentsRoot) {
if (comment.getCommentParent() == 0) { if (comment.getCommentParent() == 0) {
@ -59,7 +59,7 @@ public class CommentUtil {
return null; return null;
} }
List<Comment> commentsChild = new ArrayList<>(); final List<Comment> commentsChild = new ArrayList<>();
for (Comment comment : commentsRoot) { for (Comment comment : commentsRoot) {
if (comment.getCommentParent() != 0) { if (comment.getCommentParent() != 0) {
if (comment.getCommentParent().equals(id)) { if (comment.getCommentParent().equals(id)) {

View File

@ -48,15 +48,16 @@ public class HaloUtils {
* *
* *
* @param dir dir * @param dir dir
*
* @return List * @return List
*/ */
public static List<BackupDto> getBackUps(String dir) { public static List<BackupDto> getBackUps(String dir) {
StrBuilder srcPathStr = new StrBuilder(System.getProperties().getProperty("user.home")); final StrBuilder srcPathStr = new StrBuilder(System.getProperties().getProperty("user.home"));
srcPathStr.append("/halo/backup/"); srcPathStr.append("/halo/backup/");
srcPathStr.append(dir); srcPathStr.append(dir);
File srcPath = new File(srcPathStr.toString()); final File srcPath = new File(srcPathStr.toString());
File[] files = srcPath.listFiles(); final File[] files = srcPath.listFiles();
List<BackupDto> backupDtos = new ArrayList<>(); final List<BackupDto> backupDtos = new ArrayList<>();
BackupDto backupDto = null; BackupDto backupDto = null;
// 遍历文件 // 遍历文件
if (null != files) { if (null != files) {
@ -82,25 +83,26 @@ public class HaloUtils {
* *
* *
* @param size size * @param size size
*
* @return String * @return String
*/ */
public static String parseSize(long size) { public static String parseSize(long size) {
if (size < CommonParamsEnum.BYTE.getValue()) { if (size < CommonParamsEnum.BYTE.getValue()) {
return String.valueOf(size) + "B"; return size + "B";
} else { } else {
size = size / 1024; size = size / 1024;
} }
if (size < CommonParamsEnum.BYTE.getValue()) { if (size < CommonParamsEnum.BYTE.getValue()) {
return String.valueOf(size) + "KB"; return size + "KB";
} else { } else {
size = size / 1024; size = size / 1024;
} }
if (size < CommonParamsEnum.BYTE.getValue()) { if (size < CommonParamsEnum.BYTE.getValue()) {
size = size * 100; size = size * 100;
return String.valueOf((size / 100)) + "." + String.valueOf((size % 100)) + "MB"; return size / 100 + "." + size % 100 + "MB";
} else { } else {
size = size * 100 / 1024; size = size * 100 / 1024;
return String.valueOf((size / 100)) + "." + String.valueOf((size % 100)) + "GB"; return size / 100 + "." + size % 100 + "GB";
} }
} }
@ -108,21 +110,21 @@ public class HaloUtils {
* *
* *
* @param srcPath * @param srcPath
*
* @return * @return
*/ */
public static Date getCreateTime(String srcPath) { public static Date getCreateTime(String srcPath) {
Path path = Paths.get(srcPath); final Path path = Paths.get(srcPath);
BasicFileAttributeView basicview = Files.getFileAttributeView(path, BasicFileAttributeView.class, final BasicFileAttributeView basicview = Files.getFileAttributeView(path, BasicFileAttributeView.class, LinkOption.NOFOLLOW_LINKS);
LinkOption.NOFOLLOW_LINKS);
BasicFileAttributes attr; BasicFileAttributes attr;
try { try {
attr = basicview.readAttributes(); attr = basicview.readAttributes();
Date createDate = new Date(attr.creationTime().toMillis()); final Date createDate = new Date(attr.creationTime().toMillis());
return createDate; return createDate;
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
Calendar cal = Calendar.getInstance(); final Calendar cal = Calendar.getInstance();
cal.set(1970, 0, 1, 0, 0, 0); cal.set(1970, 0, 1, 0, 0, 0);
return cal.getTime(); return cal.getTime();
} }
@ -131,11 +133,12 @@ public class HaloUtils {
* *
* *
* @param file file * @param file file
*
* @return String * @return String
*/ */
public static String getImageWh(File file) { public static String getImageWh(File file) {
try { try {
BufferedImage image = ImageIO.read(new FileInputStream(file)); final BufferedImage image = ImageIO.read(new FileInputStream(file));
return image.getWidth() + "x" + image.getHeight(); return image.getWidth() + "x" + image.getHeight();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
@ -149,13 +152,13 @@ public class HaloUtils {
* @return List * @return List
*/ */
public static List<Theme> getThemes() { public static List<Theme> getThemes() {
List<Theme> themes = new ArrayList<>(); final List<Theme> themes = new ArrayList<>();
try { try {
// 获取项目根路径 // 获取项目根路径
File basePath = new File(ResourceUtils.getURL("classpath:").getPath()); final File basePath = new File(ResourceUtils.getURL("classpath:").getPath());
// 获取主题路径 // 获取主题路径
File themesPath = new File(basePath.getAbsolutePath(), "templates/themes"); final File themesPath = new File(basePath.getAbsolutePath(), "templates/themes");
File[] files = themesPath.listFiles(); final File[] files = themesPath.listFiles();
if (null != files) { if (null != files) {
Theme theme = null; Theme theme = null;
for (File file : files) { for (File file : files) {
@ -192,18 +195,19 @@ public class HaloUtils {
* *
* *
* @param theme theme * @param theme theme
*
* @return List * @return List
*/ */
public static List<String> getTplName(String theme) { public static List<String> getTplName(String theme) {
List<String> tpls = new ArrayList<>(); final List<String> tpls = new ArrayList<>();
try { try {
// 获取项目根路径 // 获取项目根路径
File basePath = new File(ResourceUtils.getURL("classpath:").getPath()); final File basePath = new File(ResourceUtils.getURL("classpath:").getPath());
// 获取主题路径 // 获取主题路径
File themesPath = new File(basePath.getAbsolutePath(), "templates/themes/" + theme); final File themesPath = new File(basePath.getAbsolutePath(), "templates/themes/" + theme);
File modulePath = new File(themesPath.getAbsolutePath(), "module"); final File modulePath = new File(themesPath.getAbsolutePath(), "module");
File[] baseFiles = themesPath.listFiles(); final File[] baseFiles = themesPath.listFiles();
File[] moduleFiles = modulePath.listFiles(); final File[] moduleFiles = modulePath.listFiles();
if (null != moduleFiles) { if (null != moduleFiles) {
for (File file : moduleFiles) { for (File file : moduleFiles) {
if (file.isFile() && file.getName().endsWith(".ftl")) { if (file.isFile() && file.getName().endsWith(".ftl")) {
@ -230,12 +234,12 @@ public class HaloUtils {
* @return List * @return List
*/ */
public static List<String> getCustomTpl(String theme) { public static List<String> getCustomTpl(String theme) {
List<String> tpls = new ArrayList<>(); final List<String> tpls = new ArrayList<>();
try { try {
File basePath = new File(ResourceUtils.getURL("classpath:").getPath()); final File basePath = new File(ResourceUtils.getURL("classpath:").getPath());
// 获取主题路径 // 获取主题路径
File themePath = new File(basePath.getAbsolutePath(), "templates/themes/" + theme); final File themePath = new File(basePath.getAbsolutePath(), "templates/themes/" + theme);
File[] themeFiles = themePath.listFiles(); final File[] themeFiles = themePath.listFiles();
if (null != themeFiles && themeFiles.length > 0) { if (null != themeFiles && themeFiles.length > 0) {
for (File file : themeFiles) { for (File file : themeFiles) {
String[] split = StrUtil.removeSuffix(file.getName(), ".ftl").split("_"); String[] split = StrUtil.removeSuffix(file.getName(), ".ftl").split("_");
@ -261,7 +265,7 @@ public class HaloUtils {
FileWriter fileWriter = null; FileWriter fileWriter = null;
BufferedWriter bufferedWriter = null; BufferedWriter bufferedWriter = null;
try { try {
File file = new File(filePath); final File file = new File(filePath);
if (!file.exists()) { if (!file.exists()) {
file.mkdirs(); file.mkdirs();
} }
@ -284,13 +288,15 @@ public class HaloUtils {
* rss * rss
* *
* @param posts posts * @param posts posts
*
* @return String * @return String
*
* @throws FeedException FeedException * @throws FeedException FeedException
*/ */
public static String getRss(List<Post> posts) throws FeedException { public static String getRss(List<Post> posts) throws FeedException {
Assert.notEmpty(posts, "posts must not be empty"); Assert.notEmpty(posts, "posts must not be empty");
Channel channel = new Channel("rss_2.0"); final Channel channel = new Channel("rss_2.0");
if (null == HaloConst.OPTIONS.get(BlogPropertiesEnum.BLOG_TITLE.getProp())) { if (null == HaloConst.OPTIONS.get(BlogPropertiesEnum.BLOG_TITLE.getProp())) {
channel.setTitle(""); channel.setTitle("");
} else { } else {
@ -307,13 +313,13 @@ public class HaloUtils {
channel.setDescription(HaloConst.OPTIONS.get(BlogPropertiesEnum.SEO_DESC.getProp())); channel.setDescription(HaloConst.OPTIONS.get(BlogPropertiesEnum.SEO_DESC.getProp()));
} }
channel.setLanguage("zh-CN"); channel.setLanguage("zh-CN");
List<Item> items = new ArrayList<>(); final List<Item> items = new ArrayList<>();
for (Post post : posts) { for (Post post : posts) {
Item item = new Item(); final Item item = new Item();
item.setTitle(post.getPostTitle()); item.setTitle(post.getPostTitle());
Content content = new Content(); final Content content = new Content();
String value = post.getPostContent(); String value = post.getPostContent();
char[] xmlChar = value.toCharArray(); final char[] xmlChar = value.toCharArray();
for (int i = 0; i < xmlChar.length; ++i) { for (int i = 0; i < xmlChar.length; ++i) {
if (xmlChar[i] > 0xFFFD) { if (xmlChar[i] > 0xFFFD) {
xmlChar[i] = ' '; xmlChar[i] = ' ';
@ -324,13 +330,12 @@ public class HaloUtils {
value = new String(xmlChar); value = new String(xmlChar);
content.setValue(value); content.setValue(value);
item.setContent(content); item.setContent(content);
item.setLink( item.setLink(HaloConst.OPTIONS.get(BlogPropertiesEnum.BLOG_URL.getProp()) + "/archives/" + post.getPostUrl());
HaloConst.OPTIONS.get(BlogPropertiesEnum.BLOG_URL.getProp()) + "/archives/" + post.getPostUrl());
item.setPubDate(post.getPostDate()); item.setPubDate(post.getPostDate());
items.add(item); items.add(item);
} }
channel.setItems(items); channel.setItems(items);
WireFeedOutput out = new WireFeedOutput(); final WireFeedOutput out = new WireFeedOutput();
return out.outputString(channel); return out.outputString(channel);
} }
@ -338,13 +343,14 @@ public class HaloUtils {
* sitemap * sitemap
* *
* @param posts posts * @param posts posts
*
* @return String * @return String
*/ */
public static String getSiteMap(List<Post> posts) { public static String getSiteMap(List<Post> posts) {
Assert.notEmpty(posts, "post mut not be empty"); Assert.notEmpty(posts, "post mut not be empty");
StrBuilder head = new StrBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">"); final StrBuilder head = new StrBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">");
StrBuilder urlBody = new StrBuilder(); final StrBuilder urlBody = new StrBuilder();
String urlPath = HaloConst.OPTIONS.get(BlogPropertiesEnum.BLOG_URL.getProp()) + "/archives/"; final String urlPath = HaloConst.OPTIONS.get(BlogPropertiesEnum.BLOG_URL.getProp()) + "/archives/";
for (Post post : posts) { for (Post post : posts) {
urlBody.append("<url><loc>"); urlBody.append("<url><loc>");
urlBody.append(urlPath); urlBody.append(urlPath);
@ -364,7 +370,7 @@ public class HaloUtils {
* @param password password * @param password password
*/ */
public static void configMail(String smtpHost, String userName, String password) { public static void configMail(String smtpHost, String userName, String password) {
Properties properties = OhMyEmail.defaultConfig(false); final Properties properties = OhMyEmail.defaultConfig(false);
properties.setProperty("mail.smtp.host", smtpHost); properties.setProperty("mail.smtp.host", smtpHost);
OhMyEmail.config(properties, userName, password); OhMyEmail.config(properties, userName, password);
} }
@ -375,6 +381,7 @@ public class HaloUtils {
* @param blogUrl * @param blogUrl
* @param token token * @param token token
* @param urls * @param urls
*
* @return String * @return String
*/ */
public static String baiduPost(String blogUrl, String token, String urls) { public static String baiduPost(String blogUrl, String token, String urls) {
@ -382,17 +389,17 @@ public class HaloUtils {
Assert.hasText(token, "token must not be blank"); Assert.hasText(token, "token must not be blank");
Assert.hasText(urls, "urls must not be blank"); Assert.hasText(urls, "urls must not be blank");
StrBuilder url = new StrBuilder("http://data.zz.baidu.com/urls?site="); final StrBuilder url = new StrBuilder("http://data.zz.baidu.com/urls?site=");
url.append(blogUrl); url.append(blogUrl);
url.append("&token="); url.append("&token=");
url.append(token); url.append(token);
StrBuilder result = new StrBuilder(); final StrBuilder result = new StrBuilder();
PrintWriter out = null; PrintWriter out = null;
BufferedReader in = null; BufferedReader in = null;
try { try {
// 建立URL之间的连接 // 建立URL之间的连接
URLConnection conn = new URL(url.toString()).openConnection(); final URLConnection conn = new URL(url.toString()).openConnection();
// 设置通用的请求属性 // 设置通用的请求属性
conn.setRequestProperty("Host", "data.zz.baidu.com"); conn.setRequestProperty("Host", "data.zz.baidu.com");
conn.setRequestProperty("User-Agent", "curl/7.12.1"); conn.setRequestProperty("User-Agent", "curl/7.12.1");

View File

@ -43,10 +43,11 @@ public class MarkdownUtils {
* Markdown * Markdown
* *
* @param content content * @param content content
*
* @return String * @return String
*/ */
public static String renderMarkdown(String content) { public static String renderMarkdown(String content) {
Node document = PARSER.parse(content); final Node document = PARSER.parse(content);
return RENDERER.render(document); return RENDERER.render(document);
} }
@ -54,11 +55,12 @@ public class MarkdownUtils {
* *
* *
* @param content content * @param content content
*
* @return Map * @return Map
*/ */
public static Map<String, List<String>> getFrontMatter(String content) { public static Map<String, List<String>> getFrontMatter(String content) {
YamlFrontMatterVisitor visitor = new YamlFrontMatterVisitor(); final YamlFrontMatterVisitor visitor = new YamlFrontMatterVisitor();
Node document = PARSER.parse(content); final Node document = PARSER.parse(content);
document.accept(visitor); document.accept(visitor);
return visitor.getData(); return visitor.getData();
} }

View File

@ -1,5 +1,6 @@
package cc.ryanc.halo.utils; package cc.ryanc.halo.utils;
import cn.hutool.core.text.StrBuilder;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream; import java.io.InputStream;
@ -17,15 +18,18 @@ public class Md5Util {
/** /**
* MD5 * MD5
* @param file *
* @return * @param file file
* @throws Exception *
* @return byte
*
* @throws Exception Exception
*/ */
public static byte[] createChecksum(MultipartFile file) throws Exception { private static byte[] createChecksum(MultipartFile file) throws Exception {
InputStream fis = file.getInputStream(); final InputStream fis = file.getInputStream();
byte[] buffer = new byte[1024]; final byte[] buffer = new byte[1024];
MessageDigest complete = MessageDigest.getInstance("MD5"); final MessageDigest complete = MessageDigest.getInstance("MD5");
int numRead; int numRead;
do { do {
@ -41,18 +45,20 @@ public class Md5Util {
/** /**
* hash * hash
* @param file *
* @return * @param file file
* @throws Exception *
* @return String
*
* @throws Exception Exception
*/ */
public static String getMD5Checksum(MultipartFile file) throws Exception { public static String getMD5Checksum(MultipartFile file) throws Exception {
byte[] b = createChecksum(file); final byte[] b = createChecksum(file);
String result = ""; StrBuilder result = new StrBuilder();
for (int i = 0; i < b.length; i++) { for (int i = 0; i < b.length; i++) {
result += Integer.toString( ( b[i] & 0xff ) + 0x100, 16).substring( 1 ); result.append(Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1));
} }
return result; return result.toString();
} }
} }

View File

@ -78,37 +78,38 @@ public class AdminController extends BaseController {
* *
* @param model model * @param model model
* @param session session * @param session session
*
* @return admin/admin_index * @return admin/admin_index
*/ */
@GetMapping(value = {"", "/index"}) @GetMapping(value = {"", "/index"})
public String index(Model model) { public String index(Model model) {
//查询评论的条数 //查询评论的条数
Long commentCount = commentService.getCount(); final Long commentCount = commentService.getCount();
model.addAttribute("commentCount", commentCount); model.addAttribute("commentCount", commentCount);
//查询最新的文章 //查询最新的文章
List<Post> postsLatest = postService.findPostLatest(); final List<Post> postsLatest = postService.findPostLatest();
model.addAttribute("postTopFive", postsLatest); model.addAttribute("postTopFive", postsLatest);
//查询最新的日志 //查询最新的日志
List<Logs> logsLatest = logsService.findLogsLatest(); final List<Logs> logsLatest = logsService.findLogsLatest();
model.addAttribute("logs", logsLatest); model.addAttribute("logs", logsLatest);
//查询最新的评论 //查询最新的评论
List<Comment> comments = commentService.findCommentsLatest(); final List<Comment> comments = commentService.findCommentsLatest();
model.addAttribute("comments", comments); model.addAttribute("comments", comments);
//附件数量 //附件数量
model.addAttribute("mediaCount", attachmentService.getCount()); model.addAttribute("mediaCount", attachmentService.getCount());
//文章阅读总数 //文章阅读总数
Long postViewsSum = postService.getPostViews(); final Long postViewsSum = postService.getPostViews();
model.addAttribute("postViewsSum", postViewsSum); model.addAttribute("postViewsSum", postViewsSum);
//成立天数 //成立天数
Date blogStart = DateUtil.parse(HaloConst.OPTIONS.get(BlogPropertiesEnum.BLOG_START.getProp())); final Date blogStart = DateUtil.parse(HaloConst.OPTIONS.get(BlogPropertiesEnum.BLOG_START.getProp()));
long hadDays = DateUtil.between(blogStart, DateUtil.date(), DateUnit.DAY); final long hadDays = DateUtil.between(blogStart, DateUtil.date(), DateUnit.DAY);
model.addAttribute("hadDays", hadDays); model.addAttribute("hadDays", hadDays);
return "admin/admin_index"; return "admin/admin_index";
} }
@ -117,11 +118,12 @@ public class AdminController extends BaseController {
* *
* *
* @param session session * @param session session
*
* @return admin/admin_login * @return admin/admin_login
*/ */
@GetMapping(value = "/login") @GetMapping(value = "/login")
public String login(HttpSession session) { public String login(HttpSession session) {
User user = (User) session.getAttribute(HaloConst.USER_SESSION_KEY); final User user = (User) session.getAttribute(HaloConst.USER_SESSION_KEY);
//如果session存在跳转到后台首页 //如果session存在跳转到后台首页
if (null != user) { if (null != user) {
return "redirect:/admin"; return "redirect:/admin";
@ -135,6 +137,7 @@ public class AdminController extends BaseController {
* @param loginName * @param loginName
* @param loginPwd loginPwd * @param loginPwd loginPwd
* @param session session session * @param session session session
*
* @return JsonResult JsonResult * @return JsonResult JsonResult
*/ */
@PostMapping(value = "/getLogin") @PostMapping(value = "/getLogin")
@ -143,13 +146,13 @@ public class AdminController extends BaseController {
@ModelAttribute("loginPwd") String loginPwd, @ModelAttribute("loginPwd") String loginPwd,
HttpSession session) { HttpSession session) {
//已注册账号,单用户,只有一个 //已注册账号,单用户,只有一个
User aUser = userService.findUser(); final User aUser = userService.findUser();
//首先判断是否已经被禁用已经是否已经过了10分钟 //首先判断是否已经被禁用已经是否已经过了10分钟
Date loginLast = DateUtil.date(); Date loginLast = DateUtil.date();
if (null != aUser.getLoginLast()) { if (null != aUser.getLoginLast()) {
loginLast = aUser.getLoginLast(); loginLast = aUser.getLoginLast();
} }
Long between = DateUtil.between(loginLast, DateUtil.date(), DateUnit.MINUTE); final Long between = DateUtil.between(loginLast, DateUtil.date(), DateUnit.MINUTE);
if (StrUtil.equals(aUser.getLoginEnable(), TrueFalseEnum.FALSE.getDesc()) && (between < CommonParamsEnum.TEN.getValue())) { if (StrUtil.equals(aUser.getLoginEnable(), TrueFalseEnum.FALSE.getDesc()) && (between < CommonParamsEnum.TEN.getValue())) {
return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.login.disabled")); return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.login.disabled"));
} }
@ -171,13 +174,13 @@ public class AdminController extends BaseController {
return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), localeMessageUtil.getMessage("code.admin.login.success")); return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), localeMessageUtil.getMessage("code.admin.login.success"));
} else { } else {
//更新失败次数 //更新失败次数
Integer errorCount = userService.updateUserLoginError(); final Integer errorCount = userService.updateUserLoginError();
//超过五次禁用账户 //超过五次禁用账户
if (errorCount >= CommonParamsEnum.FIVE.getValue()) { if (errorCount >= CommonParamsEnum.FIVE.getValue()) {
userService.updateUserLoginEnable(TrueFalseEnum.FALSE.getDesc()); userService.updateUserLoginEnable(TrueFalseEnum.FALSE.getDesc());
} }
logsService.save(LogsRecord.LOGIN, LogsRecord.LOGIN_ERROR + "[" + HtmlUtil.escape(loginName) + "," + HtmlUtil.escape(loginPwd) + "]", request); logsService.save(LogsRecord.LOGIN, LogsRecord.LOGIN_ERROR + "[" + HtmlUtil.escape(loginName) + "," + HtmlUtil.escape(loginPwd) + "]", request);
Object[] args = {(5 - errorCount)}; final Object[] args = {(5 - errorCount)};
return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.login.failed", args)); return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.login.failed", args));
} }
} }
@ -186,11 +189,12 @@ public class AdminController extends BaseController {
* 退 session * 退 session
* *
* @param session session * @param session session
*
* @return /admin/login * @return /admin/login
*/ */
@GetMapping(value = "/logOut") @GetMapping(value = "/logOut")
public String logOut(HttpSession session) { public String logOut(HttpSession session) {
User user = (User) session.getAttribute(HaloConst.USER_SESSION_KEY); final User user = (User) session.getAttribute(HaloConst.USER_SESSION_KEY);
session.removeAttribute(HaloConst.USER_SESSION_KEY); session.removeAttribute(HaloConst.USER_SESSION_KEY);
logsService.save(LogsRecord.LOGOUT, user.getUserName(), request); logsService.save(LogsRecord.LOGOUT, user.getUserName(), request);
log.info("User {} has logged out", user.getUserName()); log.info("User {} has logged out", user.getUserName());
@ -203,15 +207,16 @@ public class AdminController extends BaseController {
* @param model model model * @param model model model
* @param page page * @param page page
* @param size size * @param size size
*
* @return admin/widget/_logs-all * @return admin/widget/_logs-all
*/ */
@GetMapping(value = "/logs") @GetMapping(value = "/logs")
public String logs(Model model, public String logs(Model model,
@RequestParam(value = "page", defaultValue = "0") Integer page, @RequestParam(value = "page", defaultValue = "0") Integer page,
@RequestParam(value = "size", defaultValue = "10") Integer size) { @RequestParam(value = "size", defaultValue = "10") Integer size) {
Sort sort = new Sort(Sort.Direction.DESC, "logId"); final Sort sort = new Sort(Sort.Direction.DESC, "logId");
Pageable pageable = PageRequest.of(page, size, sort); final Pageable pageable = PageRequest.of(page, size, sort);
Page<Logs> logs = logsService.findAll(pageable); final Page<Logs> logs = logsService.findAll(pageable);
model.addAttribute("logs", logs); model.addAttribute("logs", logs);
return "admin/widget/_logs-all"; return "admin/widget/_logs-all";
} }
@ -249,7 +254,7 @@ public class AdminController extends BaseController {
@GetMapping(value = "/getToken") @GetMapping(value = "/getToken")
@ResponseBody @ResponseBody
public JsonResult getToken() { public JsonResult getToken() {
String token = (System.currentTimeMillis() + new Random().nextInt(999999999)) + ""; final String token = (System.currentTimeMillis() + new Random().nextInt(999999999)) + "";
return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), ResponseStatusEnum.SUCCESS.getMsg(), SecureUtil.md5(token)); return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), ResponseStatusEnum.SUCCESS.getMsg(), SecureUtil.md5(token));
} }
@ -279,6 +284,7 @@ public class AdminController extends BaseController {
* *
* @param file file * @param file file
* @param request request * @param request request
*
* @return JsonResult * @return JsonResult
*/ */
@PostMapping(value = "/tools/markdownImport") @PostMapping(value = "/tools/markdownImport")
@ -286,14 +292,14 @@ public class AdminController extends BaseController {
public JsonResult markdownImport(@RequestParam("file") MultipartFile file, public JsonResult markdownImport(@RequestParam("file") MultipartFile file,
HttpServletRequest request, HttpServletRequest request,
HttpSession session) throws IOException { HttpSession session) throws IOException {
User user = (User) session.getAttribute(HaloConst.USER_SESSION_KEY); final User user = (User) session.getAttribute(HaloConst.USER_SESSION_KEY);
String markdown = IoUtil.read(file.getInputStream(), "UTF-8"); final String markdown = IoUtil.read(file.getInputStream(), "UTF-8");
String content = MarkdownUtils.renderMarkdown(markdown); final String content = MarkdownUtils.renderMarkdown(markdown);
Map<String, List<String>> frontMatters = MarkdownUtils.getFrontMatter(markdown); final Map<String, List<String>> frontMatters = MarkdownUtils.getFrontMatter(markdown);
Post post = new Post(); final Post post = new Post();
List<String> elementValue = null; List<String> elementValue = null;
List<Tag> tags = new ArrayList<>(); final List<Tag> tags = new ArrayList<>();
List<Category> categories = new ArrayList<>(); final List<Category> categories = new ArrayList<>();
Tag tag = null; Tag tag = null;
Category category = null; Category category = null;
if (frontMatters.size() > 0) { if (frontMatters.size() > 0) {
@ -345,9 +351,9 @@ public class AdminController extends BaseController {
if (StrUtil.isNotEmpty(HaloConst.OPTIONS.get(BlogPropertiesEnum.POST_SUMMARY.getProp()))) { if (StrUtil.isNotEmpty(HaloConst.OPTIONS.get(BlogPropertiesEnum.POST_SUMMARY.getProp()))) {
postSummary = Integer.parseInt(HaloConst.OPTIONS.get(BlogPropertiesEnum.POST_SUMMARY.getProp())); postSummary = Integer.parseInt(HaloConst.OPTIONS.get(BlogPropertiesEnum.POST_SUMMARY.getProp()));
} }
String summaryText = StrUtil.cleanBlank(HtmlUtil.cleanHtmlTag(post.getPostContent())); final String summaryText = StrUtil.cleanBlank(HtmlUtil.cleanHtmlTag(post.getPostContent()));
if (summaryText.length() > postSummary) { if (summaryText.length() > postSummary) {
String summary = summaryText.substring(0, postSummary); final String summary = summaryText.substring(0, postSummary);
post.setPostSummary(summary); post.setPostSummary(summary);
} else { } else {
post.setPostSummary(summaryText); post.setPostSummary(summaryText);

View File

@ -55,15 +55,16 @@ public class AttachmentController {
* *
* *
* @param model model * @param model model
*
* @return admin/admin_attachment * @return admin/admin_attachment
*/ */
@GetMapping @GetMapping
public String attachments(Model model, public String attachments(Model model,
@RequestParam(value = "page", defaultValue = "0") Integer page, @RequestParam(value = "page", defaultValue = "0") Integer page,
@RequestParam(value = "size", defaultValue = "18") Integer size) { @RequestParam(value = "size", defaultValue = "18") Integer size) {
Sort sort = new Sort(Sort.Direction.DESC, "attachId"); final Sort sort = new Sort(Sort.Direction.DESC, "attachId");
Pageable pageable = PageRequest.of(page, size, sort); final Pageable pageable = PageRequest.of(page, size, sort);
Page<Attachment> attachments = attachmentService.findAll(pageable); final Page<Attachment> attachments = attachmentService.findAll(pageable);
model.addAttribute("attachments", attachments); model.addAttribute("attachments", attachments);
return "admin/admin_attachment"; return "admin/admin_attachment";
} }
@ -73,6 +74,7 @@ public class AttachmentController {
* *
* @param model model * @param model model
* @param page page * @param page page
*
* @return admin/widget/_attachment-select * @return admin/widget/_attachment-select
*/ */
@GetMapping(value = "/select") @GetMapping(value = "/select")
@ -80,9 +82,9 @@ public class AttachmentController {
@RequestParam(value = "page", defaultValue = "0") Integer page, @RequestParam(value = "page", defaultValue = "0") Integer page,
@RequestParam(value = "id", defaultValue = "none") String id, @RequestParam(value = "id", defaultValue = "none") String id,
@RequestParam(value = "type", defaultValue = "normal") String type) { @RequestParam(value = "type", defaultValue = "normal") String type) {
Sort sort = new Sort(Sort.Direction.DESC, "attachId"); final Sort sort = new Sort(Sort.Direction.DESC, "attachId");
Pageable pageable = PageRequest.of(page, 18, sort); final Pageable pageable = PageRequest.of(page, 18, sort);
Page<Attachment> attachments = attachmentService.findAll(pageable); final Page<Attachment> attachments = attachmentService.findAll(pageable);
model.addAttribute("attachments", attachments); model.addAttribute("attachments", attachments);
model.addAttribute("id", id); model.addAttribute("id", id);
if (StrUtil.equals(type, PostTypeEnum.POST_TYPE_POST.getDesc())) { if (StrUtil.equals(type, PostTypeEnum.POST_TYPE_POST.getDesc())) {
@ -107,16 +109,17 @@ public class AttachmentController {
* *
* @param file file * @param file file
* @param request request * @param request request
*
* @return Map * @return Map
*/ */
@PostMapping(value = "/upload", produces = {"application/json;charset=UTF-8"}) @PostMapping(value = "/upload", produces = {"application/json;charset=UTF-8"})
@ResponseBody @ResponseBody
public Map<String, Object> upload(@RequestParam("file") MultipartFile file, public Map<String, Object> upload(@RequestParam("file") MultipartFile file,
HttpServletRequest request) { HttpServletRequest request) {
Map<String, Object> result = new HashMap<>(3); final Map<String, Object> result = new HashMap<>(3);
if (!file.isEmpty()) { if (!file.isEmpty()) {
try { try {
Map<String, String> resultMap = attachmentService.upload(file, request); final Map<String, String> resultMap = attachmentService.upload(file, request);
if (resultMap == null || resultMap.isEmpty()) { if (resultMap == null || resultMap.isEmpty()) {
log.error("File upload failed"); log.error("File upload failed");
result.put("success", ResultCodeEnum.FAIL.getCode()); result.put("success", ResultCodeEnum.FAIL.getCode());
@ -157,12 +160,13 @@ public class AttachmentController {
* *
* @param model model * @param model model
* @param attachId * @param attachId
*
* @return admin/widget/_attachment-detail * @return admin/widget/_attachment-detail
*/ */
@GetMapping(value = "/attachment") @GetMapping(value = "/attachment")
public String attachmentDetail(Model model, @RequestParam("attachId") Long attachId) { public String attachmentDetail(Model model, @RequestParam("attachId") Long attachId) {
Optional<Attachment> attachment = attachmentService.findByAttachId(attachId); final Optional<Attachment> attachment = attachmentService.findByAttachId(attachId);
model.addAttribute("attachment", attachment.get()); model.addAttribute("attachment", attachment.orElse(new Attachment()));
return "admin/widget/_attachment-detail"; return "admin/widget/_attachment-detail";
} }
@ -171,6 +175,7 @@ public class AttachmentController {
* *
* @param attachId * @param attachId
* @param request request * @param request request
*
* @return JsonResult * @return JsonResult
*/ */
@GetMapping(value = "/remove") @GetMapping(value = "/remove")

View File

@ -57,6 +57,7 @@ public class BackupController {
* *
* *
* @param model model * @param model model
*
* @return admin/admin_backup * @return admin/admin_backup
*/ */
@GetMapping @GetMapping
@ -80,6 +81,7 @@ public class BackupController {
* *
* *
* @param type * @param type
*
* @return JsonResult * @return JsonResult
*/ */
@GetMapping(value = "doBackup") @GetMapping(value = "doBackup")
@ -106,8 +108,8 @@ public class BackupController {
if (HaloUtils.getBackUps(BackupTypeEnum.DATABASES.getDesc()).size() > CommonParamsEnum.TEN.getValue()) { if (HaloUtils.getBackUps(BackupTypeEnum.DATABASES.getDesc()).size() > CommonParamsEnum.TEN.getValue()) {
FileUtil.del(System.getProperties().getProperty("user.home") + "/halo/backup/databases/"); FileUtil.del(System.getProperties().getProperty("user.home") + "/halo/backup/databases/");
} }
String srcPath = System.getProperties().getProperty("user.home") + "/halo/"; final String srcPath = System.getProperties().getProperty("user.home") + "/halo/";
String distName = "databases_backup_" + DateUtil.format(DateUtil.date(), "yyyyMMddHHmmss"); final String distName = "databases_backup_" + DateUtil.format(DateUtil.date(), "yyyyMMddHHmmss");
//压缩文件 //压缩文件
ZipUtil.zip(srcPath + "halo.mv.db", System.getProperties().getProperty("user.home") + "/halo/backup/databases/" + distName + ".zip"); ZipUtil.zip(srcPath + "halo.mv.db", System.getProperties().getProperty("user.home") + "/halo/backup/databases/" + distName + ".zip");
log.info("Current time: {}, database backup was performed.", DateUtil.now()); log.info("Current time: {}, database backup was performed.", DateUtil.now());
@ -128,9 +130,9 @@ public class BackupController {
if (HaloUtils.getBackUps(BackupTypeEnum.RESOURCES.getDesc()).size() > CommonParamsEnum.TEN.getValue()) { if (HaloUtils.getBackUps(BackupTypeEnum.RESOURCES.getDesc()).size() > CommonParamsEnum.TEN.getValue()) {
FileUtil.del(System.getProperties().getProperty("user.home") + "/halo/backup/resources/"); FileUtil.del(System.getProperties().getProperty("user.home") + "/halo/backup/resources/");
} }
File path = new File(ResourceUtils.getURL("classpath:").getPath()); final File path = new File(ResourceUtils.getURL("classpath:").getPath());
String srcPath = path.getAbsolutePath(); final String srcPath = path.getAbsolutePath();
String distName = "resources_backup_" + DateUtil.format(DateUtil.date(), "yyyyMMddHHmmss"); final String distName = "resources_backup_" + DateUtil.format(DateUtil.date(), "yyyyMMddHHmmss");
//执行打包 //执行打包
ZipUtil.zip(srcPath, System.getProperties().getProperty("user.home") + "/halo/backup/resources/" + distName + ".zip"); ZipUtil.zip(srcPath, System.getProperties().getProperty("user.home") + "/halo/backup/resources/" + distName + ".zip");
log.info("Current time: {}, the resource file backup was performed.", DateUtil.now()); log.info("Current time: {}, the resource file backup was performed.", DateUtil.now());
@ -147,15 +149,15 @@ public class BackupController {
* @return JsonResult * @return JsonResult
*/ */
public JsonResult backupPosts() { public JsonResult backupPosts() {
List<Post> posts = postService.findAll(PostTypeEnum.POST_TYPE_POST.getDesc()); final List<Post> posts = postService.findAll(PostTypeEnum.POST_TYPE_POST.getDesc());
posts.addAll(postService.findAll(PostTypeEnum.POST_TYPE_PAGE.getDesc())); posts.addAll(postService.findAll(PostTypeEnum.POST_TYPE_PAGE.getDesc()));
try { try {
if (HaloUtils.getBackUps(BackupTypeEnum.POSTS.getDesc()).size() > CommonParamsEnum.TEN.getValue()) { if (HaloUtils.getBackUps(BackupTypeEnum.POSTS.getDesc()).size() > CommonParamsEnum.TEN.getValue()) {
FileUtil.del(System.getProperties().getProperty("user.home") + "/halo/backup/posts/"); FileUtil.del(System.getProperties().getProperty("user.home") + "/halo/backup/posts/");
} }
//打包好的文件名 //打包好的文件名
String distName = "posts_backup_" + DateUtil.format(DateUtil.date(), "yyyyMMddHHmmss"); final String distName = "posts_backup_" + DateUtil.format(DateUtil.date(), "yyyyMMddHHmmss");
String srcPath = System.getProperties().getProperty("user.home") + "/halo/backup/posts/" + distName; final String srcPath = System.getProperties().getProperty("user.home") + "/halo/backup/posts/" + distName;
for (Post post : posts) { for (Post post : posts) {
HaloUtils.postToFile(post.getPostContentMd(), srcPath, post.getPostTitle() + ".md"); HaloUtils.postToFile(post.getPostContentMd(), srcPath, post.getPostTitle() + ".md");
} }
@ -175,13 +177,14 @@ public class BackupController {
* *
* @param fileName * @param fileName
* @param type * @param type
*
* @return JsonResult * @return JsonResult
*/ */
@GetMapping(value = "delBackup") @GetMapping(value = "delBackup")
@ResponseBody @ResponseBody
public JsonResult delBackup(@RequestParam("fileName") String fileName, public JsonResult delBackup(@RequestParam("fileName") String fileName,
@RequestParam("type") String type) { @RequestParam("type") String type) {
String srcPath = System.getProperties().getProperty("user.home") + "/halo/backup/" + type + "/" + fileName; final String srcPath = System.getProperties().getProperty("user.home") + "/halo/backup/" + type + "/" + fileName;
try { try {
FileUtil.del(srcPath); FileUtil.del(srcPath);
return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), localeMessageUtil.getMessage("code.admin.common.delete-success")); return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), localeMessageUtil.getMessage("code.admin.common.delete-success"));
@ -195,6 +198,7 @@ public class BackupController {
* *
* @param fileName * @param fileName
* @param type * @param type
*
* @return JsonResult * @return JsonResult
*/ */
@GetMapping(value = "sendToEmail") @GetMapping(value = "sendToEmail")
@ -202,9 +206,9 @@ public class BackupController {
public JsonResult sendToEmail(@RequestParam("fileName") String fileName, public JsonResult sendToEmail(@RequestParam("fileName") String fileName,
@RequestParam("type") String type, @RequestParam("type") String type,
HttpSession session) { HttpSession session) {
String srcPath = System.getProperties().getProperty("user.home") + "/halo/backup/" + type + "/" + fileName; final String srcPath = System.getProperties().getProperty("user.home") + "/halo/backup/" + type + "/" + fileName;
User user = (User) session.getAttribute(HaloConst.USER_SESSION_KEY); final User user = (User) session.getAttribute(HaloConst.USER_SESSION_KEY);
if (null == user.getUserEmail() || StrUtil.equals(user.getUserEmail(), "")) { if (null == user.getUserEmail() || StrUtil.isEmpty(user.getUserEmail())) {
return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.backup.no-email")); return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.backup.no-email"));
} }
if (StrUtil.equals(HaloConst.OPTIONS.get(BlogPropertiesEnum.SMTP_EMAIL_ENABLE.getProp()), TrueFalseEnum.FALSE.getDesc())) { if (StrUtil.equals(HaloConst.OPTIONS.get(BlogPropertiesEnum.SMTP_EMAIL_ENABLE.getProp()), TrueFalseEnum.FALSE.getDesc())) {
@ -228,8 +232,8 @@ public class BackupController {
@Override @Override
public void run() { public void run() {
File file = new File(srcPath); final File file = new File(srcPath);
Map<String, Object> content = new HashMap<>(3); final Map<String, Object> content = new HashMap<>(3);
try { try {
content.put("fileName", file.getName()); content.put("fileName", file.getName());
content.put("createAt", HaloUtils.getCreateTime(srcPath)); content.put("createAt", HaloUtils.getCreateTime(srcPath));

View File

@ -104,7 +104,7 @@ public class CategoryController {
*/ */
@GetMapping(value = "/edit") @GetMapping(value = "/edit")
public String toEditCategory(Model model, @RequestParam("cateId") Long cateId) { public String toEditCategory(Model model, @RequestParam("cateId") Long cateId) {
Optional<Category> category = categoryService.findByCateId(cateId); final Optional<Category> category = categoryService.findByCateId(cateId);
model.addAttribute("updateCategory", category.orElse(new Category())); model.addAttribute("updateCategory", category.orElse(new Category()));
return "admin/admin_category"; return "admin/admin_category";
} }

View File

@ -62,6 +62,7 @@ public class CommentController extends BaseController {
* @param status status * @param status status
* @param page page * @param page page
* @param size size * @param size size
*
* @return admin/admin_comment * @return admin/admin_comment
*/ */
@GetMapping @GetMapping
@ -69,9 +70,9 @@ public class CommentController extends BaseController {
@RequestParam(value = "status", defaultValue = "0") Integer status, @RequestParam(value = "status", defaultValue = "0") Integer status,
@RequestParam(value = "page", defaultValue = "0") Integer page, @RequestParam(value = "page", defaultValue = "0") Integer page,
@RequestParam(value = "size", defaultValue = "10") Integer size) { @RequestParam(value = "size", defaultValue = "10") Integer size) {
Sort sort = new Sort(Sort.Direction.DESC, "commentDate"); final Sort sort = new Sort(Sort.Direction.DESC, "commentDate");
Pageable pageable = PageRequest.of(page, size, sort); final Pageable pageable = PageRequest.of(page, size, sort);
Page<Comment> comments = commentService.findAll(status,pageable); final Page<Comment> comments = commentService.findAll(status, pageable);
model.addAttribute("comments", comments); model.addAttribute("comments", comments);
model.addAttribute("publicCount", commentService.getCountByStatus(CommentStatusEnum.PUBLISHED.getCode())); model.addAttribute("publicCount", commentService.getCountByStatus(CommentStatusEnum.PUBLISHED.getCode()));
model.addAttribute("checkCount", commentService.getCountByStatus(CommentStatusEnum.CHECKING.getCode())); model.addAttribute("checkCount", commentService.getCountByStatus(CommentStatusEnum.CHECKING.getCode()));
@ -85,6 +86,7 @@ public class CommentController extends BaseController {
* *
* @param commentId * @param commentId
* @param status * @param status
*
* @return /admin/comments * @return /admin/comments
*/ */
@GetMapping(value = "/throw") @GetMapping(value = "/throw")
@ -105,15 +107,16 @@ public class CommentController extends BaseController {
* @param commentId * @param commentId
* @param status * @param status
* @param session session * @param session session
*
* @return /admin/comments * @return /admin/comments
*/ */
@GetMapping(value = "/revert") @GetMapping(value = "/revert")
public String moveToPublish(@RequestParam("commentId") Long commentId, public String moveToPublish(@RequestParam("commentId") Long commentId,
@RequestParam("status") Integer status, @RequestParam("status") Integer status,
HttpSession session) { HttpSession session) {
Comment comment = commentService.updateCommentStatus(commentId, CommentStatusEnum.PUBLISHED.getCode()); final Comment comment = commentService.updateCommentStatus(commentId, CommentStatusEnum.PUBLISHED.getCode());
Post post = comment.getPost(); final Post post = comment.getPost();
User user = (User) session.getAttribute(HaloConst.USER_SESSION_KEY); final User user = (User) session.getAttribute(HaloConst.USER_SESSION_KEY);
//判断是否启用邮件服务 //判断是否启用邮件服务
new NoticeToAuthor(comment, post, user, status).start(); new NoticeToAuthor(comment, post, user, status).start();
@ -126,6 +129,7 @@ public class CommentController extends BaseController {
* @param commentId commentId * @param commentId commentId
* @param status status * @param status status
* @param page * @param page
*
* @return string /admin/comments * @return string /admin/comments
*/ */
@GetMapping(value = "/remove") @GetMapping(value = "/remove")
@ -146,6 +150,7 @@ public class CommentController extends BaseController {
* *
* @param commentId * @param commentId
* @param commentContent * @param commentContent
*
* @return JsonResult * @return JsonResult
*/ */
@PostMapping(value = "/reply") @PostMapping(value = "/reply")
@ -157,20 +162,20 @@ public class CommentController extends BaseController {
HttpServletRequest request, HttpServletRequest request,
HttpSession session) { HttpSession session) {
try { try {
Post post = postService.findByPostId(postId).orElse(new Post()); final Post post = postService.findByPostId(postId).orElse(new Post());
//博主信息 //博主信息
User user = (User) session.getAttribute(HaloConst.USER_SESSION_KEY); final User user = (User) session.getAttribute(HaloConst.USER_SESSION_KEY);
//被回复的评论 //被回复的评论
Comment lastComment = commentService.findCommentById(commentId).orElse(new Comment()); final Comment lastComment = commentService.findCommentById(commentId).orElse(new Comment());
//修改被回复的评论的状态 //修改被回复的评论的状态
lastComment.setCommentStatus(CommentStatusEnum.PUBLISHED.getCode()); lastComment.setCommentStatus(CommentStatusEnum.PUBLISHED.getCode());
commentService.save(lastComment); commentService.save(lastComment);
//保存评论 //保存评论
Comment comment = new Comment(); final Comment comment = new Comment();
comment.setPost(post); comment.setPost(post);
comment.setCommentAuthor(user.getUserDisplayName()); comment.setCommentAuthor(user.getUserDisplayName());
comment.setCommentAuthorEmail(user.getUserEmail()); comment.setCommentAuthorEmail(user.getUserEmail());
@ -179,7 +184,7 @@ public class CommentController extends BaseController {
comment.setCommentAuthorAvatarMd5(SecureUtil.md5(user.getUserEmail())); comment.setCommentAuthorAvatarMd5(SecureUtil.md5(user.getUserEmail()));
comment.setCommentDate(DateUtil.date()); comment.setCommentDate(DateUtil.date());
StrBuilder buildContent = new StrBuilder("<a href='#comment-id-"); final StrBuilder buildContent = new StrBuilder("<a href='#comment-id-");
buildContent.append(lastComment.getCommentId()); buildContent.append(lastComment.getCommentId());
buildContent.append("'>@"); buildContent.append("'>@");
buildContent.append(lastComment.getCommentAuthor()); buildContent.append(lastComment.getCommentAuthor());
@ -225,12 +230,12 @@ public class CommentController extends BaseController {
public void run() { public void run() {
if (StrUtil.equals(HaloConst.OPTIONS.get(BlogPropertiesEnum.SMTP_EMAIL_ENABLE.getProp()), TrueFalseEnum.TRUE.getDesc()) && StrUtil.equals(HaloConst.OPTIONS.get(BlogPropertiesEnum.COMMENT_REPLY_NOTICE.getProp()), TrueFalseEnum.TRUE.getDesc())) { if (StrUtil.equals(HaloConst.OPTIONS.get(BlogPropertiesEnum.SMTP_EMAIL_ENABLE.getProp()), TrueFalseEnum.TRUE.getDesc()) && StrUtil.equals(HaloConst.OPTIONS.get(BlogPropertiesEnum.COMMENT_REPLY_NOTICE.getProp()), TrueFalseEnum.TRUE.getDesc())) {
if (Validator.isEmail(lastComment.getCommentAuthorEmail())) { if (Validator.isEmail(lastComment.getCommentAuthorEmail())) {
Map<String, Object> map = new HashMap<>(8); final Map<String, Object> map = new HashMap<>(8);
map.put("blogTitle", HaloConst.OPTIONS.get(BlogPropertiesEnum.BLOG_TITLE.getProp())); map.put("blogTitle", HaloConst.OPTIONS.get(BlogPropertiesEnum.BLOG_TITLE.getProp()));
map.put("commentAuthor", lastComment.getCommentAuthor()); map.put("commentAuthor", lastComment.getCommentAuthor());
map.put("pageName", lastComment.getPost().getPostTitle()); map.put("pageName", lastComment.getPost().getPostTitle());
StrBuilder pageUrl = new StrBuilder(HaloConst.OPTIONS.get(BlogPropertiesEnum.BLOG_URL.getProp())); final StrBuilder pageUrl = new StrBuilder(HaloConst.OPTIONS.get(BlogPropertiesEnum.BLOG_URL.getProp()));
if (StrUtil.equals(post.getPostType(), PostTypeEnum.POST_TYPE_POST.getDesc())) { if (StrUtil.equals(post.getPostType(), PostTypeEnum.POST_TYPE_POST.getDesc())) {
pageUrl.append("/archives/"); pageUrl.append("/archives/");
} else { } else {
@ -274,9 +279,9 @@ public class CommentController extends BaseController {
if (StrUtil.equals(HaloConst.OPTIONS.get(BlogPropertiesEnum.SMTP_EMAIL_ENABLE.getProp()), TrueFalseEnum.TRUE.getDesc()) && StrUtil.equals(HaloConst.OPTIONS.get(BlogPropertiesEnum.COMMENT_REPLY_NOTICE.getProp()), TrueFalseEnum.TRUE.getDesc())) { if (StrUtil.equals(HaloConst.OPTIONS.get(BlogPropertiesEnum.SMTP_EMAIL_ENABLE.getProp()), TrueFalseEnum.TRUE.getDesc()) && StrUtil.equals(HaloConst.OPTIONS.get(BlogPropertiesEnum.COMMENT_REPLY_NOTICE.getProp()), TrueFalseEnum.TRUE.getDesc())) {
try { try {
if (status == 1 && Validator.isEmail(comment.getCommentAuthorEmail())) { if (status == 1 && Validator.isEmail(comment.getCommentAuthorEmail())) {
Map<String, Object> map = new HashMap<>(6); final Map<String, Object> map = new HashMap<>(6);
StrBuilder pageUrl = new StrBuilder(HaloConst.OPTIONS.get(BlogPropertiesEnum.BLOG_URL.getProp())); final StrBuilder pageUrl = new StrBuilder(HaloConst.OPTIONS.get(BlogPropertiesEnum.BLOG_URL.getProp()));
if (StrUtil.equals(post.getPostType(), PostTypeEnum.POST_TYPE_POST.getDesc())) { if (StrUtil.equals(post.getPostType(), PostTypeEnum.POST_TYPE_POST.getDesc())) {
pageUrl.append("/archives/"); pageUrl.append("/archives/");
} else { } else {

View File

@ -75,7 +75,7 @@ public class MenuController {
*/ */
@GetMapping(value = "/edit") @GetMapping(value = "/edit")
public String updateMenu(@RequestParam("menuId") Long menuId, Model model) { public String updateMenu(@RequestParam("menuId") Long menuId, Model model) {
Menu menu = menuService.findByMenuId(menuId).orElse(new Menu()); final Menu menu = menuService.findByMenuId(menuId).orElse(new Menu());
model.addAttribute("updateMenu", menu); model.addAttribute("updateMenu", menu);
return "/admin/admin_menu"; return "/admin/admin_menu";
} }

View File

@ -10,7 +10,9 @@ import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import javax.servlet.http.HttpSession;
import java.util.Map; import java.util.Map;
/** /**
@ -49,17 +51,19 @@ public class OptionController {
* *
* *
* @param options options * @param options options
*
* @return JsonResult * @return JsonResult
*/ */
@PostMapping(value = "/save") @PostMapping(value = "/save")
@ResponseBody @ResponseBody
public JsonResult saveOptions(@RequestParam Map<String, String> options) { public JsonResult saveOptions(@RequestParam Map<String, String> options, HttpSession session) {
try { try {
optionsService.saveOptions(options); optionsService.saveOptions(options);
//刷新options //刷新options
configuration.setSharedVariable("options", optionsService.findAllOptions()); configuration.setSharedVariable("options", optionsService.findAllOptions());
HaloConst.OPTIONS.clear(); HaloConst.OPTIONS.clear();
HaloConst.OPTIONS = optionsService.findAllOptions(); HaloConst.OPTIONS = optionsService.findAllOptions();
session.removeAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME);
log.info("List of saved options: " + options); log.info("List of saved options: " + options);
return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), localeMessageUtil.getMessage("code.admin.common.save-success")); return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), localeMessageUtil.getMessage("code.admin.common.save-success"));
} catch (Exception e) { } catch (Exception e) {

View File

@ -77,7 +77,7 @@ public class PageController {
*/ */
@GetMapping @GetMapping
public String pages(Model model) { public String pages(Model model) {
List<Post> posts = postService.findAll(PostTypeEnum.POST_TYPE_PAGE.getDesc()); final List<Post> posts = postService.findAll(PostTypeEnum.POST_TYPE_PAGE.getDesc());
model.addAttribute("pages", posts); model.addAttribute("pages", posts);
return "admin/admin_page"; return "admin/admin_page";
} }
@ -102,7 +102,7 @@ public class PageController {
*/ */
@GetMapping(value = "/links/edit") @GetMapping(value = "/links/edit")
public String toEditLink(Model model, @RequestParam("linkId") Long linkId) { public String toEditLink(Model model, @RequestParam("linkId") Long linkId) {
Optional<Link> link = linkService.findByLinkId(linkId); final Optional<Link> link = linkService.findByLinkId(linkId);
model.addAttribute("updateLink", link.orElse(new Link())); model.addAttribute("updateLink", link.orElse(new Link()));
return "admin/admin_page_link"; return "admin/admin_page_link";
} }
@ -159,9 +159,9 @@ public class PageController {
public String gallery(Model model, public String gallery(Model model,
@RequestParam(value = "page", defaultValue = "0") Integer page, @RequestParam(value = "page", defaultValue = "0") Integer page,
@RequestParam(value = "size", defaultValue = "18") Integer size) { @RequestParam(value = "size", defaultValue = "18") Integer size) {
Sort sort = new Sort(Sort.Direction.DESC, "galleryId"); final Sort sort = new Sort(Sort.Direction.DESC, "galleryId");
Pageable pageable = PageRequest.of(page, size, sort); final Pageable pageable = PageRequest.of(page, size, sort);
Page<Gallery> galleries = galleryService.findAll(pageable); final Page<Gallery> galleries = galleryService.findAll(pageable);
model.addAttribute("galleries", galleries); model.addAttribute("galleries", galleries);
return "admin/admin_page_gallery"; return "admin/admin_page_gallery";
} }
@ -196,8 +196,8 @@ public class PageController {
*/ */
@GetMapping(value = "/gallery") @GetMapping(value = "/gallery")
public String gallery(Model model, @RequestParam("galleryId") Long galleryId) { public String gallery(Model model, @RequestParam("galleryId") Long galleryId) {
Optional<Gallery> gallery = galleryService.findByGalleryId(galleryId); final Optional<Gallery> gallery = galleryService.findByGalleryId(galleryId);
model.addAttribute("gallery", gallery.get()); model.addAttribute("gallery", gallery.orElse(new Gallery()));
return "admin/widget/_gallery-detail"; return "admin/widget/_gallery-detail";
} }
@ -229,7 +229,7 @@ public class PageController {
*/ */
@GetMapping(value = "/new") @GetMapping(value = "/new")
public String newPage(Model model) { public String newPage(Model model) {
List<String> customTpls = HaloUtils.getCustomTpl(HaloConst.OPTIONS.get(BlogPropertiesEnum.THEME.getProp())); final List<String> customTpls = HaloUtils.getCustomTpl(HaloConst.OPTIONS.get(BlogPropertiesEnum.THEME.getProp()));
model.addAttribute("customTpls", customTpls); model.addAttribute("customTpls", customTpls);
return "admin/admin_page_md_editor"; return "admin/admin_page_md_editor";
} }
@ -246,11 +246,11 @@ public class PageController {
String msg = localeMessageUtil.getMessage("code.admin.common.save-success"); String msg = localeMessageUtil.getMessage("code.admin.common.save-success");
try { try {
//发表用户 //发表用户
User user = (User) session.getAttribute(HaloConst.USER_SESSION_KEY); final User user = (User) session.getAttribute(HaloConst.USER_SESSION_KEY);
post.setUser(user); post.setUser(user);
post.setPostType(PostTypeEnum.POST_TYPE_PAGE.getDesc()); post.setPostType(PostTypeEnum.POST_TYPE_PAGE.getDesc());
if (null != post.getPostId()) { if (null != post.getPostId()) {
Post oldPost = postService.findByPostId(post.getPostId()).get(); final Post oldPost = postService.findByPostId(post.getPostId()).get();
if (null == post.getPostDate()) { if (null == post.getPostDate()) {
post.setPostDate(DateUtil.date()); post.setPostDate(DateUtil.date());
} }
@ -284,8 +284,8 @@ public class PageController {
*/ */
@GetMapping(value = "/edit") @GetMapping(value = "/edit")
public String editPage(@RequestParam("pageId") Long pageId, Model model) { public String editPage(@RequestParam("pageId") Long pageId, Model model) {
Optional<Post> post = postService.findByPostId(pageId); final Optional<Post> post = postService.findByPostId(pageId);
List<String> customTpls = HaloUtils.getCustomTpl(HaloConst.OPTIONS.get(BlogPropertiesEnum.THEME.getProp())); final List<String> customTpls = HaloUtils.getCustomTpl(HaloConst.OPTIONS.get(BlogPropertiesEnum.THEME.getProp()));
model.addAttribute("post", post.orElse(new Post())); model.addAttribute("post", post.orElse(new Post()));
model.addAttribute("customTpls", customTpls); model.addAttribute("customTpls", customTpls);
return "admin/admin_page_md_editor"; return "admin/admin_page_md_editor";
@ -301,7 +301,7 @@ public class PageController {
@GetMapping(value = "/checkUrl") @GetMapping(value = "/checkUrl")
@ResponseBody @ResponseBody
public JsonResult checkUrlExists(@RequestParam("postUrl") String postUrl) { public JsonResult checkUrlExists(@RequestParam("postUrl") String postUrl) {
Post post = postService.findByPostUrl(postUrl, PostTypeEnum.POST_TYPE_PAGE.getDesc()); final Post post = postService.findByPostUrl(postUrl, PostTypeEnum.POST_TYPE_PAGE.getDesc());
if (null != post) { if (null != post) {
return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.common.url-is-exists")); return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.common.url-is-exists"));
} }

View File

@ -92,9 +92,9 @@ public class PostController extends BaseController {
@RequestParam(value = "status", defaultValue = "0") Integer status, @RequestParam(value = "status", defaultValue = "0") Integer status,
@RequestParam(value = "page", defaultValue = "0") Integer page, @RequestParam(value = "page", defaultValue = "0") Integer page,
@RequestParam(value = "size", defaultValue = "10") Integer size) { @RequestParam(value = "size", defaultValue = "10") Integer size) {
Sort sort = new Sort(Sort.Direction.DESC, "postDate"); final Sort sort = new Sort(Sort.Direction.DESC, "postDate");
Pageable pageable = PageRequest.of(page, size, sort); final Pageable pageable = PageRequest.of(page, size, sort);
Page<Post> posts = postService.findPostByStatus(status, PostTypeEnum.POST_TYPE_POST.getDesc(), pageable); final Page<Post> posts = postService.findPostByStatus(status, PostTypeEnum.POST_TYPE_POST.getDesc(), pageable);
model.addAttribute("posts", posts); model.addAttribute("posts", posts);
model.addAttribute("publishCount", postService.getCountByStatus(PostStatusEnum.PUBLISHED.getCode())); model.addAttribute("publishCount", postService.getCountByStatus(PostStatusEnum.PUBLISHED.getCode()));
model.addAttribute("draftCount", postService.getCountByStatus(PostStatusEnum.DRAFT.getCode())); model.addAttribute("draftCount", postService.getCountByStatus(PostStatusEnum.DRAFT.getCode()));
@ -119,8 +119,8 @@ public class PostController extends BaseController {
@RequestParam(value = "size", defaultValue = "10") Integer size) { @RequestParam(value = "size", defaultValue = "10") Integer size) {
try { try {
//排序规则 //排序规则
Sort sort = new Sort(Sort.Direction.DESC, "postId"); final Sort sort = new Sort(Sort.Direction.DESC, "postId");
Pageable pageable = PageRequest.of(page, size, sort); final Pageable pageable = PageRequest.of(page, size, sort);
model.addAttribute("posts", postService.searchPosts(keyword, pageable)); model.addAttribute("posts", postService.searchPosts(keyword, pageable));
} catch (Exception e) { } catch (Exception e) {
log.error("未知错误:{}", e.getMessage()); log.error("未知错误:{}", e.getMessage());
@ -137,7 +137,7 @@ public class PostController extends BaseController {
*/ */
@GetMapping(value = "/view") @GetMapping(value = "/view")
public String viewPost(@RequestParam("postId") Long postId, Model model) { public String viewPost(@RequestParam("postId") Long postId, Model model) {
Optional<Post> post = postService.findByPostId(postId); final Optional<Post> post = postService.findByPostId(postId);
model.addAttribute("post", post.orElse(new Post())); model.addAttribute("post", post.orElse(new Post()));
return this.render("post"); return this.render("post");
} }
@ -161,8 +161,8 @@ public class PostController extends BaseController {
*/ */
@GetMapping(value = "/edit") @GetMapping(value = "/edit")
public String editPost(@RequestParam("postId") Long postId, Model model) { public String editPost(@RequestParam("postId") Long postId, Model model) {
Optional<Post> post = postService.findByPostId(postId); final Optional<Post> post = postService.findByPostId(postId);
model.addAttribute("post", post.get()); model.addAttribute("post", post.orElse(new Post()));
return "admin/admin_post_edit"; return "admin/admin_post_edit";
} }
@ -180,7 +180,7 @@ public class PostController extends BaseController {
@RequestParam("cateList") List<String> cateList, @RequestParam("cateList") List<String> cateList,
@RequestParam("tagList") String tagList, @RequestParam("tagList") String tagList,
HttpSession session) { HttpSession session) {
User user = (User) session.getAttribute(HaloConst.USER_SESSION_KEY); final User user = (User) session.getAttribute(HaloConst.USER_SESSION_KEY);
try { try {
post.setPostContent(MarkdownUtils.renderMarkdown(post.getPostContentMd())); post.setPostContent(MarkdownUtils.renderMarkdown(post.getPostContentMd()));
//摘要字数 //摘要字数
@ -189,9 +189,9 @@ public class PostController extends BaseController {
postSummary = Integer.parseInt(HaloConst.OPTIONS.get(BlogPropertiesEnum.POST_SUMMARY.getProp())); postSummary = Integer.parseInt(HaloConst.OPTIONS.get(BlogPropertiesEnum.POST_SUMMARY.getProp()));
} }
//设置文章摘要 //设置文章摘要
String summaryText = StrUtil.cleanBlank(HtmlUtil.cleanHtmlTag(post.getPostContent())); final String summaryText = StrUtil.cleanBlank(HtmlUtil.cleanHtmlTag(post.getPostContent()));
if (summaryText.length() > postSummary) { if (summaryText.length() > postSummary) {
String summary = summaryText.substring(0, postSummary); final String summary = summaryText.substring(0, postSummary);
post.setPostSummary(summary); post.setPostSummary(summary);
} else { } else {
post.setPostSummary(summaryText); post.setPostSummary(summaryText);
@ -231,7 +231,7 @@ public class PostController extends BaseController {
@RequestParam("cateList") List<String> cateList, @RequestParam("cateList") List<String> cateList,
@RequestParam("tagList") String tagList) { @RequestParam("tagList") String tagList) {
//old data //old data
Post oldPost = postService.findByPostId(post.getPostId()).orElse(new Post()); final Post oldPost = postService.findByPostId(post.getPostId()).orElse(new Post());
post.setPostUpdate(new Date()); post.setPostUpdate(new Date());
post.setPostViews(oldPost.getPostViews()); post.setPostViews(oldPost.getPostViews());
post.setPostContent(MarkdownUtils.renderMarkdown(post.getPostContentMd())); post.setPostContent(MarkdownUtils.renderMarkdown(post.getPostContentMd()));
@ -245,9 +245,9 @@ public class PostController extends BaseController {
postSummary = Integer.parseInt(HaloConst.OPTIONS.get(BlogPropertiesEnum.POST_SUMMARY.getProp())); postSummary = Integer.parseInt(HaloConst.OPTIONS.get(BlogPropertiesEnum.POST_SUMMARY.getProp()));
} }
//设置文章摘要 //设置文章摘要
String summaryText = StrUtil.cleanBlank(HtmlUtil.cleanHtmlTag(post.getPostContent())); final String summaryText = StrUtil.cleanBlank(HtmlUtil.cleanHtmlTag(post.getPostContent()));
if (summaryText.length() > postSummary) { if (summaryText.length() > postSummary) {
String summary = summaryText.substring(0, postSummary); final String summary = summaryText.substring(0, postSummary);
post.setPostSummary(summary); post.setPostSummary(summary);
} else { } else {
post.setPostSummary(summaryText); post.setPostSummary(summaryText);
@ -309,7 +309,7 @@ public class PostController extends BaseController {
@GetMapping(value = "/remove") @GetMapping(value = "/remove")
public String removePost(@RequestParam("postId") Long postId, @RequestParam("postType") String postType) { public String removePost(@RequestParam("postId") Long postId, @RequestParam("postType") String postType) {
try { try {
Optional<Post> post = postService.findByPostId(postId); final Optional<Post> post = postService.findByPostId(postId);
postService.remove(postId); postService.remove(postId);
logsService.save(LogsRecord.REMOVE_POST, post.get().getPostTitle(), request); logsService.save(LogsRecord.REMOVE_POST, post.get().getPostTitle(), request);
} catch (Exception e) { } catch (Exception e) {
@ -350,7 +350,7 @@ public class PostController extends BaseController {
@ResponseBody @ResponseBody
public JsonResult checkUrlExists(@RequestParam("postUrl") String postUrl) { public JsonResult checkUrlExists(@RequestParam("postUrl") String postUrl) {
postUrl = urlFilter(postUrl); postUrl = urlFilter(postUrl);
Post post = postService.findByPostUrl(postUrl, PostTypeEnum.POST_TYPE_POST.getDesc()); final Post post = postService.findByPostUrl(postUrl, PostTypeEnum.POST_TYPE_POST.getDesc());
if (null != post) { if (null != post) {
return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.common.url-is-exists")); return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.common.url-is-exists"));
} }
@ -369,16 +369,16 @@ public class PostController extends BaseController {
if (StrUtil.isBlank(baiduToken)) { if (StrUtil.isBlank(baiduToken)) {
return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.post.no-baidu-token")); return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.post.no-baidu-token"));
} }
String blogUrl = HaloConst.OPTIONS.get(BlogPropertiesEnum.BLOG_URL.getProp()); final String blogUrl = HaloConst.OPTIONS.get(BlogPropertiesEnum.BLOG_URL.getProp());
List<Post> posts = postService.findAll(PostTypeEnum.POST_TYPE_POST.getDesc()); final List<Post> posts = postService.findAll(PostTypeEnum.POST_TYPE_POST.getDesc());
StringBuilder urls = new StringBuilder(); final StringBuilder urls = new StringBuilder();
for (Post post : posts) { for (Post post : posts) {
urls.append(blogUrl); urls.append(blogUrl);
urls.append("/archives/"); urls.append("/archives/");
urls.append(post.getPostUrl()); urls.append(post.getPostUrl());
urls.append("\n"); urls.append("\n");
} }
String result = HaloUtils.baiduPost(blogUrl, baiduToken, urls.toString()); final String result = HaloUtils.baiduPost(blogUrl, baiduToken, urls.toString());
if (StrUtil.isEmpty(result)) { if (StrUtil.isEmpty(result)) {
return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.post.push-to-baidu-failed")); return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.post.push-to-baidu-failed"));
} }

View File

@ -14,6 +14,7 @@ import cc.ryanc.halo.web.controller.core.BaseController;
import cn.hutool.core.io.FileUtil; import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileReader; import cn.hutool.core.io.file.FileReader;
import cn.hutool.core.io.file.FileWriter; import cn.hutool.core.io.file.FileWriter;
import cn.hutool.core.text.StrBuilder;
import cn.hutool.core.util.RuntimeUtil; import cn.hutool.core.util.RuntimeUtil;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ZipUtil; import cn.hutool.core.util.ZipUtil;
@ -63,6 +64,7 @@ public class ThemeController extends BaseController {
* *
* *
* @param model model * @param model model
*
* @return admin/admin_theme * @return admin/admin_theme
*/ */
@GetMapping @GetMapping
@ -79,6 +81,7 @@ public class ThemeController extends BaseController {
* *
* @param siteTheme * @param siteTheme
* @param request request * @param request request
*
* @return JsonResult * @return JsonResult
*/ */
@GetMapping(value = "/set") @GetMapping(value = "/set")
@ -108,6 +111,7 @@ public class ThemeController extends BaseController {
* *
* *
* @param file * @param file
*
* @return JsonResult * @return JsonResult
*/ */
@RequestMapping(value = "/upload", method = RequestMethod.POST) @RequestMapping(value = "/upload", method = RequestMethod.POST)
@ -117,8 +121,8 @@ public class ThemeController extends BaseController {
try { try {
if (!file.isEmpty()) { if (!file.isEmpty()) {
//获取项目根路径 //获取项目根路径
File basePath = new File(ResourceUtils.getURL("classpath:").getPath()); final File basePath = new File(ResourceUtils.getURL("classpath:").getPath());
File themePath = new File(basePath.getAbsolutePath(), new StringBuffer("templates/themes/").append(file.getOriginalFilename()).toString()); final File themePath = new File(basePath.getAbsolutePath(), new StringBuffer("templates/themes/").append(file.getOriginalFilename()).toString());
file.transferTo(themePath); file.transferTo(themePath);
log.info("Upload topic success, path is " + themePath.getAbsolutePath()); log.info("Upload topic success, path is " + themePath.getAbsolutePath());
logsService.save(LogsRecord.UPLOAD_THEME, file.getOriginalFilename(), request); logsService.save(LogsRecord.UPLOAD_THEME, file.getOriginalFilename(), request);
@ -141,13 +145,14 @@ public class ThemeController extends BaseController {
* *
* *
* @param themeName * @param themeName
*
* @return string /admin/themes * @return string /admin/themes
*/ */
@GetMapping(value = "/remove") @GetMapping(value = "/remove")
public String removeTheme(@RequestParam("themeName") String themeName) { public String removeTheme(@RequestParam("themeName") String themeName) {
try { try {
File basePath = new File(ResourceUtils.getURL("classpath:").getPath()); final File basePath = new File(ResourceUtils.getURL("classpath:").getPath());
File themePath = new File(basePath.getAbsolutePath(), "templates/themes/" + themeName); final File themePath = new File(basePath.getAbsolutePath(), "templates/themes/" + themeName);
FileUtil.del(themePath); FileUtil.del(themePath);
HaloConst.THEMES.clear(); HaloConst.THEMES.clear();
HaloConst.THEMES = HaloUtils.getThemes(); HaloConst.THEMES = HaloUtils.getThemes();
@ -172,6 +177,7 @@ public class ThemeController extends BaseController {
* *
* @param remoteAddr * @param remoteAddr
* @param themeName * @param themeName
*
* @return JsonResult * @return JsonResult
*/ */
@PostMapping(value = "/clone") @PostMapping(value = "/clone")
@ -182,9 +188,9 @@ public class ThemeController extends BaseController {
return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.common.info-no-complete")); return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.common.info-no-complete"));
} }
try { try {
File basePath = new File(ResourceUtils.getURL("classpath:").getPath()); final File basePath = new File(ResourceUtils.getURL("classpath:").getPath());
File themePath = new File(basePath.getAbsolutePath(), "templates/themes"); final File themePath = new File(basePath.getAbsolutePath(), "templates/themes");
String cmdResult = RuntimeUtil.execForStr("git clone " + remoteAddr + " " + themePath.getAbsolutePath() + "/" + themeName); final String cmdResult = RuntimeUtil.execForStr("git clone " + remoteAddr + " " + themePath.getAbsolutePath() + "/" + themeName);
if (NOT_FOUND_GIT.equals(cmdResult)) { if (NOT_FOUND_GIT.equals(cmdResult)) {
return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.theme.no-git")); return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.theme.no-git"));
} }
@ -201,15 +207,16 @@ public class ThemeController extends BaseController {
* *
* *
* @param themeName * @param themeName
*
* @return JsonResult * @return JsonResult
*/ */
@GetMapping(value = "/pull") @GetMapping(value = "/pull")
@ResponseBody @ResponseBody
public JsonResult pullFromRemote(@RequestParam(value = "themeName") String themeName) { public JsonResult pullFromRemote(@RequestParam(value = "themeName") String themeName) {
try { try {
File basePath = new File(ResourceUtils.getURL("classpath:").getPath()); final File basePath = new File(ResourceUtils.getURL("classpath:").getPath());
File themePath = new File(basePath.getAbsolutePath(), "templates/themes"); final File themePath = new File(basePath.getAbsolutePath(), "templates/themes");
String cmdResult = RuntimeUtil.execForStr("cd " + themePath.getAbsolutePath() + "/" + themeName + " && git pull"); final String cmdResult = RuntimeUtil.execForStr("cd " + themePath.getAbsolutePath() + "/" + themeName, "git pull");
if (NOT_FOUND_GIT.equals(cmdResult)) { if (NOT_FOUND_GIT.equals(cmdResult)) {
return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.theme.no-git")); return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.theme.no-git"));
} }
@ -244,11 +251,12 @@ public class ThemeController extends BaseController {
* *
* *
* @param model model * @param model model
*
* @return admin/admin_theme-editor * @return admin/admin_theme-editor
*/ */
@GetMapping(value = "/editor") @GetMapping(value = "/editor")
public String editor(Model model) { public String editor(Model model) {
List<String> tpls = HaloUtils.getTplName(BaseController.THEME); final List<String> tpls = HaloUtils.getTplName(BaseController.THEME);
model.addAttribute("tpls", tpls); model.addAttribute("tpls", tpls);
return "admin/admin_theme-editor"; return "admin/admin_theme-editor";
} }
@ -257,6 +265,7 @@ public class ThemeController extends BaseController {
* *
* *
* @param tplName * @param tplName
*
* @return * @return
*/ */
@GetMapping(value = "/getTpl", produces = "text/text;charset=UTF-8") @GetMapping(value = "/getTpl", produces = "text/text;charset=UTF-8")
@ -265,10 +274,14 @@ public class ThemeController extends BaseController {
String tplContent = ""; String tplContent = "";
try { try {
//获取项目根路径 //获取项目根路径
File basePath = new File(ResourceUtils.getURL("classpath:").getPath()); final File basePath = new File(ResourceUtils.getURL("classpath:").getPath());
//获取主题路径 //获取主题路径
File themesPath = new File(basePath.getAbsolutePath(), new StringBuffer("templates/themes/").append(BaseController.THEME).append("/").append(tplName).toString()); final StrBuilder themePath = new StrBuilder("templates/themes/");
FileReader fileReader = new FileReader(themesPath); themePath.append(BaseController.THEME);
themePath.append("/");
themePath.append(tplName);
final File themesPath = new File(basePath.getAbsolutePath(), themePath.toString());
final FileReader fileReader = new FileReader(themesPath);
tplContent = fileReader.readString(); tplContent = fileReader.readString();
} catch (Exception e) { } catch (Exception e) {
log.error("Get template file error: {}", e.getMessage()); log.error("Get template file error: {}", e.getMessage());
@ -281,6 +294,7 @@ public class ThemeController extends BaseController {
* *
* @param tplName * @param tplName
* @param tplContent * @param tplContent
*
* @return JsonResult * @return JsonResult
*/ */
@PostMapping(value = "/editor/save") @PostMapping(value = "/editor/save")
@ -292,10 +306,14 @@ public class ThemeController extends BaseController {
} }
try { try {
//获取项目根路径 //获取项目根路径
File basePath = new File(ResourceUtils.getURL("classpath:").getPath()); final File basePath = new File(ResourceUtils.getURL("classpath:").getPath());
//获取主题路径 //获取主题路径
File tplPath = new File(basePath.getAbsolutePath(), new StringBuffer("templates/themes/").append(BaseController.THEME).append("/").append(tplName).toString()); final StrBuilder themePath = new StrBuilder("templates/themes/");
FileWriter fileWriter = new FileWriter(tplPath); themePath.append(BaseController.THEME);
themePath.append("/");
themePath.append(tplName);
final File tplPath = new File(basePath.getAbsolutePath(), themePath.toString());
final FileWriter fileWriter = new FileWriter(tplPath);
fileWriter.write(tplContent); fileWriter.write(tplContent);
} catch (Exception e) { } catch (Exception e) {
log.error("Template save failed: {}", e.getMessage()); log.error("Template save failed: {}", e.getMessage());

View File

@ -92,7 +92,7 @@ public class UserController {
@ModelAttribute("userId") Long userId, @ModelAttribute("userId") Long userId,
HttpSession session) { HttpSession session) {
try { try {
User user = userService.findByUserIdAndUserPass(userId, SecureUtil.md5(beforePass)); final User user = userService.findByUserIdAndUserPass(userId, SecureUtil.md5(beforePass));
if (null != user) { if (null != user) {
user.setUserPass(SecureUtil.md5(newPass)); user.setUserPass(SecureUtil.md5(newPass));
userService.save(user); userService.save(user);

View File

@ -74,7 +74,7 @@ public class ApiArchivesController {
*/ */
@GetMapping(value = "/year") @GetMapping(value = "/year")
public JsonResult archivesYear() { public JsonResult archivesYear() {
List<Archive> archives = postService.findPostGroupByYear(); final List<Archive> archives = postService.findPostGroupByYear();
if (null != archives && archives.size() > 0) { if (null != archives && archives.size() > 0) {
return new JsonResult(ResponseStatusEnum.SUCCESS.getCode(), ResponseStatusEnum.SUCCESS.getMsg(), archives); return new JsonResult(ResponseStatusEnum.SUCCESS.getCode(), ResponseStatusEnum.SUCCESS.getMsg(), archives);
} else { } else {
@ -128,7 +128,7 @@ public class ApiArchivesController {
*/ */
@GetMapping(value = "/year/month") @GetMapping(value = "/year/month")
public JsonResult archivesYearAndMonth() { public JsonResult archivesYearAndMonth() {
List<Archive> archives = postService.findPostGroupByYearAndMonth(); final List<Archive> archives = postService.findPostGroupByYearAndMonth();
if (null != archives && archives.size() > 0) { if (null != archives && archives.size() > 0) {
return new JsonResult(ResponseStatusEnum.SUCCESS.getCode(), ResponseStatusEnum.SUCCESS.getMsg(), archives); return new JsonResult(ResponseStatusEnum.SUCCESS.getCode(), ResponseStatusEnum.SUCCESS.getMsg(), archives);
} else { } else {

View File

@ -82,7 +82,7 @@ public class ApiCategoryController {
*/ */
@GetMapping(value = "/{cateUrl}") @GetMapping(value = "/{cateUrl}")
public JsonResult categories(@PathVariable("cateUrl") String cateUrl) { public JsonResult categories(@PathVariable("cateUrl") String cateUrl) {
Category category = categoryService.findByCateUrl(cateUrl); final Category category = categoryService.findByCateUrl(cateUrl);
if (null != category) { if (null != category) {
return new JsonResult(ResponseStatusEnum.SUCCESS.getCode(), ResponseStatusEnum.SUCCESS.getMsg(), category); return new JsonResult(ResponseStatusEnum.SUCCESS.getCode(), ResponseStatusEnum.SUCCESS.getMsg(), category);
} else { } else {

View File

@ -54,7 +54,7 @@ public class ApiGalleryController {
*/ */
@GetMapping @GetMapping
public JsonResult galleries() { public JsonResult galleries() {
List<Gallery> galleries = galleryService.findAll(); final List<Gallery> galleries = galleryService.findAll();
if (null != galleries && galleries.size() > 0) { if (null != galleries && galleries.size() > 0) {
return new JsonResult(ResponseStatusEnum.SUCCESS.getCode(), ResponseStatusEnum.SUCCESS.getMsg(), galleries); return new JsonResult(ResponseStatusEnum.SUCCESS.getCode(), ResponseStatusEnum.SUCCESS.getMsg(), galleries);
} else { } else {
@ -91,7 +91,7 @@ public class ApiGalleryController {
*/ */
@GetMapping(value = "/{id}") @GetMapping(value = "/{id}")
public JsonResult galleries(@PathVariable("id") Long id) { public JsonResult galleries(@PathVariable("id") Long id) {
Optional<Gallery> gallery = galleryService.findByGalleryId(id); final Optional<Gallery> gallery = galleryService.findByGalleryId(id);
if (gallery.isPresent()) { if (gallery.isPresent()) {
return new JsonResult(ResponseStatusEnum.SUCCESS.getCode(), ResponseStatusEnum.SUCCESS.getMsg(), gallery.get()); return new JsonResult(ResponseStatusEnum.SUCCESS.getCode(), ResponseStatusEnum.SUCCESS.getMsg(), gallery.get());
} else { } else {

View File

@ -54,7 +54,7 @@ public class ApiLinkController {
*/ */
@GetMapping @GetMapping
public JsonResult links() { public JsonResult links() {
List<Link> links = linkService.findAll(); final List<Link> links = linkService.findAll();
if (null != links && links.size() > 0) { if (null != links && links.size() > 0) {
return new JsonResult(ResponseStatusEnum.SUCCESS.getCode(), ResponseStatusEnum.SUCCESS.getMsg(), links); return new JsonResult(ResponseStatusEnum.SUCCESS.getCode(), ResponseStatusEnum.SUCCESS.getMsg(), links);
} else { } else {

View File

@ -55,7 +55,7 @@ public class ApiMenuController {
*/ */
@GetMapping @GetMapping
public JsonResult menus() { public JsonResult menus() {
List<Menu> menus = menuService.findAll(); final List<Menu> menus = menuService.findAll();
if (null != menus && menus.size() > 0) { if (null != menus && menus.size() > 0) {
return new JsonResult(ResponseStatusEnum.SUCCESS.getCode(), ResponseStatusEnum.SUCCESS.getMsg(), menus); return new JsonResult(ResponseStatusEnum.SUCCESS.getCode(), ResponseStatusEnum.SUCCESS.getMsg(), menus);
} else { } else {

View File

@ -57,7 +57,7 @@ public class ApiOptionController {
*/ */
@GetMapping @GetMapping
public JsonResult options() { public JsonResult options() {
Map<String, String> options = optionsService.findAllOptions(); final Map<String, String> options = optionsService.findAllOptions();
//去掉隐私元素 //去掉隐私元素
options.remove(BlogPropertiesEnum.MAIL_SMTP_HOST.getProp()); options.remove(BlogPropertiesEnum.MAIL_SMTP_HOST.getProp());
options.remove(BlogPropertiesEnum.MAIL_FROM_NAME.getProp()); options.remove(BlogPropertiesEnum.MAIL_FROM_NAME.getProp());
@ -82,11 +82,12 @@ public class ApiOptionController {
* </p> * </p>
* *
* @param optionName * @param optionName
*
* @return JsonResult * @return JsonResult
*/ */
@GetMapping(value = "/{optionName}") @GetMapping(value = "/{optionName}")
public JsonResult option(@PathVariable(value = "optionName") String optionName) { public JsonResult option(@PathVariable(value = "optionName") String optionName) {
String optionValue = optionsService.findOneOption(optionName); final String optionValue = optionsService.findOneOption(optionName);
return new JsonResult(ResponseStatusEnum.SUCCESS.getCode(), ResponseStatusEnum.SUCCESS.getMsg(), optionValue); return new JsonResult(ResponseStatusEnum.SUCCESS.getCode(), ResponseStatusEnum.SUCCESS.getMsg(), optionValue);
} }
} }

View File

@ -58,11 +58,12 @@ public class ApiPageController {
* </p> * </p>
* *
* @param postId postId * @param postId postId
*
* @return JsonResult * @return JsonResult
*/ */
@GetMapping(value = "/{postId}") @GetMapping(value = "/{postId}")
public JsonResult pages(@PathVariable(value = "postId") Long postId) { public JsonResult pages(@PathVariable(value = "postId") Long postId) {
Post post = postService.findByPostId(postId, PostTypeEnum.POST_TYPE_PAGE.getDesc()); final Post post = postService.findByPostId(postId, PostTypeEnum.POST_TYPE_PAGE.getDesc());
if (null != post) { if (null != post) {
postService.cacheViews(post.getPostId()); postService.cacheViews(post.getPostId());
return new JsonResult(ResponseStatusEnum.SUCCESS.getCode(), ResponseStatusEnum.SUCCESS.getMsg(), post); return new JsonResult(ResponseStatusEnum.SUCCESS.getCode(), ResponseStatusEnum.SUCCESS.getMsg(), post);

View File

@ -95,17 +95,18 @@ public class ApiPostController {
* </p> * </p>
* *
* @param page * @param page
*
* @return JsonResult * @return JsonResult
*/ */
@GetMapping(value = "/page/{page}") @GetMapping(value = "/page/{page}")
public JsonResult posts(@PathVariable(value = "page") Integer page) { public JsonResult posts(@PathVariable(value = "page") Integer page) {
Sort sort = new Sort(Sort.Direction.DESC, "postDate"); final Sort sort = new Sort(Sort.Direction.DESC, "postDate");
int size = 10; int size = 10;
if (StrUtil.isNotBlank(HaloConst.OPTIONS.get(BlogPropertiesEnum.INDEX_POSTS.getProp()))) { if (StrUtil.isNotBlank(HaloConst.OPTIONS.get(BlogPropertiesEnum.INDEX_POSTS.getProp()))) {
size = Integer.parseInt(HaloConst.OPTIONS.get(BlogPropertiesEnum.INDEX_POSTS.getProp())); size = Integer.parseInt(HaloConst.OPTIONS.get(BlogPropertiesEnum.INDEX_POSTS.getProp()));
} }
Pageable pageable = PageRequest.of(page - 1, size, sort); final Pageable pageable = PageRequest.of(page - 1, size, sort);
Page<Post> posts = postService.findPostByStatus(PostStatusEnum.PUBLISHED.getCode(), PostTypeEnum.POST_TYPE_POST.getDesc(), pageable); final Page<Post> posts = postService.findPostByStatus(PostStatusEnum.PUBLISHED.getCode(), PostTypeEnum.POST_TYPE_POST.getDesc(), pageable);
if (null == posts) { if (null == posts) {
return new JsonResult(ResponseStatusEnum.EMPTY.getCode(), ResponseStatusEnum.EMPTY.getMsg()); return new JsonResult(ResponseStatusEnum.EMPTY.getCode(), ResponseStatusEnum.EMPTY.getMsg());
} }
@ -146,11 +147,12 @@ public class ApiPostController {
* </p> * </p>
* *
* @param postId * @param postId
*
* @return JsonResult * @return JsonResult
*/ */
@GetMapping(value = "/{postId}") @GetMapping(value = "/{postId}")
public JsonResult posts(@PathVariable(value = "postId") Long postId) { public JsonResult posts(@PathVariable(value = "postId") Long postId) {
Post post = postService.findByPostId(postId, PostTypeEnum.POST_TYPE_POST.getDesc()); final Post post = postService.findByPostId(postId, PostTypeEnum.POST_TYPE_POST.getDesc());
if (null != post) { if (null != post) {
postService.cacheViews(post.getPostId()); postService.cacheViews(post.getPostId());
return new JsonResult(ResponseStatusEnum.SUCCESS.getCode(), ResponseStatusEnum.SUCCESS.getMsg(), post); return new JsonResult(ResponseStatusEnum.SUCCESS.getCode(), ResponseStatusEnum.SUCCESS.getMsg(), post);

View File

@ -49,7 +49,7 @@ public class ApiTagController {
*/ */
@GetMapping @GetMapping
public JsonResult tags() { public JsonResult tags() {
List<Tag> tags = tagService.findAll(); final List<Tag> tags = tagService.findAll();
if (null != tags && tags.size() > 0) { if (null != tags && tags.size() > 0) {
return new JsonResult(ResponseStatusEnum.SUCCESS.getCode(), ResponseStatusEnum.SUCCESS.getMsg(), tags); return new JsonResult(ResponseStatusEnum.SUCCESS.getCode(), ResponseStatusEnum.SUCCESS.getMsg(), tags);
} else { } else {
@ -80,7 +80,7 @@ public class ApiTagController {
*/ */
@GetMapping(value = "/{tagUrl}") @GetMapping(value = "/{tagUrl}")
public JsonResult tags(@PathVariable("tagUrl") String tagUrl) { public JsonResult tags(@PathVariable("tagUrl") String tagUrl) {
Tag tag = tagService.findByTagUrl(tagUrl); final Tag tag = tagService.findByTagUrl(tagUrl);
if (null != tag) { if (null != tag) {
return new JsonResult(ResponseStatusEnum.SUCCESS.getCode(), ResponseStatusEnum.SUCCESS.getMsg(), tag); return new JsonResult(ResponseStatusEnum.SUCCESS.getCode(), ResponseStatusEnum.SUCCESS.getMsg(), tag);
} else { } else {

View File

@ -50,7 +50,7 @@ public class ApiUserController {
*/ */
@GetMapping @GetMapping
public JsonResult user() { public JsonResult user() {
User user = userService.findUser(); final User user = userService.findUser();
return new JsonResult(ResponseStatusEnum.SUCCESS.getCode(), ResponseStatusEnum.SUCCESS.getMsg(), user); return new JsonResult(ResponseStatusEnum.SUCCESS.getCode(), ResponseStatusEnum.SUCCESS.getMsg(), user);
} }
} }

View File

@ -24,7 +24,7 @@ public abstract class BaseController {
* @return * @return
*/ */
public String render(String pageName) { public String render(String pageName) {
StrBuilder themeStr = new StrBuilder("themes/"); final StrBuilder themeStr = new StrBuilder("themes/");
themeStr.append(THEME); themeStr.append(THEME);
themeStr.append("/"); themeStr.append("/");
return themeStr.append(pageName).toString(); return themeStr.append(pageName).toString();

View File

@ -30,7 +30,7 @@ public class CommonController implements ErrorController {
*/ */
@GetMapping(value = ERROR_PATH) @GetMapping(value = ERROR_PATH)
public String handleError(HttpServletRequest request) { public String handleError(HttpServletRequest request) {
Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code"); final Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
if (statusCode.equals(CommonParamsEnum.NOT_FOUND.getValue())) { if (statusCode.equals(CommonParamsEnum.NOT_FOUND.getValue())) {
return "redirect:/404"; return "redirect:/404";
} else { } else {

View File

@ -110,7 +110,7 @@ public class InstallController {
return new JsonResult(ResultCodeEnum.FAIL.getCode(), "该博客已初始化,不能再次安装!"); return new JsonResult(ResultCodeEnum.FAIL.getCode(), "该博客已初始化,不能再次安装!");
} }
//创建新的用户 //创建新的用户
User user = new User(); final User user = new User();
user.setUserName(userName); user.setUserName(userName);
if (StrUtil.isBlank(userDisplayName)) { if (StrUtil.isBlank(userDisplayName)) {
userDisplayName = userName; userDisplayName = userName;
@ -121,15 +121,15 @@ public class InstallController {
userService.save(user); userService.save(user);
//默认分类 //默认分类
Category category = new Category(); final Category category = new Category();
category.setCateName("未分类"); category.setCateName("未分类");
category.setCateUrl("default"); category.setCateUrl("default");
category.setCateDesc("未分类"); category.setCateDesc("未分类");
categoryService.save(category); categoryService.save(category);
//第一篇文章 //第一篇文章
Post post = new Post(); final Post post = new Post();
List<Category> categories = new ArrayList<>(); final List<Category> categories = new ArrayList<>();
categories.add(category); categories.add(category);
post.setPostTitle("Hello Halo!"); post.setPostTitle("Hello Halo!");
post.setPostContentMd("# Hello Halo!\n" + post.setPostContentMd("# Hello Halo!\n" +
@ -145,7 +145,7 @@ public class InstallController {
postService.save(post); postService.save(post);
//第一个评论 //第一个评论
Comment comment = new Comment(); final Comment comment = new Comment();
comment.setPost(post); comment.setPost(post);
comment.setCommentAuthor("ruibaby"); comment.setCommentAuthor("ruibaby");
comment.setCommentAuthorEmail("i@ryanc.cc"); comment.setCommentAuthorEmail("i@ryanc.cc");
@ -159,7 +159,7 @@ public class InstallController {
comment.setIsAdmin(0); comment.setIsAdmin(0);
commentService.save(comment); commentService.save(comment);
Map<String, String> options = new HashMap<>(); final Map<String, String> options = new HashMap<>();
options.put(BlogPropertiesEnum.IS_INSTALL.getProp(), TrueFalseEnum.TRUE.getDesc()); options.put(BlogPropertiesEnum.IS_INSTALL.getProp(), TrueFalseEnum.TRUE.getDesc());
options.put(BlogPropertiesEnum.BLOG_LOCALE.getProp(), blogLocale); options.put(BlogPropertiesEnum.BLOG_LOCALE.getProp(), blogLocale);
options.put(BlogPropertiesEnum.BLOG_TITLE.getProp(), blogTitle); options.put(BlogPropertiesEnum.BLOG_TITLE.getProp(), blogTitle);
@ -176,14 +176,14 @@ public class InstallController {
//更新日志 //更新日志
logsService.save(LogsRecord.INSTALL, "安装成功欢迎使用Halo。", request); logsService.save(LogsRecord.INSTALL, "安装成功欢迎使用Halo。", request);
Menu menuIndex = new Menu(); final Menu menuIndex = new Menu();
menuIndex.setMenuName("首页"); menuIndex.setMenuName("首页");
menuIndex.setMenuUrl("/"); menuIndex.setMenuUrl("/");
menuIndex.setMenuSort(1); menuIndex.setMenuSort(1);
menuIndex.setMenuIcon(" "); menuIndex.setMenuIcon(" ");
menuService.save(menuIndex); menuService.save(menuIndex);
Menu menuArchive = new Menu(); final Menu menuArchive = new Menu();
menuArchive.setMenuName("归档"); menuArchive.setMenuName("归档");
menuArchive.setMenuUrl("/archives"); menuArchive.setMenuUrl("/archives");
menuArchive.setMenuSort(2); menuArchive.setMenuSort(2);

View File

@ -74,9 +74,9 @@ public class FrontArchiveController extends BaseController {
@PathVariable(value = "page") Integer page) { @PathVariable(value = "page") Integer page) {
//所有文章数据分页material主题适用 //所有文章数据分页material主题适用
Sort sort = new Sort(Sort.Direction.DESC, "postDate"); final Sort sort = new Sort(Sort.Direction.DESC, "postDate");
Pageable pageable = PageRequest.of(page - 1, 5, sort); final Pageable pageable = PageRequest.of(page - 1, 5, sort);
Page<Post> posts = postService.findPostByStatus(PostStatusEnum.PUBLISHED.getCode(), PostTypeEnum.POST_TYPE_POST.getDesc(), pageable); final Page<Post> posts = postService.findPostByStatus(PostStatusEnum.PUBLISHED.getCode(), PostTypeEnum.POST_TYPE_POST.getDesc(), pageable);
if (null == posts) { if (null == posts) {
return this.renderNotFound(); return this.renderNotFound();
} }
@ -98,7 +98,7 @@ public class FrontArchiveController extends BaseController {
public String archives(Model model, public String archives(Model model,
@PathVariable(value = "year") String year, @PathVariable(value = "year") String year,
@PathVariable(value = "month") String month) { @PathVariable(value = "month") String month) {
Page<Post> posts = postService.findPostByYearAndMonth(year, month, null); final Page<Post> posts = postService.findPostByYearAndMonth(year, month, null);
if (null == posts) { if (null == posts) {
return this.renderNotFound(); return this.renderNotFound();
} }
@ -119,16 +119,16 @@ public class FrontArchiveController extends BaseController {
public String getPost(@PathVariable String postUrl, public String getPost(@PathVariable String postUrl,
@RequestParam(value = "cp", defaultValue = "1") Integer cp, @RequestParam(value = "cp", defaultValue = "1") Integer cp,
Model model) { Model model) {
Post post = postService.findByPostUrl(postUrl, PostTypeEnum.POST_TYPE_POST.getDesc()); final Post post = postService.findByPostUrl(postUrl, PostTypeEnum.POST_TYPE_POST.getDesc());
if (null == post || !post.getPostStatus().equals(PostStatusEnum.PUBLISHED.getCode())) { if (null == post || !post.getPostStatus().equals(PostStatusEnum.PUBLISHED.getCode())) {
return this.renderNotFound(); return this.renderNotFound();
} }
//获得当前文章的发布日期 //获得当前文章的发布日期
Date postDate = post.getPostDate(); final Date postDate = post.getPostDate();
//查询当前文章日期之前的所有文章 //查询当前文章日期之前的所有文章
List<Post> beforePosts = postService.findByPostDateBefore(postDate); final List<Post> beforePosts = postService.findByPostDateBefore(postDate);
//查询当前文章日期之后的所有文章 //查询当前文章日期之后的所有文章
List<Post> afterPosts = postService.findByPostDateAfter(postDate); final List<Post> afterPosts = postService.findByPostDateAfter(postDate);
if (null != beforePosts && beforePosts.size() > 0) { if (null != beforePosts && beforePosts.size() > 0) {
model.addAttribute("beforePost", beforePosts.get(beforePosts.size() - 1)); model.addAttribute("beforePost", beforePosts.get(beforePosts.size() - 1));
@ -143,8 +143,8 @@ public class FrontArchiveController extends BaseController {
comments = commentService.findCommentsByPostAndCommentStatusNot(post, CommentStatusEnum.RECYCLE.getCode()); comments = commentService.findCommentsByPostAndCommentStatusNot(post, CommentStatusEnum.RECYCLE.getCode());
} }
//获取文章的标签用作keywords //获取文章的标签用作keywords
List<Tag> tags = post.getTags(); final List<Tag> tags = post.getTags();
List<String> tagWords = new ArrayList<>(); final List<String> tagWords = new ArrayList<>();
if (tags != null) { if (tags != null) {
for (Tag tag : tags) { for (Tag tag : tags) {
tagWords.add(tag.getTagName()); tagWords.add(tag.getTagName());
@ -157,8 +157,8 @@ public class FrontArchiveController extends BaseController {
size = Integer.parseInt(HaloConst.OPTIONS.get(BlogPropertiesEnum.INDEX_COMMENTS.getProp())); size = Integer.parseInt(HaloConst.OPTIONS.get(BlogPropertiesEnum.INDEX_COMMENTS.getProp()));
} }
//评论分页 //评论分页
ListPage<Comment> commentsPage = new ListPage<Comment>(CommentUtil.getComments(comments), cp, size); final ListPage<Comment> commentsPage = new ListPage<Comment>(CommentUtil.getComments(comments), cp, size);
int[] rainbow = PageUtil.rainbow(cp, commentsPage.getTotalPage(), 3); final int[] rainbow = PageUtil.rainbow(cp, commentsPage.getTotalPage(), 3);
model.addAttribute("is_post", true); model.addAttribute("is_post", true);
model.addAttribute("post", post); model.addAttribute("post", post);
model.addAttribute("comments", commentsPage); model.addAttribute("comments", commentsPage);

View File

@ -44,11 +44,12 @@ public class FrontCategoryController extends BaseController {
* *
* *
* @param model model * @param model model
*
* @return String * @return String
*/ */
@GetMapping @GetMapping
public String categories(Model model) { public String categories(Model model) {
List<Category> categories = categoryService.findAll(); final List<Category> categories = categoryService.findAll();
model.addAttribute("categories", categories); model.addAttribute("categories", categories);
return this.render("categories"); return this.render("categories");
} }
@ -58,6 +59,7 @@ public class FrontCategoryController extends BaseController {
* *
* @param model model * @param model model
* @param cateUrl cateUrl * @param cateUrl cateUrl
*
* @return string * @return string
*/ */
@GetMapping(value = "{cateUrl}") @GetMapping(value = "{cateUrl}")
@ -72,24 +74,25 @@ public class FrontCategoryController extends BaseController {
* @param model model * @param model model
* @param cateUrl * @param cateUrl
* @param page * @param page
*
* @return String * @return String
*/ */
@GetMapping("{cateUrl}/page/{page}") @GetMapping("{cateUrl}/page/{page}")
public String categories(Model model, public String categories(Model model,
@PathVariable("cateUrl") String cateUrl, @PathVariable("cateUrl") String cateUrl,
@PathVariable("page") Integer page) { @PathVariable("page") Integer page) {
Category category = categoryService.findByCateUrl(cateUrl); final Category category = categoryService.findByCateUrl(cateUrl);
if (null == category) { if (null == category) {
return this.renderNotFound(); return this.renderNotFound();
} }
Sort sort = new Sort(Sort.Direction.DESC, "postDate"); final Sort sort = new Sort(Sort.Direction.DESC, "postDate");
Integer size = 10; int size = 10;
if (StrUtil.isNotBlank(HaloConst.OPTIONS.get(BlogPropertiesEnum.INDEX_POSTS.getProp()))) { if (StrUtil.isNotBlank(HaloConst.OPTIONS.get(BlogPropertiesEnum.INDEX_POSTS.getProp()))) {
size = Integer.parseInt(HaloConst.OPTIONS.get(BlogPropertiesEnum.INDEX_POSTS.getProp())); size = Integer.parseInt(HaloConst.OPTIONS.get(BlogPropertiesEnum.INDEX_POSTS.getProp()));
} }
Pageable pageable = PageRequest.of(page - 1, size, sort); final Pageable pageable = PageRequest.of(page - 1, size, sort);
Page<Post> posts = postService.findPostByCategories(category, pageable); final Page<Post> posts = postService.findPostByCategories(category, pageable);
int[] rainbow = PageUtil.rainbow(page, posts.getTotalPages(), 3); final int[] rainbow = PageUtil.rainbow(page, posts.getTotalPages(), 3);
model.addAttribute("is_categories", true); model.addAttribute("is_categories", true);
model.addAttribute("posts", posts); model.addAttribute("posts", posts);
model.addAttribute("rainbow", rainbow); model.addAttribute("rainbow", rainbow);

View File

@ -65,15 +65,16 @@ public class FrontCommentController {
* *
* *
* @param postId postId * @param postId postId
*
* @return List * @return List
*/ */
@GetMapping(value = "/getComment/{postId}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @GetMapping(value = "/getComment/{postId}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody @ResponseBody
public List<Comment> getComment(@PathVariable Long postId) { public List<Comment> getComment(@PathVariable Long postId) {
Optional<Post> post = postService.findByPostId(postId); final Optional<Post> post = postService.findByPostId(postId);
Sort sort = new Sort(Sort.Direction.DESC, "commentDate"); final Sort sort = new Sort(Sort.Direction.DESC, "commentDate");
Pageable pageable = PageRequest.of(0, 999, sort); final Pageable pageable = PageRequest.of(0, 999, sort);
List<Comment> comments = commentService.findCommentsByPostAndCommentStatus(post.get(), pageable, CommentStatusEnum.PUBLISHED.getCode()).getContent(); final List<Comment> comments = commentService.findCommentsByPostAndCommentStatus(post.orElse(new Post()), pageable, CommentStatusEnum.PUBLISHED.getCode()).getContent();
return CommentUtil.getComments(comments); return CommentUtil.getComments(comments);
} }
@ -82,15 +83,16 @@ public class FrontCommentController {
* *
* @param page * @param page
* @param post * @param post
*
* @return List * @return List
*/ */
@GetMapping(value = "/loadComment") @GetMapping(value = "/loadComment")
@ResponseBody @ResponseBody
public List<Comment> loadComment(@RequestParam(value = "page") Integer page, public List<Comment> loadComment(@RequestParam(value = "page") Integer page,
@RequestParam(value = "post") Post post) { @RequestParam(value = "post") Post post) {
Sort sort = new Sort(Sort.Direction.DESC, "commentDate"); final Sort sort = new Sort(Sort.Direction.DESC, "commentDate");
Pageable pageable = PageRequest.of(page - 1, 10, sort); final Pageable pageable = PageRequest.of(page - 1, 10, sort);
List<Comment> comments = commentService.findCommentsByPostAndCommentStatus(post, pageable, CommentStatusEnum.PUBLISHED.getCode()).getContent(); final List<Comment> comments = commentService.findCommentsByPostAndCommentStatus(post, pageable, CommentStatusEnum.PUBLISHED.getCode()).getContent();
return comments; return comments;
} }
@ -100,6 +102,7 @@ public class FrontCommentController {
* @param comment comment * @param comment comment
* @param post post * @param post post
* @param request request * @param request request
*
* @return JsonResult * @return JsonResult
*/ */
@PostMapping(value = "/newComment") @PostMapping(value = "/newComment")
@ -115,7 +118,7 @@ public class FrontCommentController {
} }
try { try {
Comment lastComment = null; Comment lastComment = null;
post = postService.findByPostId(post.getPostId()).get(); post = postService.findByPostId(post.getPostId()).orElse(new Post());
comment.setCommentAuthorEmail(HtmlUtil.escape(comment.getCommentAuthorEmail()).toLowerCase()); comment.setCommentAuthorEmail(HtmlUtil.escape(comment.getCommentAuthorEmail()).toLowerCase());
comment.setPost(post); comment.setPost(post);
comment.setCommentDate(DateUtil.date()); comment.setCommentDate(DateUtil.date());
@ -126,8 +129,8 @@ public class FrontCommentController {
comment.setCommentAuthorAvatarMd5(SecureUtil.md5(comment.getCommentAuthorEmail())); comment.setCommentAuthorAvatarMd5(SecureUtil.md5(comment.getCommentAuthorEmail()));
} }
if (comment.getCommentParent() > 0) { if (comment.getCommentParent() > 0) {
lastComment = commentService.findCommentById(comment.getCommentParent()).get(); lastComment = commentService.findCommentById(comment.getCommentParent()).orElse(new Comment());
StrBuilder buildContent = new StrBuilder("<a href='#comment-id-"); final StrBuilder buildContent = new StrBuilder("<a href='#comment-id-");
buildContent.append(lastComment.getCommentId()); buildContent.append(lastComment.getCommentId());
buildContent.append("'>@"); buildContent.append("'>@");
buildContent.append(lastComment.getCommentAuthor()); buildContent.append(lastComment.getCommentAuthor());
@ -175,8 +178,8 @@ public class FrontCommentController {
if (StrUtil.equals(HaloConst.OPTIONS.get(BlogPropertiesEnum.SMTP_EMAIL_ENABLE.getProp()), TrueFalseEnum.TRUE.getDesc()) && StrUtil.equals(HaloConst.OPTIONS.get(BlogPropertiesEnum.NEW_COMMENT_NOTICE.getProp()), TrueFalseEnum.TRUE.getDesc())) { if (StrUtil.equals(HaloConst.OPTIONS.get(BlogPropertiesEnum.SMTP_EMAIL_ENABLE.getProp()), TrueFalseEnum.TRUE.getDesc()) && StrUtil.equals(HaloConst.OPTIONS.get(BlogPropertiesEnum.NEW_COMMENT_NOTICE.getProp()), TrueFalseEnum.TRUE.getDesc())) {
try { try {
//发送邮件到博主 //发送邮件到博主
Map<String, Object> map = new HashMap<>(5); final Map<String, Object> map = new HashMap<>(5);
StrBuilder pageUrl = new StrBuilder(HaloConst.OPTIONS.get(BlogPropertiesEnum.BLOG_URL.getProp())); final StrBuilder pageUrl = new StrBuilder(HaloConst.OPTIONS.get(BlogPropertiesEnum.BLOG_URL.getProp()));
if (StrUtil.equals(post.getPostType(), PostTypeEnum.POST_TYPE_POST.getDesc())) { if (StrUtil.equals(post.getPostType(), PostTypeEnum.POST_TYPE_POST.getDesc())) {
pageUrl.append("/archives/"); pageUrl.append("/archives/");
} else { } else {
@ -217,8 +220,8 @@ public class FrontCommentController {
//发送通知给对方 //发送通知给对方
if (StrUtil.equals(HaloConst.OPTIONS.get(BlogPropertiesEnum.SMTP_EMAIL_ENABLE.getProp()), TrueFalseEnum.TRUE.getDesc()) && StrUtil.equals(HaloConst.OPTIONS.get(BlogPropertiesEnum.NEW_COMMENT_NOTICE.getProp()), TrueFalseEnum.TRUE.getDesc())) { if (StrUtil.equals(HaloConst.OPTIONS.get(BlogPropertiesEnum.SMTP_EMAIL_ENABLE.getProp()), TrueFalseEnum.TRUE.getDesc()) && StrUtil.equals(HaloConst.OPTIONS.get(BlogPropertiesEnum.NEW_COMMENT_NOTICE.getProp()), TrueFalseEnum.TRUE.getDesc())) {
if (Validator.isEmail(lastComment.getCommentAuthorEmail())) { if (Validator.isEmail(lastComment.getCommentAuthorEmail())) {
Map<String, Object> map = new HashMap<>(8); final Map<String, Object> map = new HashMap<>(8);
StrBuilder pageUrl = new StrBuilder(HaloConst.OPTIONS.get(BlogPropertiesEnum.BLOG_URL.getProp())); final StrBuilder pageUrl = new StrBuilder(HaloConst.OPTIONS.get(BlogPropertiesEnum.BLOG_URL.getProp()));
if (StrUtil.equals(post.getPostType(), PostTypeEnum.POST_TYPE_POST.getDesc())) { if (StrUtil.equals(post.getPostType(), PostTypeEnum.POST_TYPE_POST.getDesc())) {
pageUrl.append("/archives/"); pageUrl.append("/archives/");

View File

@ -60,20 +60,19 @@ public class FrontIndexController extends BaseController {
@GetMapping(value = "page/{page}") @GetMapping(value = "page/{page}")
public String index(Model model, public String index(Model model,
@PathVariable(value = "page") Integer page) { @PathVariable(value = "page") Integer page) {
Sort sort = new Sort(Sort.Direction.DESC, "postDate"); final Sort sort = new Sort(Sort.Direction.DESC, "postDate");
//默认显示10条 //默认显示10条
int size = 10; int size = 10;
//尝试加载设置选项,用于设置显示条数
if (StrUtil.isNotBlank(HaloConst.OPTIONS.get(BlogPropertiesEnum.INDEX_POSTS.getProp()))) { if (StrUtil.isNotBlank(HaloConst.OPTIONS.get(BlogPropertiesEnum.INDEX_POSTS.getProp()))) {
size = Integer.parseInt(HaloConst.OPTIONS.get(BlogPropertiesEnum.INDEX_POSTS.getProp())); size = Integer.parseInt(HaloConst.OPTIONS.get(BlogPropertiesEnum.INDEX_POSTS.getProp()));
} }
//所有文章数据,分页 //所有文章数据,分页
Pageable pageable = PageRequest.of(page - 1, size, sort); final Pageable pageable = PageRequest.of(page - 1, size, sort);
Page<Post> posts = postService.findPostByStatus(pageable); final Page<Post> posts = postService.findPostByStatus(pageable);
if (null == posts) { if (null == posts) {
return this.renderNotFound(); return this.renderNotFound();
} }
int[] rainbow = PageUtil.rainbow(page, posts.getTotalPages(), 3); final int[] rainbow = PageUtil.rainbow(page, posts.getTotalPages(), 3);
model.addAttribute("is_index",true); model.addAttribute("is_index",true);
model.addAttribute("posts", posts); model.addAttribute("posts", posts);
model.addAttribute("rainbow", rainbow); model.addAttribute("rainbow", rainbow);
@ -89,7 +88,7 @@ public class FrontIndexController extends BaseController {
*/ */
@GetMapping(value = "search") @GetMapping(value = "search")
public String search(@RequestParam("keyword") String keyword, Model model) { public String search(@RequestParam("keyword") String keyword, Model model) {
Page<Post> posts = postService.searchByKeywords(keyword, null); final Page<Post> posts = postService.searchByKeywords(keyword, null);
model.addAttribute("posts", posts); model.addAttribute("posts", posts);
return this.render("index"); return this.render("index");
} }

View File

@ -44,10 +44,10 @@ public class FrontOthersController {
rssPosts = "20"; rssPosts = "20";
} }
//获取文章列表并根据时间排序 //获取文章列表并根据时间排序
Sort sort = new Sort(Sort.Direction.DESC, "postDate"); final Sort sort = new Sort(Sort.Direction.DESC, "postDate");
Pageable pageable = PageRequest.of(0, Integer.parseInt(rssPosts), sort); final Pageable pageable = PageRequest.of(0, Integer.parseInt(rssPosts), sort);
Page<Post> postsPage = postService.findPostByStatus(0, PostTypeEnum.POST_TYPE_POST.getDesc(), pageable); final Page<Post> postsPage = postService.findPostByStatus(0, PostTypeEnum.POST_TYPE_POST.getDesc(), pageable);
List<Post> posts = postsPage.getContent(); final List<Post> posts = postsPage.getContent();
return postService.buildRss(posts); return postService.buildRss(posts);
} }
@ -60,10 +60,10 @@ public class FrontOthersController {
@ResponseBody @ResponseBody
public String siteMap() { public String siteMap() {
//获取文章列表并根据时间排序 //获取文章列表并根据时间排序
Sort sort = new Sort(Sort.Direction.DESC, "postDate"); final Sort sort = new Sort(Sort.Direction.DESC, "postDate");
Pageable pageable = PageRequest.of(0, 999, sort); final Pageable pageable = PageRequest.of(0, 999, sort);
Page<Post> postsPage = postService.findPostByStatus(0, PostTypeEnum.POST_TYPE_POST.getDesc(), pageable); final Page<Post> postsPage = postService.findPostByStatus(0, PostTypeEnum.POST_TYPE_POST.getDesc(), pageable);
List<Post> posts = postsPage.getContent(); final List<Post> posts = postsPage.getContent();
return postService.buildSiteMap(posts); return postService.buildSiteMap(posts);
} }
} }

View File

@ -49,7 +49,7 @@ public class FrontPageController extends BaseController {
*/ */
@GetMapping(value = "/gallery") @GetMapping(value = "/gallery")
public String gallery(Model model) { public String gallery(Model model) {
List<Gallery> galleries = galleryService.findAll(); final List<Gallery> galleries = galleryService.findAll();
model.addAttribute("galleries", galleries); model.addAttribute("galleries", galleries);
return this.render("gallery"); return this.render("gallery");
} }
@ -76,7 +76,7 @@ public class FrontPageController extends BaseController {
public String getPage(@PathVariable(value = "postUrl") String postUrl, public String getPage(@PathVariable(value = "postUrl") String postUrl,
@RequestParam(value = "cp", defaultValue = "1") Integer cp, @RequestParam(value = "cp", defaultValue = "1") Integer cp,
Model model) { Model model) {
Post post = postService.findByPostUrl(postUrl, PostTypeEnum.POST_TYPE_PAGE.getDesc()); final Post post = postService.findByPostUrl(postUrl, PostTypeEnum.POST_TYPE_PAGE.getDesc());
if (null == post || !post.getPostStatus().equals(PostStatusEnum.PUBLISHED.getCode())) { if (null == post || !post.getPostStatus().equals(PostStatusEnum.PUBLISHED.getCode())) {
return this.renderNotFound(); return this.renderNotFound();
} }
@ -88,13 +88,12 @@ public class FrontPageController extends BaseController {
} }
//默认显示10条 //默认显示10条
int size = 10; int size = 10;
//获取每页评论条数
if (StrUtil.isNotBlank(HaloConst.OPTIONS.get(BlogPropertiesEnum.INDEX_COMMENTS.getProp()))) { if (StrUtil.isNotBlank(HaloConst.OPTIONS.get(BlogPropertiesEnum.INDEX_COMMENTS.getProp()))) {
size = Integer.parseInt(HaloConst.OPTIONS.get(BlogPropertiesEnum.INDEX_COMMENTS.getProp())); size = Integer.parseInt(HaloConst.OPTIONS.get(BlogPropertiesEnum.INDEX_COMMENTS.getProp()));
} }
//评论分页 //评论分页
ListPage<Comment> commentsPage = new ListPage<Comment>(CommentUtil.getComments(comments), cp, size); final ListPage<Comment> commentsPage = new ListPage<Comment>(CommentUtil.getComments(comments), cp, size);
int[] rainbow = PageUtil.rainbow(cp, commentsPage.getTotalPage(), 3); final int[] rainbow = PageUtil.rainbow(cp, commentsPage.getTotalPage(), 3);
model.addAttribute("is_page", true); model.addAttribute("is_page", true);
model.addAttribute("post", post); model.addAttribute("post", post);
model.addAttribute("comments", commentsPage); model.addAttribute("comments", commentsPage);

View File

@ -53,6 +53,7 @@ public class FrontTagController extends BaseController {
* *
* @param tagUrl * @param tagUrl
* @param model model * @param model model
*
* @return String * @return String
*/ */
@GetMapping(value = "{tagUrl}") @GetMapping(value = "{tagUrl}")
@ -67,24 +68,25 @@ public class FrontTagController extends BaseController {
* @param model model * @param model model
* @param tagUrl * @param tagUrl
* @param page * @param page
*
* @return String * @return String
*/ */
@GetMapping(value = "{tagUrl}/page/{page}") @GetMapping(value = "{tagUrl}/page/{page}")
public String tags(Model model, public String tags(Model model,
@PathVariable("tagUrl") String tagUrl, @PathVariable("tagUrl") String tagUrl,
@PathVariable("page") Integer page) { @PathVariable("page") Integer page) {
Tag tag = tagService.findByTagUrl(tagUrl); final Tag tag = tagService.findByTagUrl(tagUrl);
if (null == tag) { if (null == tag) {
return this.renderNotFound(); return this.renderNotFound();
} }
Sort sort = new Sort(Sort.Direction.DESC, "postDate"); final Sort sort = new Sort(Sort.Direction.DESC, "postDate");
Integer size = 10; int size = 10;
if (StrUtil.isNotBlank(HaloConst.OPTIONS.get(BlogPropertiesEnum.INDEX_POSTS.getProp()))) { if (StrUtil.isNotBlank(HaloConst.OPTIONS.get(BlogPropertiesEnum.INDEX_POSTS.getProp()))) {
size = Integer.parseInt(HaloConst.OPTIONS.get(BlogPropertiesEnum.INDEX_POSTS.getProp())); size = Integer.parseInt(HaloConst.OPTIONS.get(BlogPropertiesEnum.INDEX_POSTS.getProp()));
} }
Pageable pageable = PageRequest.of(page - 1, size, sort); final Pageable pageable = PageRequest.of(page - 1, size, sort);
Page<Post> posts = postService.findPostsByTags(tag, pageable); final Page<Post> posts = postService.findPostsByTags(tag, pageable);
int[] rainbow = PageUtil.rainbow(page, posts.getTotalPages(), 3); final int[] rainbow = PageUtil.rainbow(page, posts.getTotalPages(), 3);
model.addAttribute("is_tags", true); model.addAttribute("is_tags", true);
model.addAttribute("posts", posts); model.addAttribute("posts", posts);
model.addAttribute("rainbow", rainbow); model.addAttribute("rainbow", rainbow);

View File

@ -25,10 +25,12 @@ import java.util.Map;
@Component @Component
public class ApiInterceptor implements HandlerInterceptor { public class ApiInterceptor implements HandlerInterceptor {
private static final String TOKEN = "token";
@Override @Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (StrUtil.equals(TrueFalseEnum.TRUE.getDesc(), HaloConst.OPTIONS.get(BlogPropertiesEnum.API_STATUS.getProp()))) { if (StrUtil.equals(TrueFalseEnum.TRUE.getDesc(), HaloConst.OPTIONS.get(BlogPropertiesEnum.API_STATUS.getProp()))) {
if (StrUtil.equals(request.getHeader("token"), HaloConst.OPTIONS.get(BlogPropertiesEnum.API_TOKEN.getProp()))) { if (StrUtil.equals(request.getHeader(TOKEN), HaloConst.OPTIONS.get(BlogPropertiesEnum.API_TOKEN.getProp()))) {
return true; return true;
} else { } else {
response.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8");

View File

@ -23,6 +23,10 @@ public class LocaleInterceptor implements HandlerInterceptor {
@Override @Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
final Object attribute = request.getSession().getAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME);
if (null != attribute) {
return true;
}
if (StrUtil.equals(LocaleEnum.EN_US.getValue(), HaloConst.OPTIONS.get(BlogPropertiesEnum.BLOG_LOCALE.getProp()))) { if (StrUtil.equals(LocaleEnum.EN_US.getValue(), HaloConst.OPTIONS.get(BlogPropertiesEnum.BLOG_LOCALE.getProp()))) {
request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, new Locale("en", "US")); request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, new Locale("en", "US"));
} else { } else {

View File

@ -21,7 +21,7 @@ public class LoginInterceptor implements HandlerInterceptor {
@Override @Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
Object obj = request.getSession().getAttribute(HaloConst.USER_SESSION_KEY); final Object obj = request.getSession().getAttribute(HaloConst.USER_SESSION_KEY);
//如果user不为空则放行 //如果user不为空则放行
if (null != obj) { if (null != obj) {
return true; return true;

View File

@ -159,7 +159,7 @@
autofocus: true, autofocus: true,
autosave: { autosave: {
enabled: true, enabled: true,
uniqueId: "editor-temp-page-<#if post??>${post.postId}<#else>1</#if>", uniqueId: "editor-temp-page-<#if post??>${post.postId?c}<#else>1</#if>",
delay: 10000 delay: 10000
}, },
renderingConfig: { renderingConfig: {

View File

@ -177,7 +177,7 @@
autofocus: true, autofocus: true,
autosave: { autosave: {
enabled: true, enabled: true,
uniqueId: "editor-temp-${post.postId!}", uniqueId: "editor-temp-${post.postId?c}",
delay: 10000 delay: 10000
}, },
renderingConfig: { renderingConfig: {