Skip to content

Commit

Permalink
Refactor attachment handler.
Browse files Browse the repository at this point in the history
  • Loading branch information
ruibaby committed Sep 6, 2019
1 parent 1a091fb commit cbb2269
Show file tree
Hide file tree
Showing 23 changed files with 44 additions and 29 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public String version() {

@GetMapping("/avatar")
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())) {
response.sendRedirect(user.getAvatar());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,15 +38,15 @@ public BaseResponse handleDataIntegrityViolationException(DataIntegrityViolation
if (e.getCause() instanceof org.hibernate.exception.ConstraintViolationException) {
baseResponse = handleBaseException(e.getCause());
}
baseResponse.setMessage("Failed to validate request parameter");
baseResponse.setMessage("字段验证错误,请完善后重试!");
return baseResponse;
}

@ExceptionHandler(MissingServletRequestParameterException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public BaseResponse handleMissingServletRequestParameterException(MissingServletRequestParameterException 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;
}

Expand Down Expand Up @@ -92,7 +92,7 @@ public BaseResponse handleHttpMediaTypeNotAcceptableException(HttpMediaTypeNotAc
public BaseResponse handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
BaseResponse<?> baseResponse = handleBaseException(e);
baseResponse.setStatus(HttpStatus.BAD_REQUEST.value());
baseResponse.setMessage("Required request body is missing");
baseResponse.setMessage("缺失请求主体");
return baseResponse;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ public void handleCommentNewEvent(CommentNewEvent newEvent) {
return;
}

User user = userService.getCurrentUser().orElseThrow(() -> new ServiceException("找不到博主信息"));
User user = userService.getCurrentUser().orElseThrow(() -> new ServiceException("未查询到博主信息"));


Map<String, Object> data = new HashMap<>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,13 +43,14 @@ public UploadResult upload(MultipartFile file) {
Assert.notNull(file, "Multipart file must not be null");

// Get config
String ossDomain = optionService.getByPropertyOrDefault(AliYunProperties.OSS_DOMAIN, String.class, "");
String ossEndPoint = optionService.getByPropertyOfNonNull(AliYunProperties.OSS_ENDPOINT).toString();
String ossAccessKey = optionService.getByPropertyOfNonNull(AliYunProperties.OSS_ACCESS_KEY).toString();
String ossAccessSecret = optionService.getByPropertyOfNonNull(AliYunProperties.OSS_ACCESS_SECRET).toString();
String ossBucketName = optionService.getByPropertyOfNonNull(AliYunProperties.OSS_BUCKET_NAME).toString();
String ossSource = StringUtils.join("https://", ossBucketName, "." + ossEndPoint);
String ossStyleRule = optionService.getByPropertyOrDefault(AliYunProperties.OSS_STYLE_RULE,String.class,"");
String ossThumbnailStyleRule = optionService.getByPropertyOrDefault(AliYunProperties.OSS_THUMBNAIL_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, "");

// Init OSS client
OSS ossClient = new OSSClientBuilder().build(ossEndPoint, ossAccessKey, ossAccessSecret);
Expand All @@ -59,7 +60,7 @@ public UploadResult upload(MultipartFile file) {
String extension = FilenameUtils.getExtension(file.getOriginalFilename());
String timestamp = String.valueOf(System.currentTimeMillis());
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
PutObjectResult putObjectResult = ossClient.putObject(ossBucketName, upFilePath, file.getInputStream());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,15 +43,15 @@ public UploadResult upload(MultipartFile file) {
Assert.notNull(file, "Multipart file must not be null");

// Get config
String bosDomain = optionService.getByPropertyOrDefault(BaiDuYunProperties.BOS_DOMAIN, String.class, "");
String bosEndPoint = optionService.getByPropertyOfNonNull(BaiDuYunProperties.BOS_ENDPOINT).toString();
String bosAccessKey = optionService.getByPropertyOfNonNull(BaiDuYunProperties.BOS_ACCESS_KEY).toString();
String bosSecretKey = optionService.getByPropertyOfNonNull(BaiDuYunProperties.BOS_SECRET_KEY).toString();
String bosBucketName = optionService.getByPropertyOfNonNull(BaiDuYunProperties.BOS_BUCKET_NAME).toString();
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);


BosClientConfiguration config = new BosClientConfiguration();
config.setCredentials(new DefaultBceCredentials(bosAccessKey, bosSecretKey));
config.setEndpoint(bosEndPoint);
Expand All @@ -64,7 +64,7 @@ public UploadResult upload(MultipartFile file) {
String extension = FilenameUtils.getExtension(file.getOriginalFilename());
String timestamp = String.valueOf(System.currentTimeMillis());
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
PutObjectResponse putObjectResponseFromInputStream = client.putObject(bosBucketName, upFilePath, file.getInputStream());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,6 @@ public UploadResult upload(MultipartFile file) {
// Create temp path
Path tmpPath = Paths.get(System.getProperty("java.io.tmpdir"), bucket);


try {
String basename = FilenameUtils.getBasename(file.getOriginalFilename());
String extension = FilenameUtils.getExtension(file.getOriginalFilename());
Expand Down Expand Up @@ -149,7 +148,7 @@ public void delete(String key) {
bucketManager.delete(bucket, key);
} catch (QiniuException e) {
log.error("QnYun error response: [{}]", e.response);
throw new FileOperationException("Failed to delete file with " + key + " key", e);
throw new FileOperationException("附件 " + key + " 从七牛云删除失败", e);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ public UploadResult upload(MultipartFile file) {
Assert.notNull(file, "Multipart file must not be null");

// Get config
String cosDomain = optionService.getByPropertyOrDefault(TencentYunProperties.COS_DOMAIN, String.class, "");
String cosRegion = optionService.getByPropertyOfNonNull(TencentYunProperties.COS_REGION).toString();
String cosSecretId = optionService.getByPropertyOfNonNull(TencentYunProperties.COS_SECRET_ID).toString();
String cosSecretKey = optionService.getByPropertyOfNonNull(TencentYunProperties.COS_SECRET_KEY).toString();
Expand All @@ -71,7 +72,7 @@ public UploadResult upload(MultipartFile file) {
String extension = FilenameUtils.getExtension(file.getOriginalFilename());
String timestamp = String.valueOf(System.currentTimeMillis());
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
ObjectMetadata objectMetadata = new ObjectMetadata();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ public void delete(String key) {
log.warn("Failed to delete file " + key + " from UpYun");
}
} catch (Exception e) {
throw new FileOperationException("附件从又拍云删除失败", e);
throw new FileOperationException("附件 " + key + " 从又拍云删除失败", e);
}
}

Expand Down
1 change: 0 additions & 1 deletion src/main/java/run/halo/app/model/entity/PostCategory.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package run.halo.app.model.entity;

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;

import javax.persistence.*;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,11 @@
*/
public enum AliYunProperties implements PropertyEnum {

/**
* Aliyun oss domain
*/
OSS_DOMAIN("oss_aliyun_domain",String.class,""),

/**
* Aliyun oss endpoint.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,11 @@
*/
public enum BaiDuYunProperties implements PropertyEnum {

/**
* Baidu yun bos domain.
*/
BOS_DOMAIN("bos_baiduyun_domain",String.class,""),

/**
* Baidu yun bos endpoint.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,11 @@
*/
public enum TencentYunProperties implements PropertyEnum {

/**
* Tencentyun cos domain.
*/
COS_DOMAIN("cos_tencentyun_domain",String.class,""),

/**
* Tencentyun cos endpoint.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ protected void doAuthenticate(HttpServletRequest request, HttpServletResponse re
String token = getTokenFromRequest(request);

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;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -245,7 +245,7 @@ public void resetPasswordByCode(ResetPasswordParam param) {
throw new ServiceException("验证码不正确");
}

User user = userService.getCurrentUser().orElseThrow(() -> new ServiceException("找不到博主信息"));
User user = userService.getCurrentUser().orElseThrow(() -> new ServiceException("未查询到博主信息"));

// reset password
userService.setPassword(user, param.getPassword());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ public long countByStatus(PostStatus status) {
public POST getByUrl(String url) {
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
Expand All @@ -88,7 +88,7 @@ public POST getBy(PostStatus status, String url) {

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
Expand Down Expand Up @@ -175,7 +175,7 @@ public Page<POST> pageBy(PostStatus status, Pageable pageable) {
@Override
public void increaseVisit(long visits, Integer postId) {
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);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ public Category getBySlugName(String slugName) {

@Override
public Category getBySlugNameOfNonNull(String slugName) {
return categoryRepository.getBySlugName(slugName).orElseThrow(() -> new NotFoundException("该分类不存在").setErrorData(slugName));
return categoryRepository.getBySlugName(slugName).orElseThrow(() -> new NotFoundException("查询不到该分类的信息").setErrorData(slugName));
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public JournalCommentServiceImpl(JournalCommentRepository journalCommentReposito
@Override
public void validateTarget(Integer journalId) {
if (!journalRepository.existsById(journalId)) {
throw new NotFoundException("该日志不存在或已删除").setErrorData(journalId);
throw new NotFoundException("查询不到该日志信息").setErrorData(journalId);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ public Page<PostCommentWithPostVO> pageTreeBy(CommentQuery commentQuery, Pageabl
@Override
public void validateTarget(Integer postId) {
Post post = postRepository.findById(postId)
.orElseThrow(() -> new NotFoundException("该文章不存在或已删除").setErrorData(postId));
.orElseThrow(() -> new NotFoundException("查询不到该文章的信息").setErrorData(postId));

if (post.getDisallowComment()) {
throw new BadRequestException("该文章已经被禁止评论").setErrorData(postId);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,6 @@ public PostMetaServiceImpl(PostMetaRepository postMetaRepository,
@Override
public void validateTarget(Integer postId) {
postRepository.findById(postId)
.orElseThrow(() -> new NotFoundException("该文章不存在或已删除").setErrorData(postId));
.orElseThrow(() -> new NotFoundException("查询不到该文章的信息").setErrorData(postId));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ public SheetCommentServiceImpl(SheetCommentRepository sheetCommentRepository,
@Override
public void validateTarget(Integer sheetId) {
Sheet sheet = sheetRepository.findById(sheetId)
.orElseThrow(() -> new NotFoundException("该页面不存在或已删除").setErrorData(sheetId));
.orElseThrow(() -> new NotFoundException("查询不到该页面的信息").setErrorData(sheetId));

if (sheet.getDisallowComment()) {
throw new BadRequestException("该页面已被禁止评论").setErrorData(sheetId);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,6 @@ public SheetMetaServiceImpl(SheetMetaRepository sheetMetaRepository,
@Override
public void validateTarget(Integer sheetId) {
sheetRepository.findById(sheetId)
.orElseThrow(() -> new NotFoundException("该页面不存在或已删除").setErrorData(sheetId));
.orElseThrow(() -> new NotFoundException("查询不到该页面的信息").setErrorData(sheetId));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public Tag create(Tag tag) {

@Override
public Tag getBySlugNameOfNonNull(String slugName) {
return tagRepository.getBySlugName(slugName).orElseThrow(() -> new NotFoundException("该标签不存在").setErrorData(slugName));
return tagRepository.getBySlugName(slugName).orElseThrow(() -> new NotFoundException("查询不到该标签的信息").setErrorData(slugName));
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ public void setPassword(@NonNull User user, @NonNull String plainPassword) {

@Override
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);
}
}

0 comments on commit cbb2269

Please sign in to comment.