Refactor attachment handler.

pull/296/head
ruibaby 2019-09-06 22:51:17 +08:00
parent 1a091fb6b8
commit cbb2269ce8
23 changed files with 44 additions and 29 deletions

View File

@ -50,7 +50,7 @@ public class MainController {
@GetMapping("/avatar") @GetMapping("/avatar")
public void avatar(HttpServletResponse response) throws IOException { public void avatar(HttpServletResponse response) throws IOException {
User user = userService.getCurrentUser().orElseThrow(() -> new ServiceException("找不到博主信息")); User user = userService.getCurrentUser().orElseThrow(() -> new ServiceException("未查询到博主信息"));
if (StringUtils.isNotEmpty(user.getAvatar())) { if (StringUtils.isNotEmpty(user.getAvatar())) {
response.sendRedirect(user.getAvatar()); response.sendRedirect(user.getAvatar());
} }

View File

@ -38,7 +38,7 @@ public class ControllerExceptionHandler {
if (e.getCause() instanceof org.hibernate.exception.ConstraintViolationException) { if (e.getCause() instanceof org.hibernate.exception.ConstraintViolationException) {
baseResponse = handleBaseException(e.getCause()); baseResponse = handleBaseException(e.getCause());
} }
baseResponse.setMessage("Failed to validate request parameter"); baseResponse.setMessage("字段验证错误,请完善后重试!");
return baseResponse; return baseResponse;
} }
@ -46,7 +46,7 @@ public class ControllerExceptionHandler {
@ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseStatus(HttpStatus.BAD_REQUEST)
public BaseResponse handleMissingServletRequestParameterException(MissingServletRequestParameterException e) { public BaseResponse handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
BaseResponse<?> baseResponse = handleBaseException(e); BaseResponse<?> baseResponse = handleBaseException(e);
baseResponse.setMessage(String.format("Missing request parameter, required %s type %s parameter", e.getParameterType(), e.getParameterName())); baseResponse.setMessage(String.format("请求字段缺失, 类型为 %s名称为 %s", e.getParameterType(), e.getParameterName()));
return baseResponse; return baseResponse;
} }
@ -92,7 +92,7 @@ public class ControllerExceptionHandler {
public BaseResponse handleHttpMessageNotReadableException(HttpMessageNotReadableException e) { public BaseResponse handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
BaseResponse<?> baseResponse = handleBaseException(e); BaseResponse<?> baseResponse = handleBaseException(e);
baseResponse.setStatus(HttpStatus.BAD_REQUEST.value()); baseResponse.setStatus(HttpStatus.BAD_REQUEST.value());
baseResponse.setMessage("Required request body is missing"); baseResponse.setMessage("缺失请求主体");
return baseResponse; return baseResponse;
} }

View File

@ -65,7 +65,7 @@ public class CommentEventListener {
return; return;
} }
User user = userService.getCurrentUser().orElseThrow(() -> new ServiceException("找不到博主信息")); User user = userService.getCurrentUser().orElseThrow(() -> new ServiceException("未查询到博主信息"));
Map<String, Object> data = new HashMap<>(); Map<String, Object> data = new HashMap<>();

View File

@ -43,13 +43,14 @@ public class AliYunFileHandler implements FileHandler {
Assert.notNull(file, "Multipart file must not be null"); Assert.notNull(file, "Multipart file must not be null");
// Get config // Get config
String ossDomain = optionService.getByPropertyOrDefault(AliYunProperties.OSS_DOMAIN, String.class, "");
String ossEndPoint = optionService.getByPropertyOfNonNull(AliYunProperties.OSS_ENDPOINT).toString(); String ossEndPoint = optionService.getByPropertyOfNonNull(AliYunProperties.OSS_ENDPOINT).toString();
String ossAccessKey = optionService.getByPropertyOfNonNull(AliYunProperties.OSS_ACCESS_KEY).toString(); String ossAccessKey = optionService.getByPropertyOfNonNull(AliYunProperties.OSS_ACCESS_KEY).toString();
String ossAccessSecret = optionService.getByPropertyOfNonNull(AliYunProperties.OSS_ACCESS_SECRET).toString(); String ossAccessSecret = optionService.getByPropertyOfNonNull(AliYunProperties.OSS_ACCESS_SECRET).toString();
String ossBucketName = optionService.getByPropertyOfNonNull(AliYunProperties.OSS_BUCKET_NAME).toString(); String ossBucketName = optionService.getByPropertyOfNonNull(AliYunProperties.OSS_BUCKET_NAME).toString();
String ossSource = StringUtils.join("https://", ossBucketName, "." + ossEndPoint); String ossSource = StringUtils.join("https://", ossBucketName, "." + ossEndPoint);
String ossStyleRule = optionService.getByPropertyOrDefault(AliYunProperties.OSS_STYLE_RULE,String.class,""); String ossStyleRule = optionService.getByPropertyOrDefault(AliYunProperties.OSS_STYLE_RULE, String.class, "");
String ossThumbnailStyleRule = optionService.getByPropertyOrDefault(AliYunProperties.OSS_THUMBNAIL_STYLE_RULE,String.class,""); String ossThumbnailStyleRule = optionService.getByPropertyOrDefault(AliYunProperties.OSS_THUMBNAIL_STYLE_RULE, String.class, "");
// Init OSS client // Init OSS client
OSS ossClient = new OSSClientBuilder().build(ossEndPoint, ossAccessKey, ossAccessSecret); OSS ossClient = new OSSClientBuilder().build(ossEndPoint, ossAccessKey, ossAccessSecret);
@ -59,7 +60,7 @@ public class AliYunFileHandler implements FileHandler {
String extension = FilenameUtils.getExtension(file.getOriginalFilename()); String extension = FilenameUtils.getExtension(file.getOriginalFilename());
String timestamp = String.valueOf(System.currentTimeMillis()); String timestamp = String.valueOf(System.currentTimeMillis());
String upFilePath = StringUtils.join(basename, "_", timestamp, ".", extension); String upFilePath = StringUtils.join(basename, "_", timestamp, ".", extension);
String filePath = StringUtils.join(StringUtils.appendIfMissing(ossSource, "/"), upFilePath); String filePath = StringUtils.join(StringUtils.appendIfMissing(StringUtils.isNotBlank(ossDomain) ? ossDomain : ossSource, "/"), upFilePath);
// Upload // Upload
PutObjectResult putObjectResult = ossClient.putObject(ossBucketName, upFilePath, file.getInputStream()); PutObjectResult putObjectResult = ossClient.putObject(ossBucketName, upFilePath, file.getInputStream());

View File

@ -43,15 +43,15 @@ public class BaiDuYunFileHandler implements FileHandler {
Assert.notNull(file, "Multipart file must not be null"); Assert.notNull(file, "Multipart file must not be null");
// Get config // Get config
String bosDomain = optionService.getByPropertyOrDefault(BaiDuYunProperties.BOS_DOMAIN, String.class, "");
String bosEndPoint = optionService.getByPropertyOfNonNull(BaiDuYunProperties.BOS_ENDPOINT).toString(); String bosEndPoint = optionService.getByPropertyOfNonNull(BaiDuYunProperties.BOS_ENDPOINT).toString();
String bosAccessKey = optionService.getByPropertyOfNonNull(BaiDuYunProperties.BOS_ACCESS_KEY).toString(); String bosAccessKey = optionService.getByPropertyOfNonNull(BaiDuYunProperties.BOS_ACCESS_KEY).toString();
String bosSecretKey = optionService.getByPropertyOfNonNull(BaiDuYunProperties.BOS_SECRET_KEY).toString(); String bosSecretKey = optionService.getByPropertyOfNonNull(BaiDuYunProperties.BOS_SECRET_KEY).toString();
String bosBucketName = optionService.getByPropertyOfNonNull(BaiDuYunProperties.BOS_BUCKET_NAME).toString(); String bosBucketName = optionService.getByPropertyOfNonNull(BaiDuYunProperties.BOS_BUCKET_NAME).toString();
String bosStyleRule = optionService.getByPropertyOrDefault(BaiDuYunProperties.BOS_STYLE_RULE, String.class, ""); String bosStyleRule = optionService.getByPropertyOrDefault(BaiDuYunProperties.BOS_STYLE_RULE, String.class, "");
String bosThumbnailStyleRule = optionService.getByPropertyOrDefault(BaiDuYunProperties.BOS_STYLE_RULE, String.class, ""); String bosThumbnailStyleRule = optionService.getByPropertyOrDefault(BaiDuYunProperties.BOS_THUMBNAIL_STYLE_RULE, String.class, "");
String bosSource = StringUtils.join("https://", bosBucketName, "." + bosEndPoint); String bosSource = StringUtils.join("https://", bosBucketName, "." + bosEndPoint);
BosClientConfiguration config = new BosClientConfiguration(); BosClientConfiguration config = new BosClientConfiguration();
config.setCredentials(new DefaultBceCredentials(bosAccessKey, bosSecretKey)); config.setCredentials(new DefaultBceCredentials(bosAccessKey, bosSecretKey));
config.setEndpoint(bosEndPoint); config.setEndpoint(bosEndPoint);
@ -64,7 +64,7 @@ public class BaiDuYunFileHandler implements FileHandler {
String extension = FilenameUtils.getExtension(file.getOriginalFilename()); String extension = FilenameUtils.getExtension(file.getOriginalFilename());
String timestamp = String.valueOf(System.currentTimeMillis()); String timestamp = String.valueOf(System.currentTimeMillis());
String upFilePath = StringUtils.join(basename, "_", timestamp, ".", extension); String upFilePath = StringUtils.join(basename, "_", timestamp, ".", extension);
String filePath = StringUtils.join(StringUtils.appendIfMissing(bosSource, "/"), upFilePath); String filePath = StringUtils.join(StringUtils.appendIfMissing(StringUtils.isNotBlank(bosDomain) ? bosDomain : bosSource, "/"), upFilePath);
// Upload // Upload
PutObjectResponse putObjectResponseFromInputStream = client.putObject(bosBucketName, upFilePath, file.getInputStream()); PutObjectResponse putObjectResponseFromInputStream = client.putObject(bosBucketName, upFilePath, file.getInputStream());

View File

@ -79,7 +79,6 @@ public class QnYunFileHandler implements FileHandler {
// Create temp path // Create temp path
Path tmpPath = Paths.get(System.getProperty("java.io.tmpdir"), bucket); Path tmpPath = Paths.get(System.getProperty("java.io.tmpdir"), bucket);
try { try {
String basename = FilenameUtils.getBasename(file.getOriginalFilename()); String basename = FilenameUtils.getBasename(file.getOriginalFilename());
String extension = FilenameUtils.getExtension(file.getOriginalFilename()); String extension = FilenameUtils.getExtension(file.getOriginalFilename());
@ -149,7 +148,7 @@ public class QnYunFileHandler implements FileHandler {
bucketManager.delete(bucket, key); bucketManager.delete(bucket, key);
} catch (QiniuException e) { } catch (QiniuException e) {
log.error("QnYun error response: [{}]", e.response); log.error("QnYun error response: [{}]", e.response);
throw new FileOperationException("Failed to delete file with " + key + " key", e); throw new FileOperationException("附件 " + key + " 从七牛云删除失败", e);
} }
} }

View File

@ -47,6 +47,7 @@ public class TencentYunFileHandler implements FileHandler {
Assert.notNull(file, "Multipart file must not be null"); Assert.notNull(file, "Multipart file must not be null");
// Get config // Get config
String cosDomain = optionService.getByPropertyOrDefault(TencentYunProperties.COS_DOMAIN, String.class, "");
String cosRegion = optionService.getByPropertyOfNonNull(TencentYunProperties.COS_REGION).toString(); String cosRegion = optionService.getByPropertyOfNonNull(TencentYunProperties.COS_REGION).toString();
String cosSecretId = optionService.getByPropertyOfNonNull(TencentYunProperties.COS_SECRET_ID).toString(); String cosSecretId = optionService.getByPropertyOfNonNull(TencentYunProperties.COS_SECRET_ID).toString();
String cosSecretKey = optionService.getByPropertyOfNonNull(TencentYunProperties.COS_SECRET_KEY).toString(); String cosSecretKey = optionService.getByPropertyOfNonNull(TencentYunProperties.COS_SECRET_KEY).toString();
@ -71,7 +72,7 @@ public class TencentYunFileHandler implements FileHandler {
String extension = FilenameUtils.getExtension(file.getOriginalFilename()); String extension = FilenameUtils.getExtension(file.getOriginalFilename());
String timestamp = String.valueOf(System.currentTimeMillis()); String timestamp = String.valueOf(System.currentTimeMillis());
String upFilePath = StringUtils.join(basename, "_", timestamp, ".", extension); String upFilePath = StringUtils.join(basename, "_", timestamp, ".", extension);
String filePath = StringUtils.join(StringUtils.appendIfMissing(cosSource, "/"), upFilePath); String filePath = StringUtils.join(StringUtils.appendIfMissing(StringUtils.isNotBlank(cosDomain) ? cosDomain : cosSource, "/"), upFilePath);
// Upload // Upload
ObjectMetadata objectMetadata = new ObjectMetadata(); ObjectMetadata objectMetadata = new ObjectMetadata();

View File

@ -118,7 +118,7 @@ public class UpYunFileHandler implements FileHandler {
log.warn("Failed to delete file " + key + " from UpYun"); log.warn("Failed to delete file " + key + " from UpYun");
} }
} catch (Exception e) { } catch (Exception e) {
throw new FileOperationException("附件从又拍云删除失败", e); throw new FileOperationException("附件 " + key + " 从又拍云删除失败", e);
} }
} }

View File

@ -1,7 +1,6 @@
package run.halo.app.model.entity; package run.halo.app.model.entity;
import lombok.Data; import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString; import lombok.ToString;
import javax.persistence.*; import javax.persistence.*;

View File

@ -9,6 +9,11 @@ package run.halo.app.model.properties;
*/ */
public enum AliYunProperties implements PropertyEnum { public enum AliYunProperties implements PropertyEnum {
/**
* Aliyun oss domain
*/
OSS_DOMAIN("oss_aliyun_domain",String.class,""),
/** /**
* Aliyun oss endpoint. * Aliyun oss endpoint.
*/ */

View File

@ -9,6 +9,11 @@ package run.halo.app.model.properties;
*/ */
public enum BaiDuYunProperties implements PropertyEnum { public enum BaiDuYunProperties implements PropertyEnum {
/**
* Baidu yun bos domain.
*/
BOS_DOMAIN("bos_baiduyun_domain",String.class,""),
/** /**
* Baidu yun bos endpoint. * Baidu yun bos endpoint.
*/ */

View File

@ -9,6 +9,11 @@ package run.halo.app.model.properties;
*/ */
public enum TencentYunProperties implements PropertyEnum { public enum TencentYunProperties implements PropertyEnum {
/**
* Tencentyun cos domain.
*/
COS_DOMAIN("cos_tencentyun_domain",String.class,""),
/** /**
* Tencentyun cos endpoint. * Tencentyun cos endpoint.
*/ */

View File

@ -90,7 +90,7 @@ public class AdminAuthenticationFilter extends AbstractAuthenticationFilter {
String token = getTokenFromRequest(request); String token = getTokenFromRequest(request);
if (StringUtils.isBlank(token)) { if (StringUtils.isBlank(token)) {
getFailureHandler().onFailure(request, response, new AuthenticationException("You have to login before accessing admin api")); getFailureHandler().onFailure(request, response, new AuthenticationException("未登录,请登陆后访问"));
return; return;
} }

View File

@ -245,7 +245,7 @@ public class AdminServiceImpl implements AdminService {
throw new ServiceException("验证码不正确"); throw new ServiceException("验证码不正确");
} }
User user = userService.getCurrentUser().orElseThrow(() -> new ServiceException("找不到博主信息")); User user = userService.getCurrentUser().orElseThrow(() -> new ServiceException("未查询到博主信息"));
// reset password // reset password
userService.setPassword(user, param.getPassword()); userService.setPassword(user, param.getPassword());

View File

@ -78,7 +78,7 @@ public abstract class BasePostServiceImpl<POST extends BasePost> extends Abstrac
public POST getByUrl(String url) { public POST getByUrl(String url) {
Assert.hasText(url, "Url must not be blank"); Assert.hasText(url, "Url must not be blank");
return basePostRepository.getByUrl(url).orElseThrow(() -> new NotFoundException("该文章不存在").setErrorData(url)); return basePostRepository.getByUrl(url).orElseThrow(() -> new NotFoundException("查询不到该文章的信息").setErrorData(url));
} }
@Override @Override
@ -88,7 +88,7 @@ public abstract class BasePostServiceImpl<POST extends BasePost> extends Abstrac
Optional<POST> postOptional = basePostRepository.getByUrlAndStatus(url, status); Optional<POST> postOptional = basePostRepository.getByUrlAndStatus(url, status);
return postOptional.orElseThrow(() -> new NotFoundException("The post with status " + status + " and url " + url + " was not existed").setErrorData(url)); return postOptional.orElseThrow(() -> new NotFoundException("查询不到该文章的信息").setErrorData(url));
} }
@Override @Override
@ -175,7 +175,7 @@ public abstract class BasePostServiceImpl<POST extends BasePost> extends Abstrac
@Override @Override
public void increaseVisit(long visits, Integer postId) { public void increaseVisit(long visits, Integer postId) {
Assert.isTrue(visits > 0, "Visits to increase must not be less than 1"); Assert.isTrue(visits > 0, "Visits to increase must not be less than 1");
Assert.notNull(postId, "Goods id must not be null"); Assert.notNull(postId, "Post id must not be null");
long affectedRows = basePostRepository.updateVisit(visits, postId); long affectedRows = basePostRepository.updateVisit(visits, postId);

View File

@ -154,7 +154,7 @@ public class CategoryServiceImpl extends AbstractCrudService<Category, Integer>
@Override @Override
public Category getBySlugNameOfNonNull(String slugName) { public Category getBySlugNameOfNonNull(String slugName) {
return categoryRepository.getBySlugName(slugName).orElseThrow(() -> new NotFoundException("该分类不存在").setErrorData(slugName)); return categoryRepository.getBySlugName(slugName).orElseThrow(() -> new NotFoundException("查询不到该分类的信息").setErrorData(slugName));
} }
@Override @Override

View File

@ -49,7 +49,7 @@ public class JournalCommentServiceImpl extends BaseCommentServiceImpl<JournalCom
@Override @Override
public void validateTarget(Integer journalId) { public void validateTarget(Integer journalId) {
if (!journalRepository.existsById(journalId)) { if (!journalRepository.existsById(journalId)) {
throw new NotFoundException("该日志不存在或已删除").setErrorData(journalId); throw new NotFoundException("查询不到该日志信息").setErrorData(journalId);
} }
} }

View File

@ -104,7 +104,7 @@ public class PostCommentServiceImpl extends BaseCommentServiceImpl<PostComment>
@Override @Override
public void validateTarget(Integer postId) { public void validateTarget(Integer postId) {
Post post = postRepository.findById(postId) Post post = postRepository.findById(postId)
.orElseThrow(() -> new NotFoundException("该文章不存在或已删除").setErrorData(postId)); .orElseThrow(() -> new NotFoundException("查询不到该文章的信息").setErrorData(postId));
if (post.getDisallowComment()) { if (post.getDisallowComment()) {
throw new BadRequestException("该文章已经被禁止评论").setErrorData(postId); throw new BadRequestException("该文章已经被禁止评论").setErrorData(postId);

View File

@ -33,6 +33,6 @@ public class PostMetaServiceImpl extends BaseMetaServiceImpl<PostMeta> implement
@Override @Override
public void validateTarget(Integer postId) { public void validateTarget(Integer postId) {
postRepository.findById(postId) postRepository.findById(postId)
.orElseThrow(() -> new NotFoundException("该文章不存在或已删除").setErrorData(postId)); .orElseThrow(() -> new NotFoundException("查询不到该文章的信息").setErrorData(postId));
} }
} }

View File

@ -52,7 +52,7 @@ public class SheetCommentServiceImpl extends BaseCommentServiceImpl<SheetComment
@Override @Override
public void validateTarget(Integer sheetId) { public void validateTarget(Integer sheetId) {
Sheet sheet = sheetRepository.findById(sheetId) Sheet sheet = sheetRepository.findById(sheetId)
.orElseThrow(() -> new NotFoundException("该页面不存在或已删除").setErrorData(sheetId)); .orElseThrow(() -> new NotFoundException("查询不到该页面的信息").setErrorData(sheetId));
if (sheet.getDisallowComment()) { if (sheet.getDisallowComment()) {
throw new BadRequestException("该页面已被禁止评论").setErrorData(sheetId); throw new BadRequestException("该页面已被禁止评论").setErrorData(sheetId);

View File

@ -33,6 +33,6 @@ public class SheetMetaServiceImpl extends BaseMetaServiceImpl<SheetMeta> impleme
@Override @Override
public void validateTarget(Integer sheetId) { public void validateTarget(Integer sheetId) {
sheetRepository.findById(sheetId) sheetRepository.findById(sheetId)
.orElseThrow(() -> new NotFoundException("该页面不存在或已删除").setErrorData(sheetId)); .orElseThrow(() -> new NotFoundException("查询不到该页面的信息").setErrorData(sheetId));
} }
} }

View File

@ -54,7 +54,7 @@ public class TagServiceImpl extends AbstractCrudService<Tag, Integer> implements
@Override @Override
public Tag getBySlugNameOfNonNull(String slugName) { public Tag getBySlugNameOfNonNull(String slugName) {
return tagRepository.getBySlugName(slugName).orElseThrow(() -> new NotFoundException("该标签不存在").setErrorData(slugName)); return tagRepository.getBySlugName(slugName).orElseThrow(() -> new NotFoundException("查询不到该标签的信息").setErrorData(slugName));
} }
@Override @Override

View File

@ -184,7 +184,7 @@ public class UserServiceImpl extends AbstractCrudService<User, Integer> implemen
@Override @Override
public boolean verifyUser(String username, String password) { public boolean verifyUser(String username, String password) {
User user = getCurrentUser().orElseThrow(() -> new ServiceException("找不到博主信息")); User user = getCurrentUser().orElseThrow(() -> new ServiceException("未查询到博主信息"));
return user.getUsername().equals(username) && user.getEmail().equals(password); return user.getUsername().equals(username) && user.getEmail().equals(password);
} }
} }