All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.fivefaces.cloud.file_storage.AWSS3FileService Maven / Gradle / Ivy

There is a newer version: 1.0.0
Show newest version
package com.fivefaces.cloud.file_storage;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.DeleteObjectRequest;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.fivefaces.cloud.Utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.util.Date;
import java.util.UUID;

import static com.fivefaces.common.cloud.CloudConstants.getCannotSaveFile;

@Profile("FILE_STORAGE_AWS_S3")
@Slf4j
@Service
public class AWSS3FileService implements FileService {

    private final Utils utils;
    private AmazonS3 s3Client;

    public AWSS3FileService(Utils utils) {
        this.utils = utils;
    }

    @Override
    public String saveFile(final String bucketName, final String filename, byte[] data) {
        try {
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentLength(data.length);
            String fileKey = generateFileKey(filename);
            PutObjectRequest request = new PutObjectRequest(bucketName, fileKey, new ByteArrayInputStream(data), metadata);
            getS3Client().putObject(request);
            return fileKey;
        } catch (SdkClientException e) {
            log.error(getCannotSaveFile(e));
            throw new IllegalStateException(getCannotSaveFile(e));
        }
    }

    @Override
    public String getFileUrl(final String bucketName, final String fileKey) {
        Date expiration = new Date();
        expiration.setTime(expiration.getTime() + (1000 * 60));
        return getS3Client().generatePresignedUrl(bucketName, fileKey, expiration).toExternalForm();
    }

    @Override
    public void delete(final String bucketName, final String fileKey) {
        getS3Client().deleteObject(new DeleteObjectRequest(bucketName, fileKey));
    }

    private AmazonS3 getS3Client() {
        if (s3Client == null) {
            s3Client = utils.generateS3Client();
        }
        return s3Client;
    }

    private String generateFileKey(String filename) {
        return String.format("%s/%s", UUID.randomUUID(), filename);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy