Skip to content

Commit

Permalink
#21 feat: 특정 인증서(pdf) 삭제하는 API 생성(메타데이터 수정 로직 제외)
Browse files Browse the repository at this point in the history
  • Loading branch information
jinno321 committed Sep 21, 2024
1 parent 57209a8 commit a0b6582
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 13 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public S3StorageController(S3StorageService s3StorageService, WalletService wall
this.walletService = walletService;
}

@Operation(summary = "pdf 업로드",description = "s3 스토리지에 pdf 파일을 업로드 합니다.")
@Operation(summary = "인증서(pdf) 업로드",description = "인증서를 업로드합니다. 즉,s3 스토리지에 pdf 파일을 업로드 합니다.")
@PostMapping("/upload-pdf")
public ResponseEntity<String> uploadPdf(
@Parameter(description = "업로드할 pdf 파일",required = true)
Expand All @@ -52,9 +52,9 @@ public ResponseEntity<String> uploadPdf(
}


@Operation(summary = "pdf 업로드",description = "s3 스토리지에 pdf 파일을 업로드 합니다.")
@Operation(summary = "모든 인증서 삭제(지갑 삭제)",description = "모든 인증서를 삭제합니다. 즉,s3 스토리지에 pdf 파일을 모두 삭제합니다.")
@DeleteMapping("/delete-pdf")
public ResponseEntity<Void> deletePdf(
public ResponseEntity<Void> deleteWallet(
@Parameter(description = "지울 pdf 파일 경로 관련 Dto",required = true)
@RequestBody DeletePdfRequest request) {
String urlToDelete = request.getUrlToDelete();
Expand All @@ -63,6 +63,18 @@ public ResponseEntity<Void> deletePdf(
return ResponseEntity.noContent().build();
}

@Operation(summary = "특정 인증서 삭제",description = "지갑에서 특정 인증서를 삭제합니다. 즉,S3 스토리지에 pdf 파일에서 특정 페이지를 삭제합니다.")
@DeleteMapping("/delete-onepdf")
public ResponseEntity<Void> deleteCertForPage(
@Parameter(description = "지울 지갑 ID",required = true)
@RequestBody Long walletId,
@Parameter(description = "지울 페이지 번호",required = true)
@RequestBody int page) {
Wallet wallet = walletService.getWalletById(walletId).orElseThrow(()-> new EntityNotFoundException("Wallet does not exist"));
s3StorageService.deletePdfForPage(wallet,page);
return ResponseEntity.noContent().build();
}

@Operation(summary = "인증서 리스트 얻기",description = "개인의 인증서들을 모두 가져옵니다. 형식 : (페이지 - 설명)")
@GetMapping("/certs")
public ResponseEntity<HashMap<String,String>> getCertList(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Slf4j
@Service
Expand Down Expand Up @@ -69,7 +68,7 @@ public String uploadPdf(MultipartFile file, Wallet wallet,String pdfInfo,String
log.info("metadata = {}", metadata);

try {
uploadToS3(file, fileName, metadata, result);
uploadToS3(fileName, metadata, result);

} catch (S3Exception e) {
throw new IOException("Failed to upload pdf to S3: " + e.getMessage());
Expand All @@ -81,11 +80,11 @@ public String uploadPdf(MultipartFile file, Wallet wallet,String pdfInfo,String
return getpdfUrl(fileName);
}

private void uploadToS3(MultipartFile file, String fileName, HashMap<String, String> metadata, byte[] result) {
private void uploadToS3(String fileName, HashMap<String, String> metadata, byte[] result) {
PutObjectRequest putRequest = PutObjectRequest.builder()
.bucket(s3Properties.getS3BucketName())
.key(fileName)
.contentType(file.getContentType())
.contentType("application/pdf")
.metadata(metadata)
.build();

Expand Down Expand Up @@ -156,7 +155,7 @@ public String replacePdfPage(Wallet wallet, int pageNumberToRemove, MultipartFil

// 최종 PDF를 S3에 업로드
try {
uploadToS3(newPdfFile, fileName, metadata, finalPdfBytes);
uploadToS3(fileName, metadata, finalPdfBytes);
} catch (S3Exception e) {
throw new IOException("Failed to upload pdf to S3: " + e.getMessage());
} finally {
Expand Down Expand Up @@ -228,8 +227,6 @@ public HashMap<String, String> getCertList(String pdfUrl) {
return certList;
}



public HashMap<String, String> getPdfMetadata( String pdfUrl) {
HashMap<String, String> metadata;
String fileName = extractKeyFromUrl(pdfUrl);
Expand Down Expand Up @@ -318,11 +315,8 @@ private void validatePdfFile(String filename) {
}
}


//예외처리하기
public void deletePdf(String urlToDelete) {
String key = extractKeyFromUrl(urlToDelete);
System.out.println("key = " + key);
try {
s3Client.deleteObject(DeleteObjectRequest.builder()
.bucket(s3Properties.getS3BucketName())
Expand All @@ -333,6 +327,43 @@ public void deletePdf(String urlToDelete) {
}
}

public void deletePdfForPage(Wallet wallet, int pageNumberToRemove) throws IOException {
String pdfUrl = wallet.getPdfUrl();
byte[] originalPdfBytes = getPdf(pdfUrl).readAllBytes();
String fileName = extractKeyFromUrl(pdfUrl);

// 기존 PDF 로드
PDDocument originalDocument = PDDocument.load(new ByteArrayInputStream(originalPdfBytes));
int totalPages = originalDocument.getNumberOfPages();

// 페이지 번호는 0부터 시작하므로 1을 빼줌
int pageIndexToRemove = pageNumberToRemove - 1;

// 페이지가 존재하는지 확인
if (pageIndexToRemove < 0 || pageIndexToRemove >= totalPages) {
throw new IllegalArgumentException("Page number out of range: " + pageNumberToRemove);
}

byte[] frontPart = createPdfBytesPart(originalDocument, 0, pageIndexToRemove);
byte[] backPart = createPdfBytesPart(originalDocument, pageIndexToRemove + 1, originalDocument.getNumberOfPages());

// PDF 합치기
byte[] finalPdfBytes = mergePdfs(frontPart,backPart);
HashMap<String, String> metadata = getPdfMetadata(fileName);

//메타데이터 수정 로직 필요

// 최종 PDF를 S3에 업로드
try {
uploadToS3(fileName, metadata, finalPdfBytes);
} catch (S3Exception e) {
throw new IOException("Failed to upload pdf to S3: " + e.getMessage());
} finally {
originalDocument.close();
}

}

public ResponseInputStream<GetObjectResponse> getPdf(String pdfUrl) {
String key = extractKeyFromUrl(pdfUrl);
GetObjectRequest getObjectRequest = GetObjectRequest.builder()
Expand All @@ -341,6 +372,7 @@ public ResponseInputStream<GetObjectResponse> getPdf(String pdfUrl) {
.build();
return s3Client.getObject(getObjectRequest);
}

private String extractKeyFromUrl(String url) {
// Assuming the URL is in the format: https://s3.ap-northeast-2.amazonaws.com/bucketName/fileName
int index = url.lastIndexOf('/');
Expand Down

0 comments on commit a0b6582

Please sign in to comment.