16 Aralık 2022 Cuma

AWS S3 API AmazonS3 Sınıfı

Giriş
Şu satırı dahil ederiz
import com.amazonaws.services.s3.AmazonS3;
Bu sınıf AWS S3 hizmetlerine erişmek için kullanılır

constructor
AmazonS3ClientBuilder tarafından yaratılır

createBucket metodu
Örnek
Şöyle yaparız
public void createS3Bucket(String bucketName, boolean publicBucket) {
  if(amazonS3Client.doesBucketExist(bucketName)) {
    log.info("Bucket name already in use. Try another name.");
    return;
  }
  if(publicBucket) {
    amazonS3Client.createBucket(bucketName);
  } else {
    amazonS3Client.createBucket(new CreateBucketRequest(bucketName)
                                     .withCannedAcl(CannedAccessControlList.Private));
  }
}
copyObject metodu
Örnek
Şöyle yaparız
public void moveObject(String bucketSourceName, String objectName, 
  String bucketTargetName){
  amazonS3Client.copyObject(
    bucketSourceName,
    objectName,
    bucketTargetName,
    objectName
  );
}
deleteObject metodu
Örnek
Şöyle yaparız
public void deleteObject(String bucketName, String objectName){
  amazonS3Client.deleteObject(bucketName, objectName);
}
deleteObjects metodu
Örnek
Şöyle yaparız
public void deleteMultipleObjects(String bucketName, List<String> objects){
  DeleteObjectsRequest delObjectsRequests = new DeleteObjectsRequest(bucketName)
    .withKeys(objects.toArray(new String[0]));
  amazonS3Client.deleteObjects(delObjectsRequests);
}
getObjectContent metodu
Örnek
Şöyle yaparız
public void downloadObject(String bucketName, String objectName){
  S3Object s3object = amazonS3Client.getObject(bucketName, objectName);
  S3ObjectInputStream inputStream = s3object.getObjectContent();
  try {
    FileUtils.copyInputStreamToFile(inputStream, 
      new File("." + File.separator + objectName));
  } catch (IOException e) {
    log.error(e.getMessage());
  }
}
generatePresignedUrl metodu - bucketName + filePath
Açıklaması şöyle
When we want to upload the files there are 2 ways to do that:

- The first way is that the Frontend will pass the file to your server via REST API and then you will call the s3 SDK to upload the file and return the result back to the Frontend.

- And the second way is something called pre-signed URLs. Pre-Signed URLs are URLs that have limited permissions and expiry. any client can use that URL to PUT the file directly to s3 without the need to worry about the AWS access key and secret.
Örnek
10 dakika boyunca geçerli URL için şöyle yaparız
public String generatePreSignedUrl(String filePath,
                                   String bucketName,
                                   HttpMethod httpMethod) {
  Calendar calendar = Calendar.getInstance();
  calendar.setTime(new Date());
  calendar.add(Calendar.MINUTE, 10); //validity of 10 minutes
  return amazonS3.generatePresignedUrl(bucketName, filePath, 
    calendar.getTime(), httpMethod).toString();
}
Açıklaması şöyle
filePath : this is the object key for your s3 that you want to upload files.

bucketName : this is the bucket name for your s3 bucket.

httpMethod : this is the allowed HTTP Method for your Pre-Signed URL. Here we want to upload the file so we will pass HttpMethod.PUT it here.
Yani şöyle çağırırız. Böylece 10 dakika boyunca geçerli bir adrese PUT işlemi yapılabilir.
awsS3Service.generatePreSignedUrl(UUID.randomUUID() + ".txt", 
  "my-bucket-name", HttpMethod.PUT));
Örnek - bucket + filePath
1 gün boyunca geçerlir URL için şöyle yaparız
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
cal.add(Calendar.DATE, 1);
Date expiration = cal.getTime();


String key = ...
GeneratePresignedUrlRequest generatePresignedUrlRequest =
  new GeneratePresignedUrlRequest(bucket, key)
    .withMethod(HttpMethod.GET)
    .withExpiration(expiration);
URL url = s3.generatePresignedUrl(generatePresignedUrlRequest);

return PreSignedUrlDTO.builder()
  .url(url.toString())
  .expiration(expiration)
  .build();
listBuckets metodu
Örnek
Şöyle yaparız
public List<Bucket> listBuckets(){
  return amazonS3Client.listBuckets();
}
listObjects metodu
Örnek
Şöyle yaparız
public List<S3ObjectSummary> listObjects(String bucketName){
  ObjectListing objectListing = amazonS3Client.listObjects(bucketName);
  return objectListing.getObjectSummaries();
}
listObjectsV2 metodu
En fazla 1000 tane sonuç döndürür.
Örnek
Şöyle yaparız
ListObjectsV2Request listObjectsV2Request = new ListObjectsV2Request();
List<S3ObjectSummary> objectSummaries =
  amazonS3Client.listObjectsV2(listObjectsV2Request).getObjectSummaries();
Eğer her şeyi listelemek istersek ListObjectsV2Result.getNextContinuationToken() metodunu yeni istek ile göndermek gerekir. Şöyle yaparız
ListObjectsV2Request listObjectsV2Request = new ListObjectsV2Request();
listObjectsV2Request.setBucketName(myBucketName);
listObjectsV2Request.setPrefix(path);

List<S3ObjectSummary> objectSummariesList = new ArrayList<>();
ListObjectsV2Result listObjectsV2Result;
do {
  listObjectsV2Result = amazonS3Client.listObjectsV2(listObjectsV2Request);
  objectSummariesList.addAll(listObjectsV2Result.getObjectSummaries())
  listObjectsV2Request
    .setContinuationToken(listObjectsV2Result.getNextContinuationToken());
} while (listObjectsV2Result.isTruncated());

putObject metodu
Örnek
Şöyle yaparız
public void putObject(String bucketName, 
  BucketObjectRepresentaion representation, 
  boolean publicObject) throws IOException {

  String objectName = representation.getObjectName();
  String objectValue = representation.getText();

  File file = new File("." + File.separator + objectName);
  FileWriter fileWriter = new FileWriter(file, false);
  PrintWriter printWriter = new PrintWriter(fileWriter);
  printWriter.println(objectValue);
  printWriter.flush();
  printWriter.close();

  try {
    if(publicObject) {
      var putObjectRequest = new PutObjectRequest(bucketName, objectName, file)
        .withCannedAcl(CannedAccessControlList.PublicRead);
      amazonS3Client.putObject(putObjectRequest);
    } else {
      var putObjectRequest = new PutObjectRequest(bucketName, objectName, file)
        .withCannedAcl(CannedAccessControlList.Private);
      amazonS3Client.putObject(putObjectRequest);
    }
  } catch (Exception e){
    log.error("Some error has ocurred.");
  }
}
Örnek
Şöyle yaparız. path olarak bucket name verilir. filename olarak istediğimiz şeyi veririz.
@Service 
public class Storage {
	
  private final AmazonS3 s3;

  public void save(String path,String fileName,
                   Optional<Map<String,String>> optionalMetadata,
		   InputStream inputStream) {
					   
    ObjectMetadata metadata = new ObjectMetadata();
    optionalMetadata.ifPresent(map -> {
      if(!map.isEmpty()) {
        for (Map.Entry<String, String> entry : map.entrySet()) {
        String key = entry.getKey();
        String value = entry.getValue();
        if (key == "Content-Length") {
          metadata.setContentLength(Long.parseLong(value));
         }
         if (key == "Content-Type") {
          metadata.setContentType(value);
         }
        }
      }
    });
    try {
      s3.putObject(new PutObjectRequest(path,fileName,inputStream, metadata)
      .withCannedAcl(CannedAccessControlList.PublicRead));
    } catch (AmazonServiceException e) {
      throw new IllegalStateException("Failed to store file", e);
    } 
  } 
}



Hiç yorum yok:

Yorum Gönder