use of run.halo.app.exception.ServiceException in project halo by ruibaby.
the class SmmsFileHandler method upload.
@Override
public UploadResult upload(MultipartFile file) {
Assert.notNull(file, "Multipart file must not be null");
String apiSecretToken = optionService.getByPropertyOfNonNull(SmmsProperties.SMMS_API_SECRET_TOKEN).toString();
if (StringUtils.isEmpty(apiSecretToken)) {
throw new ServiceException("请先设置 SM.MS 的 Secret Token");
}
if (!isImageType(file)) {
log.error("Invalid extension: [{}]", file.getContentType());
throw new FileOperationException("不支持的文件类型,仅支持 \"jpeg, jpg, png, gif, bmp\" 格式的图片");
}
setHeaders();
// Set content type
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
LinkedMultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
try {
body.add("smfile", new HttpClientUtils.MultipartFileResource(file.getBytes(), file.getOriginalFilename()));
} catch (IOException e) {
log.error("Failed to get file input stream", e);
throw new FileOperationException("上传附件 " + file.getOriginalFilename() + " 到 SM.MS 失败", e);
}
body.add("format", "json");
HttpEntity<LinkedMultiValueMap<String, Object>> httpEntity = new HttpEntity<>(body, headers);
// Upload file
ResponseEntity<SmmsResponse> mapResponseEntity = httpsRestTemplate.postForEntity(UPLOAD_API_V2, httpEntity, SmmsResponse.class);
// Check status
if (mapResponseEntity.getStatusCode().isError()) {
log.error("Server response detail: [{}]", mapResponseEntity);
throw new FileOperationException("SM.MS 服务状态异常,状态码: " + mapResponseEntity.getStatusCodeValue());
}
// Get smms response
SmmsResponse smmsResponse = mapResponseEntity.getBody();
// Check error
if (!isResponseSuccessfully(smmsResponse)) {
log.error("Smms response detail: [{}]", smmsResponse);
throw new FileOperationException(smmsResponse == null ? "SM.MS 服务返回内容为空" : smmsResponse.getMessage()).setErrorData(smmsResponse);
}
if (!smmsResponse.getSuccess()) {
throw new FileOperationException("上传请求失败:" + smmsResponse.getMessage()).setErrorData(smmsResponse);
}
// Get response data
SmmsResponseData data = smmsResponse.getData();
// Build result
UploadResult result = new UploadResult();
result.setFilename(FilenameUtils.getBasename(Objects.requireNonNull(file.getOriginalFilename())));
result.setSuffix(FilenameUtils.getExtension(file.getOriginalFilename()));
result.setMediaType(MediaType.valueOf(Objects.requireNonNull(file.getContentType())));
result.setFilePath(data.getUrl());
result.setThumbPath(data.getUrl());
result.setKey(data.getHash());
result.setWidth(data.getWidth());
result.setHeight(data.getHeight());
result.setSize(data.getSize().longValue());
log.info("File: [{}] uploaded successfully", file.getOriginalFilename());
return result;
}
use of run.halo.app.exception.ServiceException in project halo by ruibaby.
the class AdminServiceImpl method getLogFiles.
@Override
public String getLogFiles(@NonNull Long lines) {
Assert.notNull(lines, "Lines must not be null");
File file = new File(haloProperties.getWorkDir(), LOG_PATH);
List<String> linesArray = new ArrayList<>();
final StringBuilder result = new StringBuilder();
if (!file.exists()) {
return StringUtils.EMPTY;
}
long count = 0;
RandomAccessFile randomAccessFile = null;
try {
randomAccessFile = new RandomAccessFile(file, "r");
long length = randomAccessFile.length();
if (length == 0L) {
return StringUtils.EMPTY;
} else {
long pos = length - 1;
while (pos > 0) {
pos--;
randomAccessFile.seek(pos);
if (randomAccessFile.readByte() == '\n') {
String line = randomAccessFile.readLine();
linesArray.add(new String(line.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8));
count++;
if (count == lines) {
break;
}
}
}
if (pos == 0) {
randomAccessFile.seek(0);
linesArray.add(new String(randomAccessFile.readLine().getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8));
}
}
} catch (Exception e) {
throw new ServiceException("读取日志失败", e);
} finally {
if (randomAccessFile != null) {
try {
randomAccessFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Collections.reverse(linesArray);
linesArray.forEach(line -> result.append(line).append(StringUtils.LF));
return result.toString();
}
use of run.halo.app.exception.ServiceException in project halo by ruibaby.
the class BackupServiceImpl method backupWorkDirectory.
@Override
public BackupDTO backupWorkDirectory(List<String> options) {
if (CollectionUtils.isEmpty(options)) {
throw new BadRequestException("The options parameter is missing, at least one.");
}
// Zip work directory to temporary file
try {
// Create zip path for halo zip
String haloZipFileName = HALO_BACKUP_PREFIX + DateTimeUtils.format(LocalDateTime.now(), HORIZONTAL_LINE_DATETIME_FORMATTER) + HaloUtils.simpleUUID().hashCode() + ".zip";
// Create halo zip file
Path haloZipFilePath = Paths.get(haloProperties.getBackupDir(), haloZipFileName);
if (!Files.exists(haloZipFilePath.getParent())) {
Files.createDirectories(haloZipFilePath.getParent());
}
Path haloZipPath = Files.createFile(haloZipFilePath);
// Zip halo
run.halo.app.utils.FileUtils.zip(Paths.get(this.haloProperties.getWorkDir()), haloZipPath, path -> {
for (String itemToBackup : options) {
Path backupItemPath = Paths.get(this.haloProperties.getWorkDir()).resolve(itemToBackup);
if (path.startsWith(backupItemPath)) {
return true;
}
}
return false;
});
// Build backup dto
return buildBackupDto(BACKUP_RESOURCE_BASE_URI, haloZipPath);
} catch (IOException e) {
throw new ServiceException("Failed to backup halo", e);
}
}
use of run.halo.app.exception.ServiceException in project halo by ruibaby.
the class BackupServiceImpl method deleteWorkDirBackup.
@Override
public void deleteWorkDirBackup(String fileName) {
Assert.hasText(fileName, "File name must not be blank");
Path backupRootPath = Paths.get(haloProperties.getBackupDir());
// Get backup path
Path backupPath = backupRootPath.resolve(fileName);
// Check directory traversal
checkDirectoryTraversal(backupRootPath, backupPath);
try {
// Delete backup file
Files.delete(backupPath);
} catch (NoSuchFileException e) {
throw new NotFoundException("The file " + fileName + " was not found", e);
} catch (IOException e) {
throw new ServiceException("Failed to delete backup", e);
}
}
use of run.halo.app.exception.ServiceException in project halo by ruibaby.
the class BackupServiceImpl method buildBackupDto.
/**
* Builds backup dto.
*
* @param backupPath backup path must not be null
* @return backup dto
*/
private BackupDTO buildBackupDto(@NonNull String basePath, @NonNull Path backupPath) {
Assert.notNull(basePath, "Base path must not be null");
Assert.notNull(backupPath, "Backup path must not be null");
String backupFileName = backupPath.getFileName().toString();
BackupDTO backup = new BackupDTO();
try {
backup.setDownloadLink(buildDownloadUrl(basePath, backupFileName));
backup.setFilename(backupFileName);
backup.setUpdateTime(Files.getLastModifiedTime(backupPath).toMillis());
backup.setFileSize(Files.size(backupPath));
} catch (IOException e) {
throw new ServiceException("Failed to access file " + backupPath, e);
}
return backup;
}
Aggregations