261104_04_HOT: 엑셀파일 생성 시 스트리밍 방식으로 생성
This commit is contained in:
@@ -14,6 +14,9 @@ import io.swagger.v3.oas.annotations.media.Content;
|
|||||||
import io.swagger.v3.oas.annotations.media.Schema;
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||||
import jakarta.validation.Valid;
|
import jakarta.validation.Valid;
|
||||||
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.Files;
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||||
@@ -93,13 +96,28 @@ public class ExportController {
|
|||||||
@PostMapping(
|
@PostMapping(
|
||||||
value = "/project/{projectType}/{pkey}/export/data",
|
value = "/project/{projectType}/{pkey}/export/data",
|
||||||
produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
|
produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
|
||||||
public ResponseEntity<byte[]> data(
|
public void data(
|
||||||
@PathVariable ProjectType projectType,
|
@PathVariable ProjectType projectType,
|
||||||
@PathVariable String pkey,
|
@PathVariable String pkey,
|
||||||
@Valid @RequestBody RawDataExportRequestDto request,
|
@Valid @RequestBody RawDataExportRequestDto request,
|
||||||
@Parameter(hidden = true) RequestUserContext ctx) {
|
@Parameter(hidden = true) RequestUserContext ctx, HttpServletResponse response) throws IOException {
|
||||||
return download(
|
ProjectRefDto project = new ProjectRefDto(projectType, pkey);
|
||||||
exportService.data(new ProjectRefDto(projectType, pkey), ctx.getUserRole(), request));
|
try (var file = exportService.prepareData(project, ctx.getUserRole(), request)) {
|
||||||
|
String fileName = FileUtil.extractFileNameFromPath(file.fileName())
|
||||||
|
.replaceAll("[\\p{Cntrl}\\\\/:*?\"<>|]", "_");
|
||||||
|
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
|
||||||
|
response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
|
||||||
|
ContentDisposition.attachment().filename(fileName, StandardCharsets.UTF_8).build().toString());
|
||||||
|
response.setHeader(HttpHeaders.CACHE_CONTROL, "no-store");
|
||||||
|
response.setContentLengthLong(Files.size(file.path()));
|
||||||
|
Files.copy(file.path(), response.getOutputStream());
|
||||||
|
} catch (IOException | RuntimeException error) {
|
||||||
|
// Before any file bytes are committed, preserve the normal JSON error response.
|
||||||
|
if (!response.isCommitted()) {
|
||||||
|
response.reset();
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private ResponseEntity<byte[]> download(ExportFileDto file) {
|
private ResponseEntity<byte[]> download(ExportFileDto file) {
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
package com.kri.kart.server.dto.export;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
|
||||||
|
/** Completed download file owned by the caller until close. */
|
||||||
|
public record ExportTempFileDto(String fileName, Path path) implements AutoCloseable {
|
||||||
|
@Override
|
||||||
|
public void close() throws IOException {
|
||||||
|
Files.deleteIfExists(path);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,6 +7,7 @@ import com.kri.kart.server.dto.export.ExportTitleDto;
|
|||||||
import java.time.LocalDate;
|
import java.time.LocalDate;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import org.apache.ibatis.annotations.Param;
|
import org.apache.ibatis.annotations.Param;
|
||||||
|
import org.apache.ibatis.session.ResultHandler;
|
||||||
|
|
||||||
public interface ExportMapper {
|
public interface ExportMapper {
|
||||||
String additionalColumns(@Param("pkey") String pkey);
|
String additionalColumns(@Param("pkey") String pkey);
|
||||||
@@ -19,10 +20,11 @@ public interface ExportMapper {
|
|||||||
|
|
||||||
String surveyType(@Param("pkey") String pkey);
|
String surveyType(@Param("pkey") String pkey);
|
||||||
|
|
||||||
List<ExportDataDto> data(
|
void data(
|
||||||
@Param("pkey") String pkey,
|
@Param("pkey") String pkey,
|
||||||
@Param("type") String type,
|
@Param("type") String type,
|
||||||
@Param("startDate") LocalDate startDate,
|
@Param("startDate") LocalDate startDate,
|
||||||
@Param("endDate") LocalDate endDate,
|
@Param("endDate") LocalDate endDate,
|
||||||
@Param("includeInterviewer") Boolean includeInterviewer);
|
@Param("includeInterviewer") Boolean includeInterviewer,
|
||||||
|
ResultHandler<ExportDataDto> handler);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import com.kri.kart.server.dto.project.ProjectRefDto;
|
|||||||
import com.kri.kart.server.persistence.SurveySessionProvider;
|
import com.kri.kart.server.persistence.SurveySessionProvider;
|
||||||
import com.kri.kart.server.persistence.mapper.ExportMapper;
|
import com.kri.kart.server.persistence.mapper.ExportMapper;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.function.Consumer;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||||
import org.springframework.stereotype.Repository;
|
import org.springframework.stereotype.Repository;
|
||||||
@@ -42,14 +43,14 @@ public class ExportRepository {
|
|||||||
return surveySessionProvider.mapper(project, ExportMapper.class).surveyType(project.pkey());
|
return surveySessionProvider.mapper(project, ExportMapper.class).surveyType(project.pkey());
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<ExportDataDto> data(
|
public void data(
|
||||||
ProjectRefDto project, RawDataExportRequestDto request, boolean includeInterviewer) {
|
ProjectRefDto project, RawDataExportRequestDto request, boolean includeInterviewer, Consumer<ExportDataDto> consumer) {
|
||||||
return surveySessionProvider.mapper(project, ExportMapper.class)
|
surveySessionProvider.mapper(project, ExportMapper.class)
|
||||||
.data(
|
.data(
|
||||||
project.pkey(),
|
project.pkey(),
|
||||||
request.getType(),
|
request.getType(),
|
||||||
request.getStartDate(),
|
request.getStartDate(),
|
||||||
request.getEndDate() == null ? request.getStartDate() : request.getEndDate(),
|
request.getEndDate() == null ? request.getStartDate() : request.getEndDate(),
|
||||||
includeInterviewer);
|
includeInterviewer, context -> consumer.accept(context.getResultObject()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import com.kri.kart.server.common.consts.KartConstant;
|
|||||||
import com.kri.kart.server.dto.export.ExportDataDto;
|
import com.kri.kart.server.dto.export.ExportDataDto;
|
||||||
import com.kri.kart.server.dto.export.ExportDerivedHeaderDto;
|
import com.kri.kart.server.dto.export.ExportDerivedHeaderDto;
|
||||||
import com.kri.kart.server.dto.export.ExportFileDto;
|
import com.kri.kart.server.dto.export.ExportFileDto;
|
||||||
|
import com.kri.kart.server.dto.export.ExportTempFileDto;
|
||||||
import com.kri.kart.server.dto.export.ExportGuideDto;
|
import com.kri.kart.server.dto.export.ExportGuideDto;
|
||||||
import com.kri.kart.server.dto.export.ExportHeaderDto;
|
import com.kri.kart.server.dto.export.ExportHeaderDto;
|
||||||
import com.kri.kart.server.dto.export.ExportTitleDto;
|
import com.kri.kart.server.dto.export.ExportTitleDto;
|
||||||
@@ -20,6 +21,7 @@ import com.kri.kart.server.persistence.repository.ExportRepository;
|
|||||||
import com.kri.kart.server.persistence.repository.QuestionRepository;
|
import com.kri.kart.server.persistence.repository.QuestionRepository;
|
||||||
import java.io.ByteArrayOutputStream;
|
import java.io.ByteArrayOutputStream;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
import java.io.OutputStream;
|
||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
import java.time.format.DateTimeFormatter;
|
import java.time.format.DateTimeFormatter;
|
||||||
@@ -128,8 +130,26 @@ public class ExportService {
|
|||||||
return rows;
|
return rows;
|
||||||
}
|
}
|
||||||
|
|
||||||
public ExportFileDto data(
|
public ExportTempFileDto prepareData(
|
||||||
ProjectRefDto project, Integer userRole, RawDataExportRequestDto request) {
|
ProjectRefDto project, Integer userRole, RawDataExportRequestDto request) throws IOException {
|
||||||
|
Path path = Files.createTempFile("kart-data-export-", ".xlsx");
|
||||||
|
try {
|
||||||
|
try (OutputStream output = Files.newOutputStream(path)) {
|
||||||
|
data(project, userRole, request, output);
|
||||||
|
}
|
||||||
|
return new ExportTempFileDto(dataFileName(project), path);
|
||||||
|
} catch (IOException | RuntimeException | Error error) {
|
||||||
|
try {
|
||||||
|
Files.deleteIfExists(path);
|
||||||
|
} catch (IOException cleanupError) {
|
||||||
|
error.addSuppressed(cleanupError);
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void data(
|
||||||
|
ProjectRefDto project, Integer userRole, RawDataExportRequestDto request, OutputStream output) throws IOException {
|
||||||
if (!List.of("COMPLETE", "INCOMPLETE").contains(Objects.toString(request.getType(), ""))
|
if (!List.of("COMPLETE", "INCOMPLETE").contains(Objects.toString(request.getType(), ""))
|
||||||
|| (request.getStartDate() == null && request.getEndDate() != null)
|
|| (request.getStartDate() == null && request.getEndDate() != null)
|
||||||
|| (request.getStartDate() != null
|
|| (request.getStartDate() != null
|
||||||
@@ -138,36 +158,48 @@ public class ExportService {
|
|||||||
throw BusinessException.badRequest("다운로드 유형과 날짜 범위를 확인해 주세요.");
|
throw BusinessException.badRequest("다운로드 유형과 날짜 범위를 확인해 주세요.");
|
||||||
}
|
}
|
||||||
Map<String, String> headers = headers(project, userRole);
|
Map<String, String> headers = headers(project, userRole);
|
||||||
List<Map<String, String>> rows = new ArrayList<>();
|
|
||||||
rows.add(headers); // Row 1 contains storage keys, row 2 contains variable aliases.
|
|
||||||
boolean includeInterviewer = "2".equals(exportRepository.surveyType(project));
|
boolean includeInterviewer = "2".equals(exportRepository.surveyType(project));
|
||||||
for (ExportDataDto response : exportRepository.data(project, request, includeInterviewer)) {
|
try (var workbook = ExcelMapper.createStreamingWorkbook(100)) {
|
||||||
|
try (var writer = ExcelMapper.openStreamingMapWriter(workbook, new ArrayList<>(headers.keySet()), "DATA", 1)) {
|
||||||
|
writer.append(headers);
|
||||||
|
exportRepository.data(project, request, includeInterviewer, response -> {
|
||||||
String dat = response.getDat();
|
String dat = response.getDat();
|
||||||
if (dat == null || dat.isEmpty()) {
|
if (dat == null || dat.isEmpty()) {
|
||||||
continue; // SQL STUFF returns NULL when all response groups are empty.
|
return;
|
||||||
}
|
}
|
||||||
// Preserve legacy ReplaceUnicodeEmpty after SQL UPPER/FOR XML serialization.
|
|
||||||
JsonNode values = jsonObject(dat.replaceAll("\\\\U\\d*", ""));
|
JsonNode values = jsonObject(dat.replaceAll("\\\\U\\d*", ""));
|
||||||
Map<String, String> row = new LinkedHashMap<>();
|
Map<String, String> row = new LinkedHashMap<>();
|
||||||
for (String key : headers.keySet()) {
|
for (String key : headers.keySet()) {
|
||||||
row.put(key, responseValue(response, values, key, includeInterviewer));
|
String value = responseValue(response, values, key, includeInterviewer);
|
||||||
|
if (value != null && !value.isEmpty()) {
|
||||||
|
row.put(key, value);
|
||||||
}
|
}
|
||||||
rows.add(row);
|
|
||||||
}
|
}
|
||||||
Workbook workbook = ExcelMapper.writeFromMapList(rows, "DATA");
|
writer.append(row);
|
||||||
try {
|
});
|
||||||
ExcelMapper.appendSheetToWorkbook(
|
|
||||||
workbook, guideRows(project), ExportGuideDto.class, "GUIDE", 1);
|
|
||||||
return file("DATA", project, workbook);
|
|
||||||
} catch (RuntimeException exception) {
|
|
||||||
try {
|
|
||||||
workbook.close();
|
|
||||||
} catch (IOException closeException) {
|
|
||||||
exception.addSuppressed(closeException);
|
|
||||||
}
|
}
|
||||||
throw exception;
|
// Metadata is bounded by the questionnaire; respondent rows are never accumulated.
|
||||||
|
try (var writer = ExcelMapper.openStreamingMapWriter(workbook,
|
||||||
|
List.of("문항 타입", "문항 / 보기번호", "내용", "VALUE LABEL", "VARIABLE LABEL"), "GUIDE", 1)) {
|
||||||
|
for (ExportGuideDto guide : guideRows(project)) {
|
||||||
|
Map<String, String> row = new LinkedHashMap<>();
|
||||||
|
row.put("문항 타입", guide.questionType());
|
||||||
|
row.put("문항 / 보기번호", guide.variable());
|
||||||
|
row.put("내용", guide.content());
|
||||||
|
row.put("VALUE LABEL", guide.valueLabel());
|
||||||
|
row.put("VARIABLE LABEL", guide.variableLabel());
|
||||||
|
row.values().removeIf(value -> value == null || value.isEmpty());
|
||||||
|
writer.append(row);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
workbook.write(output);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public String dataFileName(ProjectRefDto project) {
|
||||||
|
return "[DATA]" + project.pkey() + "_"
|
||||||
|
+ DateTimeUtil.nowKstLocalDateTime().format(FILE_TIMESTAMP) + ".xlsx";
|
||||||
|
}
|
||||||
|
|
||||||
private String responseValue(
|
private String responseValue(
|
||||||
ExportDataDto response, JsonNode values, String key, boolean includeInterviewer) {
|
ExportDataDto response, JsonNode values, String key, boolean includeInterviewer) {
|
||||||
|
|||||||
@@ -41,7 +41,7 @@
|
|||||||
<select id="surveyType" databaseId="survey" resultType="string">
|
<select id="surveyType" databaseId="survey" resultType="string">
|
||||||
SELECT JSON_VALUE(PROJECTJSON, '$.must.surveytype') FROM PROJECT WHERE PKEY = #{pkey}
|
SELECT JSON_VALUE(PROJECTJSON, '$.must.surveytype') FROM PROJECT WHERE PKEY = #{pkey}
|
||||||
</select>
|
</select>
|
||||||
<select id="data" databaseId="survey" resultType="com.kri.kart.server.dto.export.ExportDataDto">
|
<select id="data" databaseId="survey" resultSetType="FORWARD_ONLY" fetchSize="100" useCache="false" resultType="com.kri.kart.server.dto.export.ExportDataDto">
|
||||||
<![CDATA[
|
<![CDATA[
|
||||||
SELECT IA.Status, DAT.DAT, DAT.start_date, DAT.end_date, DAT.interval_min
|
SELECT IA.Status, DAT.DAT, DAT.start_date, DAT.end_date, DAT.interval_min
|
||||||
]]>
|
]]>
|
||||||
|
|||||||
Reference in New Issue
Block a user