first commit

This commit is contained in:
2025-12-09 11:54:11 +09:00
commit f1ae6e3cb8
43 changed files with 1923 additions and 0 deletions

View File

@@ -0,0 +1,19 @@
package com.krt.flower.Flower;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.filter.HiddenHttpMethodFilter;
@SpringBootApplication
public class FlowerApplication {
public static void main(String[] args) {
SpringApplication.run(FlowerApplication.class, args);
}
@Bean
public HiddenHttpMethodFilter hiddenHttpMethodFilter() {
return new HiddenHttpMethodFilter();
}
}

View File

@@ -0,0 +1,27 @@
package com.krt.flower.Flower.Interceptor;
import com.krt.flower.Flower.service.IpAccessControlService;
import com.krt.flower.Flower.util.IpUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
@RequiredArgsConstructor
@Component
public class IpAccessControlInterceptor implements HandlerInterceptor {
private final IpAccessControlService ipAccessControlService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String clientIpAddress = IpUtil.getClientIp(request); // 추가
if (!ipAccessControlService.isAccessible(clientIpAddress)) {
String requestURI = request.getRequestURI();
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return false;
}
return true;
}
}

View File

@@ -0,0 +1,20 @@
package com.krt.flower.Flower.config;
import com.querydsl.jpa.impl.JPAQueryFactory;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
@EnableJpaAuditing
@Configuration
public class QueryDslConfig {
@PersistenceContext
private EntityManager entityManager;
@Bean
public JPAQueryFactory jpaQueryFactory() {
return new JPAQueryFactory(this.entityManager);
}
}

View File

@@ -0,0 +1,37 @@
package com.krt.flower.Flower.config;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.annotation.web.configurers.HttpBasicConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.ignoring().requestMatchers("/v2/api-docs", "/configuration/ui",
"/swagger-resources/**", "/configuration/security",
"/webjars/**","/swagger/**", "/");
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.httpBasic(HttpBasicConfigurer::disable)
.csrf(AbstractHttpConfigurer::disable)
.cors(Customizer.withDefaults())
.sessionManagement((sessionManagement) ->
sessionManagement.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
);
return http.build();
}
}

View File

@@ -0,0 +1,26 @@
package com.krt.flower.Flower.config;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.servers.Server;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class SwaggerConfig {
@Bean
public OpenAPI newSsakOpenAPI() {
Info info = new Info()
.version("v1.0.0")
.title("새싹 꽃님 API")
.description("새싹 파일 입출력 관련 API");
/*
Components components = new Components();
*/
return new OpenAPI()
.info(info)
.addServersItem(new Server().url("/"));
//.components(components);
}
}

View File

@@ -0,0 +1,34 @@
package com.krt.flower.Flower.config;
import com.krt.flower.Flower.Interceptor.IpAccessControlInterceptor;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@EnableWebMvc
@RequiredArgsConstructor
public class WebConfig implements WebMvcConfigurer {
private final IpAccessControlInterceptor ipAccessControlInterceptor;
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOriginPatterns("*")
.allowedMethods("*")
.allowedHeaders("*")
.allowCredentials(true)
.maxAge(3000);
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(ipAccessControlInterceptor)
.order(1)
.addPathPatterns("/swagger-ui/**", "/v3/api-docs/**");
}
}

View File

@@ -0,0 +1,233 @@
package com.krt.flower.Flower.controller;
import com.krt.flower.Flower.dto.SurveyUploadInfoDto;
import com.krt.flower.Flower.service.FileService;
import com.krt.flower.Flower.util.Common;
import com.krt.flower.Flower.util.SecurityUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.NoArgsConstructor;
import lombok.RequiredArgsConstructor;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.format.DateTimeFormatter;
import java.util.List;
@Tag(name = "Files", description = "파일 관련 API")
@RestController
@RequestMapping("api/v1/files")
@RequiredArgsConstructor
public class FileController {
private final FileService fileService;
@Operation(summary = "로고 파일 가져 오기")
@GetMapping("/logo/{filename}")
public ResponseEntity<Resource> getLogo(
@PathVariable(name = "filename") String filename
, @RequestParam(name = "sc", defaultValue = "") String security_code
) throws Exception {
String logoPath = "";
if(!security_code.isEmpty()){
String projectCode = "";
try{
projectCode = SecurityUtil.decrypt(URLDecoder.decode(security_code, StandardCharsets.UTF_8));
}catch (Exception ex){
projectCode = SecurityUtil.decrypt(security_code);
}
logoPath += projectCode + "/";
}
logoPath += filename;
Resource resource = new UrlResource(fileService.getLogoPath(logoPath).toUri());
if (resource.exists()) {
return ResponseEntity.ok().body(resource);
} else {
return ResponseEntity.notFound().build();
}
}
@Operation(summary = "로고 파일 저장")
@PostMapping(value = "/projectLogoUpload", consumes = { MediaType.APPLICATION_JSON_VALUE, MediaType.MULTIPART_FORM_DATA_VALUE })
public ResponseEntity<?> projectFilesUpload(
@RequestPart(value = "project_code") String projectCode,
@RequestPart(value = "upload_file", required = false) List<MultipartFile> multipartFileList
) throws Exception {
int result = fileService.saveProjectLogoFiles(projectCode, multipartFileList);
return ResponseEntity.ok(result);
}
@Operation(summary = "프로젝트에서 사용할 파일 가져 오기")
@GetMapping("/file/{filename}")
public ResponseEntity<?> getProjectFile(
@PathVariable(name = "filename") String filename,
@RequestParam(name = "sc") String security_code
) throws Exception {
String projectCode = "";
try{
projectCode = SecurityUtil.decrypt(URLDecoder.decode(security_code, StandardCharsets.UTF_8));
}catch (Exception ex){
projectCode = SecurityUtil.decrypt(security_code);
}
//String projectCode = SecurityUtil.decrypt(security_code);
Resource resource = new UrlResource(fileService.getProjectFilePath(projectCode, filename).toUri());
if (resource.exists()) {
MediaType mediaType = MediaType.parseMediaType(Common.getMediaType(resource));
if(filename.toLowerCase().contains("pdf")){
mediaType = MediaType.APPLICATION_PDF;
}
//String encodedFilename = URLEncoder.encode(filename, StandardCharsets.UTF_8).replaceAll("\\+", "%20");
return ResponseEntity.ok()
.header("Content-Disposition", "inline; filename*=UTF-8\"" + filename + "\"")
.contentType(mediaType)
.body(resource);
} else {
return ResponseEntity.notFound().build();
}
}
@Operation(summary="프로젝트에서 사용할 파일 리스트")
@GetMapping(value = "/projectFiles")
public ResponseEntity<?> getProjectFileList(@RequestParam(name = "sc") String security_code) throws Exception{
String projectCode = "";
try{
projectCode = SecurityUtil.decrypt(URLDecoder.decode(security_code, StandardCharsets.UTF_8));
}catch (Exception ex){
projectCode = SecurityUtil.decrypt(security_code);
}
List<String> fileUrls = fileService.getProjectFileList(projectCode, URLEncoder.encode(security_code, StandardCharsets.UTF_8));
return ResponseEntity.ok(fileUrls);
}
@Operation(summary = "프로젝트에서 사용할 파일 업로드")
@PostMapping(value = "/projectFilesUpload", consumes = { MediaType.APPLICATION_JSON_VALUE, MediaType.MULTIPART_FORM_DATA_VALUE })
public ResponseEntity<?> projectFilesUpload(
@RequestPart(value = "security_code") String security_code,
@RequestPart(value = "member_code") String string_member_code,
@RequestPart(value = "upload_file", required = false) List<MultipartFile> multipartFiles
) throws Exception {
String projectCode = "";
try{
projectCode = SecurityUtil.decrypt(URLDecoder.decode(security_code, StandardCharsets.UTF_8));
}catch (Exception ex){
projectCode = SecurityUtil.decrypt(security_code);
}
int memberCode = Integer.parseInt(string_member_code);
int result = fileService.saveProjectFiles(projectCode, memberCode, multipartFiles);
return ResponseEntity.ok(result);
}
@Operation(summary = "프로젝트에서 사용하는 파일 모두 제거")
@PostMapping(value = "projectFilesEmpty", consumes = { MediaType.APPLICATION_JSON_VALUE, MediaType.MULTIPART_FORM_DATA_VALUE })
public ResponseEntity<?> projectFileAllDelete(
@RequestPart(value = "security_code") String security_code,
@RequestPart(value = "member_code") String string_member_code
) throws Exception {
String projectCode = "";
try{
projectCode = SecurityUtil.decrypt(URLDecoder.decode(security_code, StandardCharsets.UTF_8));
}catch (Exception ex){
projectCode = SecurityUtil.decrypt(security_code);
}
int memberCode = Integer.parseInt(string_member_code);
int result = fileService.deleteAllFiles(projectCode, memberCode);
return ResponseEntity.ok(result);
}
@Operation(summary = "설문 파일 업로드 저장")
@PostMapping(value = "/fileUpload", consumes = { MediaType.APPLICATION_JSON_VALUE, MediaType.MULTIPART_FORM_DATA_VALUE })
public ResponseEntity<?> fileUpload(
@RequestPart(value = "upload_info") SurveyUploadInfoDto uploadInfoDto,
@RequestPart(value = "upload_file", required = false) List<MultipartFile> multipartFiles
) throws Exception {
int result = fileService.saveSurveyFiles(uploadInfoDto, multipartFiles);
return ResponseEntity.ok(result);
}
@Operation(summary = "설문 응답 파일 가져 오기")
@GetMapping("/upload/{ans_id}/{question_unique_key}/{loop_id}/{filename}")
public ResponseEntity<?> getUploadFile(
@PathVariable(name = "ans_id") String ans_id,
@PathVariable(name = "question_unique_key") String question_unique_key,
@PathVariable(name = "loop_id") String loop_id,
@PathVariable(name = "filename") String filename,
@RequestParam(name = "sc") String security_code
) throws Exception {
String projectCode = "";
try{
projectCode = SecurityUtil.decrypt(URLDecoder.decode(security_code, StandardCharsets.UTF_8));
}catch (Exception ex){
projectCode = SecurityUtil.decrypt(security_code);
}
//String projectCode = SecurityUtil.decrypt(security_code);
Resource resource = new UrlResource(fileService.getUploadFilePath(projectCode, ans_id, question_unique_key, loop_id, filename).toUri());
if (resource.exists()) {
MediaType mediaType = MediaType.parseMediaType(Common.getMediaType(resource));
if(filename.toLowerCase().contains("pdf")){
mediaType = MediaType.APPLICATION_PDF;
}
//String encodedFilename = URLEncoder.encode(filename, StandardCharsets.UTF_8).replaceAll("\\+", "%20");
return ResponseEntity.ok()
.header("Content-Disposition", "inline; filename*=UTF-8\"" + filename + "\"")
.contentType(mediaType)
.body(resource);
} else {
return ResponseEntity.notFound().build();
}
}
@Operation(summary = "설문 응답 파일 ZIP 다운로드")
@GetMapping("/download")
public ResponseEntity<?> getUploadFile(@RequestParam(name = "sc") String security_code, @RequestParam(name = "md") String download_mode) throws Exception {
String projectCode = "";
try{
projectCode = SecurityUtil.decrypt(URLDecoder.decode(security_code, StandardCharsets.UTF_8));
}catch (Exception ex){
projectCode = SecurityUtil.decrypt(security_code);
}
boolean isComplete = true;
boolean isTest = false;
switch (download_mode.toLowerCase()){
case "not":
isComplete = false;
break;
case "test":
isTest = true;
break;
}
String zipFilename = "[File] " + projectCode + "_" + Common.getNow(DateTimeFormatter.ofPattern("yyyy-MM-dd_HHmmss"))+".zip";
byte[] zipFile = fileService.getSurveyFilesZip(projectCode, "", isComplete, isTest);
ByteArrayResource resource = new ByteArrayResource(zipFile);
if (resource.exists()) {
MediaType mediaType = MediaType.parseMediaType("application/zip");
//String encodedFilename = URLEncoder.encode(filename, StandardCharsets.UTF_8).replaceAll("\\+", "%20");
return ResponseEntity.ok()
.header("Content-Disposition", "attachment; filename=\"" + zipFilename + "\"")
.contentType(mediaType)
.contentLength(zipFile.length)
.body(resource);
} else {
return ResponseEntity.notFound().build();
}
}
}

View File

@@ -0,0 +1,13 @@
package com.krt.flower.Flower.dto;
import lombok.*;
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class FileStructureDto {
private String directoryName;
private String fileName;
}

View File

@@ -0,0 +1,17 @@
package com.krt.flower.Flower.dto;
import lombok.*;
@Getter
@Setter
@Builder
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class SurveyDataStructureDto {
private int t;
private int m;
private int s;
private int r;
private String o;
}

View File

@@ -0,0 +1,15 @@
package com.krt.flower.Flower.dto;
import lombok.*;
@Getter @Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class SurveyUploadFileDto {
private String ansId;
private String questionID;
private int questionUniqueKey;
private int loopId;
private String ansData;
}

View File

@@ -0,0 +1,13 @@
package com.krt.flower.Flower.dto;
import lombok.*;
@Getter @Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class SurveyUploadInfoDto {
private String security_code;
private String answer_id;
//private List<UploadFileDto> uploadFiles;
}

View File

@@ -0,0 +1,12 @@
package com.krt.flower.Flower.dto;
import lombok.*;
@Getter @Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class UploadFileDto {
private String originalName;
private String newName;
}

View File

@@ -0,0 +1,14 @@
package com.krt.flower.Flower.dto;
import lombok.*;
import java.nio.file.Path;
@Getter @Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ZipFileDto {
Path filePath;
String outputPath;
}

View File

@@ -0,0 +1,42 @@
package com.krt.flower.Flower.entity;
import com.krt.flower.Flower.entity_pk.ProjectFileEntityPK;
import com.krt.flower.Flower.util.Common;
import jakarta.persistence.*;
import lombok.*;
@Entity
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@IdClass(ProjectFileEntityPK.class)
@Table(name = "project_file")
public class ProjectFileEntity {
@Column(name = "IDX", insertable = false, updatable = false)
private long idx;
@Id
@Column(name = "PRJ_CD")
private String projectCode;
@Id
@Column(name = "NM")
private String fileName;
@Column(name = "REG_MBR")
private int regMember;
@Column(name = "REG_DT")
private String regDate;
public static ProjectFileEntity of(String projectCode, String fileName, int memberCode){
return ProjectFileEntity.builder()
.projectCode(projectCode)
.fileName(fileName)
.regMember(memberCode)
.regDate(Common.getNow(null))
.build();
}
}

View File

@@ -0,0 +1,62 @@
package com.krt.flower.Flower.entity;
import com.krt.flower.Flower.entity_pk.QuestionEntityPK;
import jakarta.persistence.*;
import lombok.*;
@Entity
@Getter @Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@IdClass(QuestionEntityPK.class)
@Table(name = "question")
public class QuestionEntity {
@Column(name = "IDX", insertable = false, updatable = false)
private long idx;
@Id
@Column(name = "PRJ_CD", insertable = false, updatable = false)
private String projectCode;
@Id
@Column(name = "Q_UK", insertable = false, updatable = false)
private int questionUniqueKey;
@Column(name = "Q_ID", insertable = false, updatable = false)
private String questionID;
@Column(name = "Q_ODR", insertable = false, updatable = false)
private int questionOrder;
@Column(name = "NM", insertable = false, updatable = false)
private String questionName;
@Column(name = "DIM", insertable = false, updatable = false)
private int questionDimension;
@Column(name = "TY", insertable = false, updatable = false)
private int questionType;
@Column(name = "EXP_TXT", insertable = false, updatable = false)
private String questionExplain;
@Column(name = "TT", insertable = false, updatable = false)
private String questionTitle;
@Column(name = "DES", insertable = false, updatable = false)
private String questionDescription;
@Column(name = "REG_MBR", insertable = false, updatable = false)
private int regMember;
@Column(name = "REG_DT", insertable = false, updatable = false)
private String regDate;
@Column(name = "IS_DEL", insertable = false)
private int isDelete;
@Column(name = "DEL_DT", insertable = false)
private String deleteDate;
}

View File

@@ -0,0 +1,52 @@
package com.krt.flower.Flower.entity;
import com.krt.flower.Flower.entity_pk.SurveyDataEntityPK;
import jakarta.persistence.*;
import lombok.*;
@Entity
@Getter
@Setter
@ToString
@Builder
@NoArgsConstructor
@AllArgsConstructor
@IdClass(SurveyDataEntityPK.class)
@Table(name = "survey_data")
public class SurveyDataEntity {
@Column(name = "IDX", insertable = false, updatable = false)
private long idx;
@Id
@Column(name = "PRJ_CD")
private String projectCode;
@Id
@Column(name = "ANS_ID")
private String answerId;
@Id
@Column(name = "Q_UK")
private int questionUniqueKey;
@Id
@Column(name = "LOOP_ID")
private int loopId;
@Column(name = "ANS_DATA")
private String answerData;
@Column(name = "ANS_DT")
private String answerDate;
public static SurveyDataEntity toEntity(String projectCode, String answerId, int questionUniqueKey, int loopId, String answerData, String answerDate){
return SurveyDataEntity.builder()
.projectCode(projectCode)
.answerId(answerId)
.questionUniqueKey(questionUniqueKey)
.loopId(loopId)
.answerData(answerData)
.answerDate(answerDate)
.build();
}
}

View File

@@ -0,0 +1,44 @@
package com.krt.flower.Flower.entity;
import com.krt.flower.Flower.entity_pk.SurveyRespondentEntityPK;
import jakarta.persistence.*;
import lombok.*;
@Entity
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@IdClass(SurveyRespondentEntityPK.class)
@Table(name = "survey_respondent")
public class SurveyRespondentEntity {
@Column(name = "IDX", insertable = false, updatable = false)
private long idx;
@Id
@Column(name = "PRJ_CD")
private String projectCode;
@Id
@Column(name = "ANS_ID")
private String answerId;
@Column(name = "SV_TY_CD")
private int surveyTypeCode;
@Column(name = "ANS_ST")
private int answerState;
@Column(name = "ANS_S_DT", insertable = false, updatable = false)
private String answerStartDate;
@Column(name = "ANS_E_Q_UK")
private int answerEndQuestionUniqueKey;
@Column(name = "ANS_LOOP_ID")
private int answerLoopId;
@Column(name = "ANS_E_DT", insertable = false)
private String answerEndDate;
}

View File

@@ -0,0 +1,11 @@
package com.krt.flower.Flower.entity_pk;
import lombok.Data;
import java.io.Serializable;
@Data
public class ProjectFileEntityPK implements Serializable {
private String projectCode;
private String fileName;
}

View File

@@ -0,0 +1,11 @@
package com.krt.flower.Flower.entity_pk;
import lombok.Data;
import java.io.Serializable;
@Data
public class QuestionEntityPK implements Serializable {
private int questionUniqueKey;
private String projectCode;
}

View File

@@ -0,0 +1,13 @@
package com.krt.flower.Flower.entity_pk;
import lombok.Data;
import java.io.Serializable;
@Data
public class SurveyDataEntityPK implements Serializable {
private String projectCode;
private String answerId;
private int questionUniqueKey;
private int loopId;
}

View File

@@ -0,0 +1,11 @@
package com.krt.flower.Flower.entity_pk;
import lombok.Data;
import java.io.Serializable;
@Data
public class SurveyRespondentEntityPK implements Serializable {
private String projectCode;
private String answerId;
}

View File

@@ -0,0 +1,19 @@
package com.krt.flower.Flower.exception;
import org.springframework.http.HttpStatus;
public class ApiException extends RuntimeException{
ExceptionDto exceptionDto;
public ApiException(HttpStatus status, String code, String message, String errorPoint, String countryCode) {
this.exceptionDto = ExceptionDto.builder()
.status(status)
.code(code)
.message(message)
.errorPoint(errorPoint)
.countryCode(countryCode)
.build();
}
}

View File

@@ -0,0 +1,33 @@
package com.krt.flower.Flower.exception;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class ApiExceptionAdvice {
@ExceptionHandler({ApiException.class})
public ResponseEntity<ApiExceptionEntity> exceptionHandler(ApiException apiEx) {
return ResponseEntity
.status(apiEx.exceptionDto.getStatus())
.body(ApiExceptionEntity.builder()
.errorCode(apiEx.exceptionDto.getCode())
.errorMessage(apiEx.exceptionDto.getMessage())
.errorPoint(apiEx.exceptionDto.getErrorPoint())
.build());
}
@ExceptionHandler({TextException.class})
public ResponseEntity<TextExceptionEntity> exceptionHandler(TextException apiEx) {
return ResponseEntity
.status(apiEx.exceptionDto.getStatus())
.body(TextExceptionEntity.builder()
.errorCode(apiEx.exceptionDto.getCode())
.errorMessage(apiEx.exceptionDto.getMessage())
.build());
}
}

View File

@@ -0,0 +1,37 @@
package com.krt.flower.Flower.exception;
import com.krt.flower.Flower.dto.SurveyDataStructureDto;
import lombok.Builder;
import lombok.Getter;
import lombok.ToString;
@Getter
@ToString
public class ApiExceptionEntity {
private String errorCode;
private String errorMessage;
private SurveyDataStructureDto errorPoint;
@Builder
public ApiExceptionEntity(String errorCode, String errorMessage, String errorPoint) {
this.errorCode = errorCode;
this.errorMessage = errorMessage;
if(errorPoint != null) {
//surveyInfo
int tensor = Integer.parseInt(errorPoint.split("\\|\\|")[0]);
int matrix = Integer.parseInt(errorPoint.split("\\|\\|")[1]);
int scalar = Integer.parseInt(errorPoint.split("\\|\\|")[2]);
this.errorPoint = SurveyDataStructureDto.builder()
.t(tensor)
.m(matrix)
.s(scalar)
.build();
}
}
}

View File

@@ -0,0 +1,18 @@
package com.krt.flower.Flower.exception;
import lombok.*;
import org.springframework.http.HttpStatus;
@Getter
@Builder
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class ExceptionDto {
private HttpStatus status; //상태코드
private String code; //커스텀코드
private String message; //에러메시지
private String countryCode; //다국어코드
private String errorPoint; //데이터 정보
}

View File

@@ -0,0 +1,18 @@
package com.krt.flower.Flower.exception;
import org.springframework.http.HttpStatus;
public class TextException extends RuntimeException{
ExceptionDto exceptionDto;
public TextException(HttpStatus status, String code, String message, String countryCode) {
this.exceptionDto = ExceptionDto.builder()
.status(status)
.code(code)
.message(message)
.countryCode(countryCode)
.build();
}
}

View File

@@ -0,0 +1,22 @@
package com.krt.flower.Flower.exception;
import lombok.Builder;
import lombok.Getter;
import lombok.ToString;
@Getter
@ToString
public class TextExceptionEntity {
private String errorCode;
private String errorMessage;
@Builder
public TextExceptionEntity(String errorCode, String errorMessage) {
this.errorCode = errorCode;
this.errorMessage = errorMessage;
}
}

View File

@@ -0,0 +1,10 @@
package com.krt.flower.Flower.repository;
import com.krt.flower.Flower.entity.ProjectFileEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
public interface ProjectFileRepository extends JpaRepository<ProjectFileEntity, Long>, JpaSpecificationExecutor<ProjectFileEntity> {
ProjectFileEntity findByProjectCodeAndFileName(String projectCode, String filename);
}

View File

@@ -0,0 +1,79 @@
package com.krt.flower.Flower.repository;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.krt.flower.Flower.dto.SurveyDataStructureDto;
import com.krt.flower.Flower.dto.SurveyUploadFileDto;
import com.krt.flower.Flower.entity.QQuestionEntity;
import com.krt.flower.Flower.entity.QSurveyDataEntity;
import com.krt.flower.Flower.entity.QSurveyRespondentEntity;
import com.querydsl.core.types.Projections;
import com.querydsl.core.types.dsl.BooleanExpression;
import com.querydsl.jpa.impl.JPAQueryFactory;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Repository;
import java.lang.reflect.Type;
import java.util.List;
@Repository
@RequiredArgsConstructor
public class SurveyFileQueryRepository {
private final JPAQueryFactory queryFactory;
private QQuestionEntity questionEntity = QQuestionEntity.questionEntity;
private QSurveyDataEntity surveyDataEntity = QSurveyDataEntity.surveyDataEntity;
private QSurveyRespondentEntity surveyRespondentEntity = QSurveyRespondentEntity.surveyRespondentEntity;
public List<SurveyUploadFileDto> getSurveyUploadFileList(String projectCode, String ansId, boolean isComplete, boolean isTest){
List<SurveyUploadFileDto> content = queryFactory
.select(Projections.constructor(SurveyUploadFileDto.class,
surveyRespondentEntity.answerId,
questionEntity.questionID,
surveyDataEntity.questionUniqueKey,
surveyDataEntity.loopId,
surveyDataEntity.answerData
)
)
.from(surveyRespondentEntity)
.innerJoin(surveyDataEntity).on(
surveyRespondentEntity.projectCode.eq(surveyDataEntity.projectCode),
surveyRespondentEntity.answerId.eq(surveyDataEntity.answerId)
)
.innerJoin(questionEntity).on(
surveyRespondentEntity.projectCode.eq(questionEntity.projectCode),
surveyDataEntity.questionUniqueKey.eq(questionEntity.questionUniqueKey),
questionEntity.questionDimension.gt(0),
questionEntity.questionType.eq(91),
questionEntity.isDelete.eq(0)
)
.where(
eqProjectCode(projectCode),
eqAnsId(ansId),
isAnswerStateComplete(isComplete, isTest),
isSurveyTypeTest(isTest)
)
.fetch();
return content;
}
private BooleanExpression eqProjectCode(String projectCode){
return "".equals(projectCode) ? null : surveyRespondentEntity.projectCode.eq(projectCode);
}
private BooleanExpression eqAnsId(String ansId){
return "".equals(ansId) ? null : surveyRespondentEntity.answerId.eq(ansId);
}
private BooleanExpression isAnswerStateComplete(boolean isComplete, boolean isTest){
if(isTest){
return null;
}
return isComplete ? surveyRespondentEntity.answerState.eq(10) : surveyRespondentEntity.answerState.ne(10);
}
private BooleanExpression isSurveyTypeTest(boolean isTest){
return isTest ? surveyRespondentEntity.surveyTypeCode.eq(99) : surveyRespondentEntity.surveyTypeCode.ne(99);
}
}

View File

@@ -0,0 +1,264 @@
package com.krt.flower.Flower.service;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.krt.flower.Flower.dto.*;
import com.krt.flower.Flower.entity.ProjectFileEntity;
import com.krt.flower.Flower.repository.ProjectFileRepository;
import com.krt.flower.Flower.repository.SurveyFileQueryRepository;
import com.krt.flower.Flower.util.Common;
import com.krt.flower.Flower.util.SecurityUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@Service
@RequiredArgsConstructor
public class FileService {
private final ProjectFileRepository projectFileRepository;
private final SurveyFileQueryRepository surveyFileQueryRepository;
public Path getLogoPath(String filename) {
return Paths.get("/opt/newssak/Logos/" + filename);
}
public int saveProjectLogoFiles(String projectCode, List<MultipartFile> multipartFileList) throws Exception {
MultipartFile multipartFile = null;
//파일 있을 시, 실행
try {
//String directory = "D:\\opt\\newssak\\Logos\\" + projectCode;
String directory = "/opt/newssak/Logos/" + projectCode;
File fileFolder = new File(directory);
boolean fileFolderCheck = fileFolder.mkdirs();
//파일 저장
for(MultipartFile mf : multipartFileList) {
multipartFile = mf;
File saveFile = new File(directory + "/" + mf.getOriginalFilename());
multipartFile.transferTo(saveFile);
}
}catch (Exception e) {
return 0;
}
return 1;
}
public Path getProjectFilePath(String projectCode,String filename) {
return Paths.get("/opt/newssak/projectfiles/"+projectCode+"/" + filename);
}
public List<String> getProjectFileList(String projectCode, String securityCode){
String baseUrl = "https://flower.kric.com:7443/api/v1/files/file/";
//String directory = "D:\\opt\\newssak\\projectfiles\\" + projectCode;
String directory = "/opt/newssak/projectfiles/" + projectCode;
Path dirPath = Paths.get(directory);
List<String> fileUrls;
try {
fileUrls = Files.walk(dirPath)
.filter(Files::isRegularFile)
.map(path -> baseUrl + path.getFileName().toString() + "?sc="+securityCode)
.collect(Collectors.toList());
} catch (Exception e) {
ArrayList<String> empty = new ArrayList<String>();
return empty.stream().toList();
}
return fileUrls;
}
public Path getUploadFilePath(String projectCode, String answerId, String questionUniqueKey, String loop_id,String filename) {
return Paths.get("/opt/newssak/uploadfiles/" + projectCode + "/" + answerId + "/" + questionUniqueKey + "/" + loop_id + "/" + filename);
}
public int saveProjectFiles(String projectCode, int memberCode, List<MultipartFile> multiPartFiles) throws Exception {
MultipartFile multipartFile = null;
//파일 있을 시, 실행
try {
if(multiPartFiles != null){
//String directory = "D:\\opt\\newssak\\projectfiles\\" + projectCode;
String directory = "/opt/newssak/projectfiles/" + projectCode;
File fileFolder = new File(directory);
boolean fileFolderCheck = fileFolder.mkdirs();
if (fileFolder.exists() && fileFolder.isDirectory()) {
// 디렉토리 내의 모든 파일과 서브 디렉토리를 가져옴
File[] files = fileFolder.listFiles();
if (files != null) {
for (File file : files) {
if(multiPartFiles.stream().noneMatch(f -> Objects.equals(f.getOriginalFilename(), file.getName()))){
ProjectFileEntity deleteFileEntity = projectFileRepository.findByProjectCodeAndFileName(projectCode, file.getName());
projectFileRepository.delete(deleteFileEntity);
}
deleteRecursively(file);
}
}
}
//파일 저장
for(MultipartFile mf : multiPartFiles) {
multipartFile = mf;
File saveFile = new File(directory + "/" + mf.getOriginalFilename());
multipartFile.transferTo(saveFile);
ProjectFileEntity projectFileEntity = ProjectFileEntity.of(projectCode, mf.getOriginalFilename(), memberCode);
projectFileRepository.save(projectFileEntity);
}
}
}catch (Exception e) {
return 0;
}
return 1;
}
public int deleteAllFiles(String projectCode, int memberCode) throws Exception {
try{
String directory = "/opt/newssak/projectfiles/" + projectCode;
File fileFolder = new File(directory);
boolean fileFolderCheck = fileFolder.mkdirs();
if (fileFolder.exists() && fileFolder.isDirectory()) {
File[] files = fileFolder.listFiles();
if (files != null) {
for (File file : files) {
ProjectFileEntity deleteFileEntity = projectFileRepository.findByProjectCodeAndFileName(projectCode, file.getName());
projectFileRepository.delete(deleteFileEntity);
deleteRecursively(file);
}
}
}
}catch (Exception e) {
return 0;
}
return 1;
}
public int saveSurveyFiles(SurveyUploadInfoDto uploadInfoDto, List<MultipartFile> multiPartFiles) throws Exception {
MultipartFile multipartFile = null;
//프로젝트 코드
String projectCode = SecurityUtil.decrypt(URLDecoder.decode(uploadInfoDto.getSecurity_code(), StandardCharsets.UTF_8));
//응답자 아이디
String answerId = uploadInfoDto.getAnswer_id();
//파일 있을 시, 실행
try {
if(multiPartFiles != null){
//String directory = "D:\\opt\\newssak\\uploadfiles\\" + projectCode + "\\" + answerId;
String directory = "/opt/newssak/uploadfiles/" + projectCode + "/" + answerId;
//파일 저장
for(MultipartFile mf : multiPartFiles) {
multipartFile = mf;
FileStructureDto fileStructureDto = getFileStructure(directory + "/" + mf.getOriginalFilename());
File fileFolder = new File(fileStructureDto.getDirectoryName());
boolean fileFolderCheck = fileFolder.mkdirs();
File saveFile = new File(fileStructureDto.getDirectoryName() + "/" + fileStructureDto.getFileName());
multipartFile.transferTo(saveFile);
}
}
}catch (Exception e) {
return 0;
}
return 1;
}
public byte[] getSurveyFilesZip(String projectCode, String ansId, boolean isComplete, boolean isTest) throws IOException {
Gson gson = new Gson();
Type surveyDataStructure = new TypeToken<List<SurveyDataStructureDto>>() {}.getType();
List<ZipFileDto> fileList = new ArrayList<ZipFileDto>();
//String directory = "D:\\opt\\newssak\\uploadfiles\\" + projectCode + "\\";
String directory = "/opt/newssak/uploadfiles/" + projectCode;
List<SurveyUploadFileDto> surveyUploadFileList = surveyFileQueryRepository.getSurveyUploadFileList(projectCode, ansId, isComplete, isTest);
for(SurveyUploadFileDto surveyUploadFile : surveyUploadFileList){
List<SurveyDataStructureDto> surveyDataList = gson.fromJson(surveyUploadFile.getAnsData(), surveyDataStructure);
for(SurveyDataStructureDto surveyData : surveyDataList){
String uploadFilePath = directory + "/"
+ surveyUploadFile.getAnsId() + "/"
+ surveyUploadFile.getQuestionUniqueKey() + "/"
+ surveyUploadFile.getLoopId() + "/"
+ surveyData.getO();
if(Files.exists(Paths.get(uploadFilePath))){
String outputPath = surveyUploadFile.getAnsId() + "/" + surveyUploadFile.getQuestionID();
if(surveyUploadFile.getLoopId() > -1){
outputPath += "/" + surveyUploadFile.getLoopId();
}
outputPath += "/" + surveyData.getO();
ZipFileDto zipFile = new ZipFileDto();
zipFile.setFilePath(Paths.get(uploadFilePath));
zipFile.setOutputPath(outputPath);
fileList.add(zipFile);
}
}
}
return compressFilesToZip(fileList);
}
private byte[] compressFilesToZip(List<ZipFileDto> fileList) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(baos);
for (ZipFileDto file : fileList) {
ZipEntry zipEntry = new ZipEntry(file.getOutputPath());
zos.putNextEntry(zipEntry);
byte[] bytes = Files.readAllBytes(file.getFilePath());
zos.write(bytes, 0, bytes.length);
zos.closeEntry();
}
zos.finish();
return baos.toByteArray();
}
private void deleteRecursively(File file) {
// 파일이 디렉토리인 경우, 재귀적으로 내부 파일 삭제
if (file.isDirectory()) {
File[] files = file.listFiles();
if (files != null) {
for (File innerFile : files) {
deleteRecursively(innerFile);
}
}
}
// 파일 또는 빈 디렉토리 삭제
file.delete();
}
private FileStructureDto getFileStructure(String filename){
FileStructureDto fileStructureDto = new FileStructureDto();
String[] splitFileName = filename.split("/");
if(splitFileName.length > 1){
fileStructureDto.setFileName(splitFileName[splitFileName.length-1]);
fileStructureDto.setDirectoryName(String.join("/", Arrays.copyOf(splitFileName, splitFileName.length - 1)));
}
return fileStructureDto;
}
}

View File

@@ -0,0 +1,23 @@
package com.krt.flower.Flower.service;
import lombok.RequiredArgsConstructor;
import org.springframework.security.web.util.matcher.IpAddressMatcher;
import org.springframework.stereotype.Service;
import java.util.List;
@RequiredArgsConstructor
@Service
public class IpAccessControlService {
public boolean isAccessible(String ipAddress) {
List<IpAddressMatcher> ipAddressMatchers = List.of(
new IpAddressMatcher("::1/24"),
new IpAddressMatcher("1.235.195.0/24"),
new IpAddressMatcher("211.254.145.128/25"),
new IpAddressMatcher("175.45.203.213/32")
);
return ipAddressMatchers.stream().anyMatch(matcher -> matcher.matches(ipAddress));
}
}

View File

@@ -0,0 +1,66 @@
package com.krt.flower.Flower.util;
import com.krt.flower.Flower.exception.TextException;
import jakarta.activation.MimetypesFileTypeMap;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpStatus;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
public class Common {
public static String getNow(DateTimeFormatter setFormatter){
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
if(setFormatter != null){
formatter = setFormatter;
}
return now.format(formatter);
}
public static String getMediaType(Resource resource) {
MimetypesFileTypeMap fileTypeMap = new MimetypesFileTypeMap();
try {
String contentType = fileTypeMap.getContentType(resource.getFile());
return contentType;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
//문자열 -> 날짜 메소드
public static Date convertStringToDate(String date) {
Date changeDate = null;
try {
SimpleDateFormat dtFormat = new SimpleDateFormat("yyyy/MM/dd");
changeDate = dtFormat.parse(date);
}catch (Exception e) {
throw new TextException(HttpStatus.BAD_REQUEST, "LVE400", "입력한 날짜 형식을 확인해주세요.", "0");
}
return changeDate;
}
//날짜 -> 문자열 메소드
public static String convertDateToString(Date date) {
String changeDate = null;
try {
SimpleDateFormat dtFormat = new SimpleDateFormat("yyyy년 MM월 dd일");
changeDate = dtFormat.format(date);
}catch (Exception e) {
throw new TextException(HttpStatus.BAD_REQUEST, "LVE400", "입력한 날짜 형식을 확인해주세요.", "0");
}
return changeDate;
}
//변환 시, 정수면 소수점 제거
public static Object doubleCheck(Double num) {
return Math.round(num) == num ? String.format("%.0f", num) : num;
}
}

View File

@@ -0,0 +1,56 @@
package com.krt.flower.Flower.util;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import java.util.List;
public class IpUtil {
private static final String[] IP_HEADER_CANDIDATES = {
"Proxy-Client-IP",
"WL-Proxy-Client-IP",
"HTTP_X_FORWARDED_FOR",
"HTTP_X_FORWARDED",
"HTTP_X_CLUSTER_CLIENT_IP",
"HTTP_CLIENT_IP",
"HTTP_FORWARDED_FOR",
"HTTP_FORWARDED",
"HTTP_VIA",
"REMOTE_ADDR"
};
public static String getClientIp(HttpServletRequest request) {
String ip = getIpXFF(request);
for (String ipHeader: List.of(IP_HEADER_CANDIDATES)) {
ip = request.getHeader(ipHeader);
if (!notValidIp(ip)) return ip;
}
return ip != null ? ip : request.getRemoteAddr();
}
private static String getIpXFF(HttpServletRequest request) {
String ip = request.getHeader("X-Forwarded-For");
if (isMultipleIpXFF(ip)) {
ip = getClientIpWhenMultipleIpXFF(ip);
}
return ip;
}
private static boolean notValidIp(String ip) {
return ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip);
}
private static boolean isMultipleIpXFF(String ip) {
// return ip.contains(",");
return StringUtils.contains(ip, ","); // null-safe
}
private static String getClientIpWhenMultipleIpXFF(String ipList) {
// return ips.split(",")[0];
return StringUtils.split(ipList, ",")[0]; // null-safe
}
}

View File

@@ -0,0 +1,53 @@
package com.krt.flower.Flower.util;
import jakarta.xml.bind.DatatypeConverter;
import org.springframework.util.DigestUtils;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Base64;
public class SecurityUtil {
private static final String key = "kriT#3415%130$^$tuDi0_Ds34155100";//32자리 KART에서 사용하는 키
private static final String iv = key.substring(0, 16); // 16byte의 초기화벡터값
public static String encrypt(String plainText) throws Exception {
//암호화 모드는 CBC를, 패딩은 PKCS5을 사용
Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "AES");
IvParameterSpec ivParamSpec = new IvParameterSpec(iv.getBytes());
c.init(Cipher.ENCRYPT_MODE, keySpec, ivParamSpec);
byte[] encrypted = c.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
//base64로 인코딩
Base64.Encoder encoder = Base64.getEncoder();
return new String(encoder.encode(encrypted));
}
public static String decrypt(String cipherText) throws Exception {
Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "AES");
IvParameterSpec ivParamSpec = new IvParameterSpec(iv.getBytes());
c.init(Cipher.DECRYPT_MODE, keySpec, ivParamSpec);
Base64.Decoder decoder = Base64.getDecoder();
byte[] decodedBytes = decoder.decode(cipherText.replaceAll("\\r\\n|\\r|\\n",""));
byte[] decrypted = c.doFinal(decodedBytes);
return new String(decrypted, StandardCharsets.UTF_8);
}
public static String md5AndHexUpper(String plainText) throws Exception{
//MessageDigest 인스턴스 생성(MD5)
MessageDigest md = MessageDigest.getInstance("MD5");
//해쉬값 업데이트
md.update(plainText.getBytes());
//Byte To Hex String
return DatatypeConverter.printHexBinary(md.digest());
}
public static String md5AndHexLower(String plainText) throws Exception{
//Byte To Hex String(apache)
return new String(DigestUtils.md5DigestAsHex(plainText.getBytes()));
}
}