Search in sources :

Example 1 with ServiceException

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;
}
Also used : HttpEntity(org.springframework.http.HttpEntity) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) FileOperationException(run.halo.app.exception.FileOperationException) IOException(java.io.IOException) HttpClientUtils(run.halo.app.utils.HttpClientUtils) ServiceException(run.halo.app.exception.ServiceException) UploadResult(run.halo.app.model.support.UploadResult)

Example 2 with ServiceException

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();
}
Also used : RandomAccessFile(java.io.RandomAccessFile) ServiceException(run.halo.app.exception.ServiceException) ArrayList(java.util.ArrayList) IOException(java.io.IOException) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File) NotFoundException(run.halo.app.exception.NotFoundException) IOException(java.io.IOException) BadRequestException(run.halo.app.exception.BadRequestException) ServiceException(run.halo.app.exception.ServiceException)

Example 3 with ServiceException

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);
    }
}
Also used : Path(java.nio.file.Path) ServiceException(run.halo.app.exception.ServiceException) BadRequestException(run.halo.app.exception.BadRequestException) IOException(java.io.IOException)

Example 4 with ServiceException

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);
    }
}
Also used : Path(java.nio.file.Path) ServiceException(run.halo.app.exception.ServiceException) NoSuchFileException(java.nio.file.NoSuchFileException) NotFoundException(run.halo.app.exception.NotFoundException) IOException(java.io.IOException)

Example 5 with ServiceException

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;
}
Also used : ServiceException(run.halo.app.exception.ServiceException) BackupDTO(run.halo.app.model.dto.BackupDTO) IOException(java.io.IOException)

Aggregations

ServiceException (run.halo.app.exception.ServiceException)80 IOException (java.io.IOException)60 Path (java.nio.file.Path)39 NotFoundException (run.halo.app.exception.NotFoundException)18 NoSuchFileException (java.nio.file.NoSuchFileException)9 BadRequestException (run.halo.app.exception.BadRequestException)9 FileOperationException (run.halo.app.exception.FileOperationException)9 User (run.halo.app.model.entity.User)9 HashMap (java.util.HashMap)6 ThemePropertyMissingException (run.halo.app.exception.ThemePropertyMissingException)6 ThemeUpdateException (run.halo.app.exception.ThemeUpdateException)6 ThemeProperty (run.halo.app.handler.theme.config.support.ThemeProperty)6 Transactional (org.springframework.transaction.annotation.Transactional)5 NonNull (org.springframework.lang.NonNull)4 ThemeNotSupportException (run.halo.app.exception.ThemeNotSupportException)4 TemplateModelException (freemarker.template.TemplateModelException)3 MalformedURLException (java.net.MalformedURLException)3 URISyntaxException (java.net.URISyntaxException)3 LinkedList (java.util.LinkedList)3 ZipInputStream (java.util.zip.ZipInputStream)3