Skip to content

Commit

Permalink
#21 Refactor : 새 인증서(pdf) 업로드 메서드 예외처리 언체크 예외로 변경
Browse files Browse the repository at this point in the history
  • Loading branch information
jinno321 committed Oct 6, 2024
1 parent cfa8fe9 commit c3b8c69
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 34 deletions.
Binary file not shown.
Original file line number Diff line number Diff line change
Expand Up @@ -44,13 +44,9 @@ public ResponseEntity<String> uploadPdf(
@Parameter(description = "pdf 키값",required = true)
@RequestParam String pdfKey) {
Wallet wallet = walletService.getWalletById(walletId).orElseThrow(()-> new EntityNotFoundException("Wallet does not exist"));
try {
String pdfUrl = s3StorageService.uploadPdf(file, wallet,pdfInfo,pdfKey);
return ResponseEntity.ok(pdfUrl);
} catch (IOException e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to upload pdf: " + e.getMessage());
}
String pdfUrl = s3StorageService.uploadPdf(file, wallet,pdfInfo,pdfKey);
return ResponseEntity.ok(pdfUrl);

}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,54 +36,75 @@ public S3StorageService(S3Properties s3Properties, WalletRepository walletReposi
this.walletRepository = walletRepository;
}

public String uploadPdf(MultipartFile file, Wallet wallet,String pdfInfo,String pdfKey) throws IOException {
@Transactional
public String uploadPdf(MultipartFile file, Wallet wallet, String pdfInfo, String pdfKey) {
String fileName;
byte[] result;
HashMap<String, String> metadata = new HashMap<>();
int nowPage = 1;

//첫 등록일때 => 생성해줘야함
if (wallet.getPdfUrl() == null){
fileName = (file.getSize() > 0) ? getFileName(wallet): getEmptyFilename(wallet);

// PDF 파일 확장자 검증
//validatePdfFile(fileName);
result = (file.getSize() > 0) ? file.getBytes():createEmptyPdf();

}
else{
//이미 있을시 -> pdf 병합
// 첫 등록일 때 => 생성해줘야 함
if (wallet.getPdfUrl() == null) {
fileName = (file.getSize() > 0) ? getFileName(wallet) : getEmptyFilename(wallet);
result = (file.getSize() > 0) ? getFileBytes(file) : createEmptyPdf();
} else {
// 이미 있을 시 -> PDF 병합
String destination = wallet.getPdfUrl();
fileName = extractKeyFromUrl(destination);

byte[] first = getPdf(destination).readAllBytes();//원래 파일
byte[] second = (file.getSize() > 0) ? file.getBytes() : createEmptyPdf(); //뒤에 들어온 파일
byte[] first = new byte[0]; // 원래 파일
first = getBytes(destination);
byte[] second = (file.getSize() > 0) ? getFileBytes(file) : createEmptyPdf(); // 뒤에 들어온 파일

nowPage = getPdfPageCount(first)+1;
nowPage = getPdfPageCount(first) + 1;
result = mergePdfs(first, second);

metadata= decodeMetadata(getPdfMetadata(fileName));
metadata = decodeMetadata(getPdfMetadata(fileName));
}

String page = "page-" + nowPage; // 키 설정
String value = pdfInfo + ":" + pdfKey;
metadata.put(page,value); // 키-값 쌍으로 추가
metadata.put(page, value); // 키-값 쌍으로 추가

log.info("metadata = {}", metadata);

try {
uploadToS3(fileName, metadata, result);

} catch (S3Exception e) {
throw new IOException("Failed to upload pdf to S3: " + e.getMessage());
}
uploadPdf(fileName, metadata, result);

wallet.updatePdfUrl(getpdfUrl(fileName));
walletRepository.saveAndFlush(wallet);

return getpdfUrl(fileName);
}



private byte[] getBytes(String destination) {
byte[] first;
try {
first = getPdf(destination).readAllBytes();
} catch (IOException e) {
throw new RuntimeException(e);
}
return first;
}

// 파일 바이트 배열을 가져오는 메서드 추가 (오류 처리 포함)
private byte[] getFileBytes(MultipartFile file) {
try {
return file.getBytes();
} catch (IOException e) {
throw new RuntimeException("Failed to get file bytes: " + e.getMessage(), e);
}
}

private void uploadPdf(String fileName, HashMap<String, String> metadata, byte[] result) {
try {
uploadToS3(fileName, metadata, result);
} catch (S3Exception e) {
throw new RuntimeException("Failed to upload pdf to S3: " + e.getMessage(), e);
}
}

private void uploadToS3(String fileName, HashMap<String, String> metadata, byte[] result) {

HashMap<String, String> encodedMetadata = new HashMap<>();
Expand All @@ -95,6 +116,7 @@ private void uploadToS3(String fileName, HashMap<String, String> metadata, byte[
PutObjectRequest putRequest = PutObjectRequest.builder()
.bucket(s3Properties.getS3BucketName())
.key(fileName)

.contentType("application/pdf")
.metadata(encodedMetadata)
.build();
Expand All @@ -111,7 +133,7 @@ private static String getEmptyFilename(Wallet wallet) {
return wallet.getAddress() + "_" + System.currentTimeMillis() + "_" + "empty.pdf";
}

public byte[] mergePdfs(byte[] pdf1, byte[] pdf2) throws IOException {
public byte[] mergePdfs(byte[] pdf1, byte[] pdf2){
PDFMergerUtility merger = new PDFMergerUtility();

ByteArrayInputStream inputStream1 = new ByteArrayInputStream(pdf1);
Expand All @@ -122,17 +144,23 @@ public byte[] mergePdfs(byte[] pdf1, byte[] pdf2) throws IOException {

ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
merger.setDestinationStream(outputStream);
merger.mergeDocuments(null);
try {
merger.mergeDocuments(null);
} catch (IOException e) {
throw new RuntimeException(e);
}

return outputStream.toByteArray();
}

private byte[] createEmptyPdf() throws IOException {
private byte[] createEmptyPdf(){
try (PDDocument document = new PDDocument()) {
document.addPage(new PDPage()); // 빈 페이지 추가
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
document.save(outputStream);
return outputStream.toByteArray();
} catch (IOException e) {
throw new RuntimeException(e);
}
}

Expand Down Expand Up @@ -316,9 +344,11 @@ public String getPdfKeyForPage(String pdfUrl, int pageNumber) {



public int getPdfPageCount(byte[] pdfBytes) throws IOException {
public int getPdfPageCount(byte[] pdfBytes){
try (PDDocument document = PDDocument.load(pdfBytes)) {
return document.getNumberOfPages();
} catch (IOException e) {
throw new RuntimeException(e);
}
}

Expand Down

0 comments on commit c3b8c69

Please sign in to comment.