Refactor FileHandler

pull/137/head
johnniang 2019-03-27 13:28:58 +08:00
parent 5e60db3819
commit e48e0de6a4
22 changed files with 269 additions and 68 deletions

View File

@ -1,6 +1,7 @@
package cc.ryanc.halo.service.upload;
package cc.ryanc.halo.filehandler;
import cc.ryanc.halo.exception.FileUploadException;
import cc.ryanc.halo.model.enums.AttachmentType;
import cc.ryanc.halo.model.support.UploadResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
@ -38,6 +39,14 @@ public interface FileHandler {
*/
boolean delete(@NonNull String key);
/**
* Checks if the given type is supported.
*
* @param type attachment type
* @return true if supported; false or else
*/
boolean supportType(AttachmentType type);
/**
* Check whether media type provided is an image type.

View File

@ -0,0 +1,35 @@
package cc.ryanc.halo.filehandler;
import cc.ryanc.halo.config.properties.HaloProperties;
import cc.ryanc.halo.service.OptionService;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* File handler configuration.
*
* @author johnniang
* @date 3/27/19
*/
@Configuration
public class FileHandlerConfiguration {
@Bean
@ConditionalOnMissingBean
FileHandler localFileHandler(OptionService optionService, HaloProperties haloProperties) {
return new LocalFileHandler(optionService, haloProperties);
}
@Bean
@ConditionalOnMissingBean
FileHandler qnYunFileHandler(OptionService optionService) {
return new QnYunFileHandler(optionService);
}
@Bean
@ConditionalOnMissingBean
FileHandler upYunFileHandler(OptionService optionService) {
return new UpYunFileHandler(optionService);
}
}

View File

@ -0,0 +1,72 @@
package cc.ryanc.halo.filehandler;
import cc.ryanc.halo.exception.FileUploadException;
import cc.ryanc.halo.model.enums.AttachmentType;
import cc.ryanc.halo.model.support.UploadResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;
import java.util.Collection;
import java.util.LinkedList;
/**
* File handler manager.
*
* @author johnniang
* @date 3/27/19
*/
@Slf4j
@Component
public class FileHandlers {
/**
* File handler container.
*/
private final Collection<FileHandler> fileHandlers = new LinkedList<>();
public FileHandlers(ApplicationContext applicationContext) {
// Add all file handler
addFileHandlers(applicationContext.getBeansOfType(FileHandler.class).values());
}
public UploadResult upload(MultipartFile file, AttachmentType attachmentType) {
for (FileHandler fileHandler : fileHandlers) {
if (fileHandler.supportType(attachmentType)) {
return fileHandler.upload(file);
}
}
log.error("There is no available file handle for attachment type: [{}]", attachmentType);
throw new FileUploadException("No available file handler to filehandler the file").setErrorData(attachmentType);
}
public boolean delete(String key, AttachmentType attachmentType) {
for (FileHandler fileHandler : fileHandlers) {
if (fileHandler.supportType(attachmentType)) {
return fileHandler.delete(key);
}
}
log.error("There is no available file handle for attachment type: [{}]", attachmentType);
throw new FileUploadException("No available file handler to delete the file").setErrorData(attachmentType);
}
/**
* Adds file handlers.
*
* @param fileHandlers file handler collection
* @return current file handlers
*/
@NonNull
public FileHandlers addFileHandlers(@Nullable Collection<FileHandler> fileHandlers) {
if (!CollectionUtils.isEmpty(fileHandlers)) {
this.fileHandlers.addAll(fileHandlers);
}
return this;
}
}

View File

@ -1,7 +1,8 @@
package cc.ryanc.halo.service.upload;
package cc.ryanc.halo.filehandler;
import cc.ryanc.halo.config.properties.HaloProperties;
import cc.ryanc.halo.exception.ServiceException;
import cc.ryanc.halo.model.enums.AttachmentType;
import cc.ryanc.halo.model.support.UploadResult;
import cc.ryanc.halo.service.OptionService;
import cc.ryanc.halo.utils.FilenameUtils;
@ -23,8 +24,6 @@ import java.nio.file.Paths;
import java.util.Calendar;
import java.util.Objects;
import static cc.ryanc.halo.service.upload.FileHandler.isImageType;
/**
* Local file handler.
*
@ -126,7 +125,7 @@ public class LocalFileHandler implements FileHandler {
uploadResult.setSize(file.getSize());
// Check file type
if (isImageType(uploadResult.getMediaType())) {
if (FileHandler.isImageType(uploadResult.getMediaType())) {
// Upload a thumbnail
String thumbnailBasename = basename + '-' + "thumbnail";
String thumbnailSubFilePath = subDir + thumbnailBasename + '.' + extension;
@ -161,6 +160,11 @@ public class LocalFileHandler implements FileHandler {
return false;
}
@Override
public boolean supportType(AttachmentType type) {
return AttachmentType.LOCAL.equals(type);
}
/**
* Generates thumbnail image.
*

View File

@ -1,6 +1,7 @@
package cc.ryanc.halo.service.upload;
package cc.ryanc.halo.filehandler;
import cc.ryanc.halo.exception.FileUploadException;
import cc.ryanc.halo.model.enums.AttachmentType;
import cc.ryanc.halo.model.enums.QnYunProperties;
import cc.ryanc.halo.model.support.QiNiuPutSet;
import cc.ryanc.halo.model.support.UploadResult;
@ -26,7 +27,7 @@ import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;
import static cc.ryanc.halo.service.upload.FileHandler.isImageType;
import static cc.ryanc.halo.filehandler.FileHandler.isImageType;
/**
* Qi niu yun file handler.
@ -120,4 +121,9 @@ public class QnYunFileHandler implements FileHandler {
public boolean delete(String key) {
return false;
}
@Override
public boolean supportType(AttachmentType type) {
return AttachmentType.QNYUN.equals(type);
}
}

View File

@ -1,7 +1,8 @@
package cc.ryanc.halo.service.upload;
package cc.ryanc.halo.filehandler;
import cc.ryanc.halo.exception.FileUploadException;
import cc.ryanc.halo.exception.PropertyFormatException;
import cc.ryanc.halo.model.enums.AttachmentType;
import cc.ryanc.halo.model.enums.UpYunProperties;
import cc.ryanc.halo.model.support.UploadResult;
import cc.ryanc.halo.service.OptionService;
@ -18,8 +19,6 @@ import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.util.Objects;
import static cc.ryanc.halo.service.upload.FileHandler.isImageType;
/**
* Up Yun file handler.
*
@ -87,7 +86,7 @@ public class UpYunFileHandler implements FileHandler {
uploadResult.setSize(file.getSize());
// Handle thumbnail
if (isImageType(uploadResult.getMediaType())) {
if (FileHandler.isImageType(uploadResult.getMediaType())) {
BufferedImage image = ImageIO.read(file.getInputStream());
uploadResult.setWidth(image.getWidth());
uploadResult.setHeight(image.getHeight());
@ -104,4 +103,9 @@ public class UpYunFileHandler implements FileHandler {
public boolean delete(String key) {
return false;
}
@Override
public boolean supportType(AttachmentType type) {
return AttachmentType.UPYUN.equals(type);
}
}

View File

@ -143,7 +143,7 @@ public class StartedListener implements ApplicationListener<ApplicationStartedEv
*/
private void initThemes() {
// Whether the blog has initialized
Boolean isInstalled = optionService.getByProperty(BlogProperties.IS_INSTALL, Boolean.class, false);
Boolean isInstalled = optionService.getByPropertyOrDefault(BlogProperties.IS_INSTALL, Boolean.class, false);
try {
if (isInstalled) {
// Skip

View File

@ -19,6 +19,8 @@ public class AttachmentOutputDTO implements OutputConverter<AttachmentOutputDTO,
private String path;
private String fileKey;
private String thumbPath;
private String mediaType;

View File

@ -115,7 +115,7 @@ public class Attachment extends BaseEntity {
}
if (type == null) {
type = AttachmentType.SERVER;
type = AttachmentType.LOCAL;
}
}
}

View File

@ -11,7 +11,7 @@ public enum AttachmentType implements ValueEnum<Integer> {
/**
*
*/
SERVER(0),
LOCAL(0),
/**
*
@ -21,7 +21,7 @@ public enum AttachmentType implements ValueEnum<Integer> {
/**
*
*/
QINIUYUN(2);
QNYUN(2);
private Integer value;

View File

@ -1,6 +1,7 @@
package cc.ryanc.halo.model.enums;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
/**
@ -78,6 +79,7 @@ public interface PropertyEnum extends ValueEnum<String> {
* @param <T> property value enum type
* @return property enum value or null
*/
@Nullable
static <T extends Enum<T>> T convertToEnum(@NonNull String value, @NonNull Class<T> type) {
Assert.hasText(value, "Property value must not be blank");

View File

@ -1,6 +1,7 @@
package cc.ryanc.halo.model.support;
import lombok.Data;
import lombok.ToString;
import org.springframework.http.MediaType;
/**
@ -10,6 +11,7 @@ import org.springframework.http.MediaType;
* @date 3/26/19
*/
@Data
@ToString
public class UploadResult {
private String filename;

View File

@ -1,10 +1,13 @@
package cc.ryanc.halo.service;
import cc.ryanc.halo.exception.FileUploadException;
import cc.ryanc.halo.model.dto.AttachmentOutputDTO;
import cc.ryanc.halo.model.entity.Attachment;
import cc.ryanc.halo.service.base.CrudService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.lang.NonNull;
import org.springframework.web.multipart.MultipartFile;
/**
@ -21,4 +24,14 @@ public interface AttachmentService extends CrudService<Attachment, Integer> {
* @return a page of attachment output dto
*/
Page<AttachmentOutputDTO> pageDtosBy(Pageable pageable);
/**
* Uploads file.
*
* @param file multipart file must not be null
* @return attachment info
* @throws FileUploadException throws when failed to filehandler the file
*/
@NonNull
Attachment upload(@NonNull MultipartFile file);
}

View File

@ -1,11 +0,0 @@
package cc.ryanc.halo.service;
/**
* File service interface.
*
* @author johnniang
* @date 3/26/19
*/
public interface FileService {
}

View File

@ -139,7 +139,7 @@ public interface OptionService extends CrudService<Option, Integer> {
* @param <T> property type
* @return property value
*/
<T> T getByProperty(@NonNull PropertyEnum property, @NonNull Class<T> propertyType, T defaultValue);
<T> T getByPropertyOrDefault(@NonNull PropertyEnum property, @NonNull Class<T> propertyType, T defaultValue);
/**
* Gets property value by blog property.
@ -160,7 +160,7 @@ public interface OptionService extends CrudService<Option, Integer> {
* @param <T> property type
* @return value
*/
<T> T getByKey(@NonNull String key, @NonNull Class<T> valueType, T defaultValue);
<T> T getByKeyOrDefault(@NonNull String key, @NonNull Class<T> valueType, T defaultValue);
/**
* Gets value by key.
@ -172,6 +172,27 @@ public interface OptionService extends CrudService<Option, Integer> {
*/
<T> Optional<T> getByKey(@NonNull String key, @NonNull Class<T> valueType);
/**
* Gets enum value by property.
*
* @param property property must not be blank
* @param valueType enum value type must not be null
* @param <T> enum value type
* @return an optional enum value
*/
<T extends Enum<T>> Optional<T> getEnumByProperty(@NonNull PropertyEnum property, @NonNull Class<T> valueType);
/**
* Gets enum value by property.
*
* @param property property must not be blank
* @param valueType enum value type must not be null
* @param defaultValue default value
* @param <T> enum value type
* @return enum value
*/
<T extends Enum<T>> T getEnumByPropertyOrDefault(@NonNull PropertyEnum property, @NonNull Class<T> valueType, T defaultValue);
/**
* Gets post page size.
*

View File

@ -2,13 +2,21 @@ package cc.ryanc.halo.service.impl;
import cc.ryanc.halo.model.dto.AttachmentOutputDTO;
import cc.ryanc.halo.model.entity.Attachment;
import cc.ryanc.halo.model.enums.AttachmentType;
import cc.ryanc.halo.model.enums.BlogProperties;
import cc.ryanc.halo.model.support.UploadResult;
import cc.ryanc.halo.repository.AttachmentRepository;
import cc.ryanc.halo.service.AttachmentService;
import cc.ryanc.halo.service.OptionService;
import cc.ryanc.halo.service.base.AbstractCrudService;
import cc.ryanc.halo.filehandler.FileHandlers;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;
/**
* AttachmentService implementation class
@ -16,14 +24,23 @@ import org.springframework.util.Assert;
* @author : RYAN0UP
* @date : 2019-03-14
*/
@Slf4j
@Service
public class AttachmentServiceImpl extends AbstractCrudService<Attachment, Integer> implements AttachmentService {
private final AttachmentRepository attachmentRepository;
public AttachmentServiceImpl(AttachmentRepository attachmentRepository) {
private final OptionService optionService;
private final FileHandlers fileHandlers;
public AttachmentServiceImpl(AttachmentRepository attachmentRepository,
OptionService optionService,
FileHandlers fileHandlers) {
super(attachmentRepository);
this.attachmentRepository = attachmentRepository;
this.optionService = optionService;
this.fileHandlers = fileHandlers;
}
@Override
@ -36,4 +53,43 @@ public class AttachmentServiceImpl extends AbstractCrudService<Attachment, Integ
// Convert and return
return attachmentPage.map(attachment -> new AttachmentOutputDTO().convertFrom(attachment));
}
@Override
public Attachment upload(MultipartFile file) {
Assert.notNull(file, "Multipart file must not be null");
AttachmentType attachmentType = getAttachmentType();
// Upload file
UploadResult uploadResult = fileHandlers.upload(file, attachmentType);
log.debug("Attachment type: [{}]", attachmentType);
log.debug("Upload result: [{}]", uploadResult);
// Build attachment
Attachment attachment = new Attachment();
attachment.setName(uploadResult.getFilename());
attachment.setPath(uploadResult.getFilePath());
attachment.setFileKey(uploadResult.getKey());
attachment.setThumbPath(uploadResult.getThumbPath());
attachment.setMediaType(uploadResult.getMediaType().toString());
attachment.setSuffix(uploadResult.getSuffix());
attachment.setWidth(uploadResult.getWidth());
attachment.setHeight(uploadResult.getHeight());
attachment.setSize(uploadResult.getSize());
attachment.setType(attachmentType);
// Create and return
return create(attachment);
}
/**
* Get attachment type from options.
*
* @return attachment type
*/
@NonNull
private AttachmentType getAttachmentType() {
return optionService.getEnumByPropertyOrDefault(BlogProperties.ATTACHMENT_TYPE, AttachmentType.class, AttachmentType.LOCAL);
}
}

View File

@ -120,7 +120,7 @@ public class CommentServiceImpl extends AbstractCrudService<Comment, Long> imple
}
// Handle comment status
Boolean needAudit = optionService.getByProperty(BlogProperties.NEW_COMMENT_NEED_CHECK, Boolean.class, true);
Boolean needAudit = optionService.getByPropertyOrDefault(BlogProperties.NEW_COMMENT_NEED_CHECK, Boolean.class, true);
if (needAudit) {
comment.setStatus(CommentStatus.AUDITING);
} else {

View File

@ -1,17 +0,0 @@
package cc.ryanc.halo.service.impl;
import cc.ryanc.halo.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
/**
* File service implementation.
*
* @author johnniang
* @date 3/26/19
*/
@Slf4j
@Service
public class FileServiceImpl implements FileService {
}

View File

@ -167,7 +167,7 @@ public class OptionServiceImpl extends AbstractCrudService<Option, Integer> impl
}
@Override
public <T> T getByProperty(PropertyEnum property, Class<T> propertyType, T defaultValue) {
public <T> T getByPropertyOrDefault(PropertyEnum property, Class<T> propertyType, T defaultValue) {
Assert.notNull(property, "Blog property must not be null");
return getByProperty(property, propertyType).orElse(defaultValue);
@ -179,7 +179,7 @@ public class OptionServiceImpl extends AbstractCrudService<Option, Integer> impl
}
@Override
public <T> T getByKey(String key, Class<T> valueType, T defaultValue) {
public <T> T getByKeyOrDefault(String key, Class<T> valueType, T defaultValue) {
return getByKey(key, valueType).orElse(defaultValue);
}
@ -188,10 +188,20 @@ public class OptionServiceImpl extends AbstractCrudService<Option, Integer> impl
return getByKey(key).map(value -> PropertyEnum.convertTo(value, valueType));
}
@Override
public <T extends Enum<T>> Optional<T> getEnumByProperty(PropertyEnum property, Class<T> valueType) {
return getByProperty(property).map(value -> PropertyEnum.convertToEnum(value, valueType));
}
@Override
public <T extends Enum<T>> T getEnumByPropertyOrDefault(PropertyEnum property, Class<T> valueType, T defaultValue) {
return getEnumByProperty(property, valueType).orElse(defaultValue);
}
@Override
public int getPostPageSize() {
try {
return getByProperty(BlogProperties.INDEX_POSTS, Integer.class, DEFAULT_COMMENT_PAGE_SIZE);
return getByPropertyOrDefault(BlogProperties.INDEX_POSTS, Integer.class, DEFAULT_COMMENT_PAGE_SIZE);
} catch (NumberFormatException e) {
log.error(BlogProperties.INDEX_POSTS + " option is not a number format", e);
return DEFAULT_POST_PAGE_SIZE;
@ -201,7 +211,7 @@ public class OptionServiceImpl extends AbstractCrudService<Option, Integer> impl
@Override
public int getCommentPageSize() {
try {
return getByProperty(BlogProperties.INDEX_COMMENTS, Integer.class, DEFAULT_COMMENT_PAGE_SIZE);
return getByPropertyOrDefault(BlogProperties.INDEX_COMMENTS, Integer.class, DEFAULT_COMMENT_PAGE_SIZE);
} catch (NumberFormatException e) {
log.error(BlogProperties.INDEX_COMMENTS + " option is not a number format", e);
return DEFAULT_COMMENT_PAGE_SIZE;
@ -211,7 +221,7 @@ public class OptionServiceImpl extends AbstractCrudService<Option, Integer> impl
@Override
public int getRssPageSize() {
try {
return getByProperty(BlogProperties.RSS_POSTS, Integer.class, DEFAULT_COMMENT_PAGE_SIZE);
return getByPropertyOrDefault(BlogProperties.RSS_POSTS, Integer.class, DEFAULT_COMMENT_PAGE_SIZE);
} catch (NumberFormatException e) {
log.error(BlogProperties.RSS_POSTS + " setting is not a number format", e);
return DEFAULT_RSS_PAGE_SIZE;

View File

@ -1,9 +1,7 @@
package cc.ryanc.halo.web.controller.admin.api;
import cc.ryanc.halo.model.dto.AttachmentOutputDTO;
import cc.ryanc.halo.model.support.UploadResult;
import cc.ryanc.halo.service.AttachmentService;
import cc.ryanc.halo.service.FileService;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
@ -25,12 +23,9 @@ public class AttachmentController {
private final AttachmentService attachmentService;
private final FileService fileService;
public AttachmentController(AttachmentService attachmentService,
FileService fileService) {
public AttachmentController(AttachmentService attachmentService) {
this.attachmentService = attachmentService;
this.fileService = fileService;
}
/**
@ -68,8 +63,7 @@ public class AttachmentController {
}
@PostMapping("upload")
public UploadResult uploadAttachment(@RequestParam("file") MultipartFile file) {
// TODO Just for test
return fileService.uploadToLocal(file);
public AttachmentOutputDTO uploadAttachment(@RequestParam("file") MultipartFile file) {
return new AttachmentOutputDTO().convertFrom(attachmentService.upload(file));
}
}

View File

@ -7,7 +7,6 @@ import cc.ryanc.halo.model.enums.BlogProperties;
import cc.ryanc.halo.model.params.InstallParam;
import cc.ryanc.halo.model.support.BaseResponse;
import cc.ryanc.halo.service.*;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import freemarker.template.Configuration;
import lombok.extern.slf4j.Slf4j;
@ -168,12 +167,12 @@ public class InstallController {
properties.put(BlogProperties.BLOG_TITLE, installParam.getTitle());
properties.put(BlogProperties.BLOG_URL, installParam.getUrl());
properties.put(BlogProperties.THEME, DEFAULT_THEME_NAME);
properties.put(BlogProperties.BLOG_START, DateUtil.format(DateUtil.date(), "yyyy-MM-dd"));
properties.put(BlogProperties.BLOG_START, String.valueOf(System.currentTimeMillis()));
properties.put(BlogProperties.SMTP_EMAIL_ENABLE, Boolean.FALSE.toString());
properties.put(BlogProperties.NEW_COMMENT_NOTICE, Boolean.FALSE.toString());
properties.put(BlogProperties.COMMENT_PASS_NOTICE, Boolean.FALSE.toString());
properties.put(BlogProperties.COMMENT_REPLY_NOTICE, Boolean.FALSE.toString());
properties.put(BlogProperties.ATTACHMENT_TYPE, AttachmentType.SERVER.getValue().toString());
properties.put(BlogProperties.ATTACHMENT_TYPE, AttachmentType.LOCAL.getValue().toString());
// Create properties
optionService.saveProperties(properties, "system");

View File

@ -24,9 +24,9 @@ public class AttachmentTypeTest {
@Test
public void conversionTest() {
assertThat(conversionService.convert("SERVER", AttachmentType.class), equalTo(AttachmentType.SERVER));
assertThat(conversionService.convert("server", AttachmentType.class), equalTo(AttachmentType.SERVER));
assertThat(conversionService.convert("Server", AttachmentType.class), equalTo(AttachmentType.SERVER));
assertThat(conversionService.convert("SerVer", AttachmentType.class), equalTo(AttachmentType.SERVER));
assertThat(conversionService.convert("SERVER", AttachmentType.class), equalTo(AttachmentType.LOCAL));
assertThat(conversionService.convert("server", AttachmentType.class), equalTo(AttachmentType.LOCAL));
assertThat(conversionService.convert("Server", AttachmentType.class), equalTo(AttachmentType.LOCAL));
assertThat(conversionService.convert("SerVer", AttachmentType.class), equalTo(AttachmentType.LOCAL));
}
}