Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: File 관련 코드 분리 #102

Merged
merged 5 commits into from
Mar 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,7 @@
import sunflower.server.util.FileUtil;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.UUID;

@Slf4j
@RequiredArgsConstructor
Expand All @@ -29,9 +26,9 @@ public class TranslationService {
@Transactional
public Long register(final MultipartFile file) {
final String originalFileName = file.getOriginalFilename();
final String fileName = UUID.randomUUID() + "_" + file.getOriginalFilename();
final String fileName = FileUtil.createRandomFileName(file);

final String pdfPath = FileUtil.savePdfFile(file, fileName);
final String pdfPath = FileUtil.saveFile(file, fileName, Paths.get("src", "main", "pdf"));
final Translations translations = translationsRepository.save(Translations.of(pdfPath, originalFileName));
log.info("Saved pdf File in Server. File URI: {}", pdfPath);

Expand All @@ -49,13 +46,8 @@ public TranslationStatusDto status(final Long id) {

public String findBrfFileById(final Long id) {
final Translations translations = translationsRepository.getById(id);
final String brfPath = translations.getBrfPath();
final File file = Paths.get(brfPath).toFile();

try {
return new String(Files.readAllBytes(Paths.get(file.getPath())));
} catch (IOException e) {
throw new RuntimeException(e);
}
final File file = FileUtil.findFile(translations.getBrfPath());

return FileUtil.readFile(file);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
Expand All @@ -12,12 +11,9 @@
import sunflower.server.client.BrailleTranslationClient;
import sunflower.server.entity.Translations;
import sunflower.server.repository.TranslationsRepository;
import sunflower.server.util.FileUtil;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import static org.springframework.transaction.annotation.Propagation.REQUIRES_NEW;
Expand All @@ -29,17 +25,14 @@ public class BrailleTranslateEventListener {

private TranslationsRepository translationsRepository;
private BrailleTranslationClient brailleTranslationClient;
private ApplicationEventPublisher eventPublisher;

@Autowired
public BrailleTranslateEventListener(
final TranslationsRepository translationsRepository,
final BrailleTranslationClient brailleTranslationClient,
final ApplicationEventPublisher eventPublisher
final BrailleTranslationClient brailleTranslationClient
) {
this.translationsRepository = translationsRepository;
this.brailleTranslationClient = brailleTranslationClient;
this.eventPublisher = eventPublisher;
}

@Async
Expand All @@ -48,42 +41,15 @@ public BrailleTranslateEventListener(
public void downloadLatexFile(final BrailleTranslateEvent event) {
final Translations translations = translationsRepository.getById(event.getId());

final String latexPath = translations.getLatexPath();
final File latexFile = Paths.get(latexPath).toFile();
final File latexFile = FileUtil.findFile(translations.getLatexPath());

if (!latexFile.exists()) {
throw new RuntimeException("파일이 존재하지 않습니다!");
}

final String brfContent = brailleTranslationClient.translate(latexFile);
final String brfPath = saveBrfFile(brfContent, translations.getOcrPdfId());
final String brfPath = FileUtil.saveFile(brfContent, translations.getOcrPdfId(), Paths.get("src", "main", "brf"));

translations.finishTransbraille(brfPath);
}

private String saveBrfFile(final String content, final String ocrPdfId) {
final Path directoryPath = Paths.get("src", "main", "brf");
if (!Files.exists(directoryPath)) {
try {
Files.createDirectories(directoryPath);
} catch (IOException e) {
throw new RuntimeException("Unable to create directory: " + directoryPath, e);
}
}

final String directory = "src/main/brf";
final String fileName = ocrPdfId + ".brf";
final Path brfPath = Paths.get(directory, fileName);

final File file = brfPath.toFile();
try {
final FileWriter writer = new FileWriter(file);
writer.write(content);
writer.close();
} catch (IOException e) {
throw new RuntimeException(e);
}

return brfPath.toString();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,11 @@
import sunflower.server.client.OcrDownloadClient;
import sunflower.server.entity.Translations;
import sunflower.server.repository.TranslationsRepository;
import sunflower.server.util.FileUtil;

import java.nio.file.Paths;

import static org.springframework.transaction.annotation.Propagation.REQUIRES_NEW;
import static sunflower.server.util.FileUtil.saveLatexFile;

@Slf4j
@NoArgsConstructor
Expand Down Expand Up @@ -45,7 +47,7 @@ public void downloadLatexFile(final OcrDownloadEvent event) {
final String pdfId = translations.getOcrPdfId();

final byte[] latex = ocrDownloadClient.download(pdfId);
final String latexPath = saveLatexFile(pdfId, latex);
final String latexPath = FileUtil.saveFile(latex, pdfId, Paths.get("src", "main", "latex"));
log.info("Latex File 저장! 경로: {}", latexPath);
translations.registerLatexPath(latexPath);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@
import sunflower.server.client.OcrRegisterClient;
import sunflower.server.entity.Translations;
import sunflower.server.repository.TranslationsRepository;
import sunflower.server.util.FileUtil;

import java.io.File;
import java.nio.file.Paths;

import static org.springframework.transaction.annotation.Propagation.REQUIRES_NEW;

Expand Down Expand Up @@ -47,8 +47,7 @@ public void registerOcr(final OcrRegisterEvent event) {

final Long id = event.getTranslations().getId();
final Translations translations = translationsRepository.getById(id);
final String pdfPath = translations.getPdfPath();
final File file = Paths.get(pdfPath).toFile();
final File file = FileUtil.findFile(translations.getPdfPath());

translations.startOcr();
final String pdfId = ocrRegisterClient.requestPdfId(file);
Expand Down
86 changes: 53 additions & 33 deletions server/src/main/java/sunflower/server/util/FileUtil.java
Original file line number Diff line number Diff line change
@@ -1,24 +1,23 @@
package sunflower.server.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

@Slf4j
public final class FileUtil {

public static String savePdfFile(final MultipartFile file, String fileName) {
final Path directoryPath = Paths.get("src", "main", "pdf");
public static String saveFile(Object file, String fileName, Path directoryPath) {
if (!Files.exists(directoryPath)) {
try {
Files.createDirectories(directoryPath);
Expand All @@ -27,50 +26,71 @@ public static String savePdfFile(final MultipartFile file, String fileName) {
}
}

final Path path = Paths.get("src", "main", "pdf", fileName);
Path path;
if (file instanceof MultipartFile) {
path = saveMultipartFile((MultipartFile) file, fileName, directoryPath);
} else if (file instanceof String) {
path = saveStringContent((String) file, fileName, directoryPath);
} else if (file instanceof byte[]) {
path = saveZipFile((byte[]) file, fileName, directoryPath);
} else {
throw new IllegalArgumentException("Unsupported file type");
}

return path.toString();
}

private static Path saveMultipartFile(MultipartFile file, String fileName, Path directoryPath) {
try {
Files.copy(file.getInputStream(), path);
Resource resource = new FileSystemResource(path.toFile());
return resource.getFile().getPath();
Path filePath = Paths.get(directoryPath.toString(), fileName);
Files.copy(file.getInputStream(), filePath);
return filePath;
} catch (IOException e) {
throw new RuntimeException(e);
}
}

public static FileSystemResource convertToFileSystemResource(final MultipartFile file) {
return (FileSystemResource) file.getResource();
}

public static FileSystemResource convertToFileSystemResource(final File file) {
return new FileSystemResource(file);
private static Path saveStringContent(String content, String fileName, Path directoryPath) {
Path filePath = Paths.get(directoryPath.toString(), fileName);
try (FileWriter writer = new FileWriter(filePath.toFile())) {
writer.write(content);
return filePath;
} catch (IOException e) {
throw new RuntimeException(e);
}
}

public static String saveLatexFile(final String pdfId, byte[] content) {
final Path directoryPath = Paths.get("src", "main", "latex");
if (!Files.exists(directoryPath)) {
try {
Files.createDirectories(directoryPath);
} catch (IOException e) {
throw new RuntimeException("Unable to create directory: " + directoryPath, e);
private static Path saveZipFile(byte[] content, String fileName, Path directoryPath) {
try {
String path = "src/main/latex/" + fileName + ".tex";
try (ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(content))) {
ZipEntry entry;
while ((entry = zipInputStream.getNextEntry()) != null) {
if (!entry.isDirectory()) {
Files.copy(zipInputStream, Paths.get(path));
break;
}
}
}
return Paths.get(path);
} catch (IOException e) {
throw new RuntimeException(e);
}
}

public static String createRandomFileName(final MultipartFile file) {
return UUID.randomUUID() + "_" + file.getOriginalFilename();
}

String path = "src/main/latex/" + pdfId + ".tex";
public static File findFile(String path) {
return Paths.get(path).toFile();
}

try (ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(content))) {
ZipEntry entry;
while ((entry = zipInputStream.getNextEntry()) != null) {
if (!entry.isDirectory()) {
Files.copy(zipInputStream, Paths.get(path));
break;
}
}
public static String readFile(final File file) {
try {
return new String(Files.readAllBytes(Paths.get(file.getPath())));
} catch (IOException e) {
log.error("Error extracting file from zip: {}", e.getMessage());
throw new RuntimeException(e);
}

return path;
}
}