Skip to content
Open
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
58 changes: 12 additions & 46 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ plugins {
id 'io.spring.dependency-management' version '1.1.6'
}

group = 'com.example'
group = 'Comment_Adm'
version = '0.0.1-SNAPSHOT'

java {
Expand All @@ -13,58 +13,24 @@ java {
}
}

configurations {
compileOnly {
extendsFrom annotationProcessor
}
}

jar {
enabled = true
}

repositories {
mavenCentral()
}

dependencies {
// Spring Boot JPA와 관련 의존성도 확인(Database와 관련)
// implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
// OAuth2 클라이언트 기능 지원
implementation 'org.springframework.boot:spring-boot-starter-oauth2-client'
// Spring Security를 사용한 인증 및 권한 관리를 지원
// implementation 'org.springframework.boot:spring-boot-starter-security'
// implementation 'mysql:mysql-connector-java:8.0.33'
// Spring MVC와 REST API 개발을 위한 기본 설정 및 라이브러리 제공
implementation 'org.springframework.boot:spring-boot-starter-web'
// Spring Boot와 Thymeleaf 템플릿 엔진의 통합을 지원
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'

// Lombok 라이브러리 의존성
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
implementation 'org.projectlombok:lombok:1.18.20'

// MySQL 데이터베이스에 연결하기 위한 JDBC 드라이버 추가
// runtimeOnly 'com.mysql:mysql-connector-j'

// runtimeOnly 'com.mysql:mysql-connector-j' // -j
// runtimeOnly 'com.mysql:mysql-connector-java:8.0.38'
// implementation 'com.mysql:mysql-connector-java:8.0.33'
// 테스트 코드를 작성하고 실행하기 위한 라이브러리 모음 추가
testImplementation 'org.springframework.boot:spring-boot-starter-test'

// Spring Security를 테스트하기 위한 유틸리티 추가
testImplementation("org.springframework.security:spring-security-test")
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'

// 비밀번호 암호화(Password Encoder)
// implementation 'org.springframework.security:spring-security-crypto:5.7.1'

// 웹소켓 서버 세팅
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa' // JPA 의존성 추가
implementation 'org.springframework.boot:spring-boot-starter-websocket'
// WebClient 사용을 위해 필요
// implementation 'org.springframework.boot:spring-boot-starter-webflux'
implementation 'org.projectlombok:lombok:1.18.26'
annotationProcessor 'org.projectlombok:lombok:1.18.26'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'mysql:mysql-connector-java'
implementation 'mysql:mysql-connector-java:8.0.33'
testImplementation ('org.springframework.boot:spring-boot-starter-test'){
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}

tasks.named('test') {
Expand Down
2 changes: 1 addition & 1 deletion gradle/wrapper/gradle-wrapper.properties
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@ distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
zipStorePath=wrapper/dists
2 changes: 0 additions & 2 deletions src/main/java/com/example/taba_project/DemoApplication.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
// import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;

// @SpringBootApplication(exclude = { SecurityAutoConfiguration.class })
@SpringBootApplication(exclude = {SecurityAutoConfiguration.class})
public class DemoApplication {

Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package com.example.taba_project.controller;

import com.example.taba_project.handler.FileStorageHandler;
import com.example.taba_project.model.Image;
import com.example.taba_project.repository.ImageRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

@RestController
@RequestMapping("/api/image")
public class ImageController {

private final ImageRepository imageRepository;
private final FileStorageHandler fileStorageHandler;
private static final Logger logger = LoggerFactory.getLogger(ImageController.class);

@Value("${file.storage.directory")
private String directoryPath;

public ImageController(ImageRepository imageRepository, FileStorageHandler fileStorageHandler) {
this.imageRepository = imageRepository;
this.fileStorageHandler = fileStorageHandler;
}

@PostMapping("/upload")
public ResponseEntity<String> uploadImage(@RequestParam("fileName") String fileName,
@RequestBody byte[] fileData) {
try {
// 파일 저장
String savedFilePath = fileStorageHandler.saveFile(directoryPath, fileName, fileData);

// DB에 저장
Image image = new Image();
image.setUrl(savedFilePath); // 파일 경로를 url로 설정
imageRepository.save(image);

return ResponseEntity.ok("파일 업로드 및 DB 저장 성공: " + savedFilePath);

} catch (IOException e) {
logger.error("파일 저장 실패", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("파일 저장 실패: " + e.getMessage());
}
}
}
Original file line number Diff line number Diff line change
@@ -1,30 +1,3 @@
//package com.example.demo.controller;
//
//import com.example.demo.model.ImageData;
//import com.example.demo.service.ImageProcessingService;
//import lombok.RequiredArgsConstructor;
//import org.springframework.messaging.handler.annotation.MessageMapping;
//import org.springframework.messaging.handler.annotation.Payload;
//import org.springframework.stereotype.Controller;
//
//@Controller
//@RequiredArgsConstructor
//public class ImageWebSocketController {
//
// private final ImageProcessingService imageProcessingService;
//
// @MessageMapping("/upload")
// public void handleImageUpload(@Payload ImageData imageData) {
// try {
// // 서비스 계층으로 이미지 데이터 전달 및 저장
// String savedPath = imageProcessingService.saveImage(imageData);
// System.out.println("이미지 저장 경로: " + savedPath);
// } catch (Exception e) {
// System.err.println("이미지 처리 중 오류: " + e.getMessage());
// }
// }
//}

package com.example.taba_project.controller;

import com.example.taba_project.model.ImageData;
Expand Down Expand Up @@ -60,4 +33,4 @@ public void handleImageUpload(@Payload ImageData imageData) {
logger.error("이미지 처리 중 오류: {}", e.getMessage());
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
package com.example.taba_project.controller;

import com.example.taba_project.model.Info;
import com.example.taba_project.repository.InfoRepository;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/info")
@RequiredArgsConstructor
public class InfoController {

private static final Logger logger = LoggerFactory.getLogger(InfoController.class);

private final InfoRepository infoRepository;

// 새로운 Info 저장
@PostMapping
public ResponseEntity<Info> saveInfo(@RequestBody Info info) {
if (info.getEmotion() == null || info.getPercentage() == null) {
logger.warn("유효하지 않은 데이터 요청: {}", info);
return ResponseEntity.badRequest().body(null);
}

if (!isValidPercentage(info.getPercentage())) {
logger.warn("퍼센트 범위 초과: {}", info.getPercentage());
return ResponseEntity.badRequest().body(null);
}

Info savedInfo = infoRepository.save(info);
logger.info("Info 저장 성공: {}", savedInfo);
return ResponseEntity.ok(savedInfo);
}

// 특정 Info 조회 및 스크립트 반환
@GetMapping("/{id}")
public ResponseEntity<String> getInfoWithScript(@PathVariable Long id) {
Info info = infoRepository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("Info not found with id: " + id));

try {
String script = generateEmotionScript(info.getEmotion(), info.getPercentage());
logger.info("생성된 스크립트: {}", script);
return ResponseEntity.ok(script);
} catch (IllegalArgumentException e) {
logger.error("스크립트 생성 중 오류 - id: {}, 이유: {}", id, e.getMessage());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("스크립트 생성 오류: " + e.getMessage());
}
}

private String generateEmotionScript(String emotion, String percentageStr) {
double percentage = Double.parseDouble(percentageStr);

String intensity;
if (percentage >= 90) {
intensity = "완전히";
} else if (percentage >= 75) {
intensity = "매우";
} else if (percentage >= 60) {
intensity = "상당히";
} else if (percentage >= 50) {
intensity = "약간";
} else {
return "50% 미만 감정은 분석되지 않습니다.";
}

return switch (emotion.toLowerCase()) {
case "행복" -> "상대가 " + intensity + " 행복해 합니다.";
case "놀람" -> "상대가 " + intensity + " 놀랐습니다.";
case "무표정" -> "상대가 " + intensity + " 무표정입니다.";
case "혐오" -> "상대가 " + intensity + " 불쾌한 상태입니다.";
case "분노" -> "상대가 " + intensity + " 화가 난 상태입니다.";
case "슬픔" -> "상대가 " + intensity + " 슬퍼합니다.";
default -> throw new IllegalArgumentException("알 수 없는 감정: " + emotion);
};
}

private boolean isValidPercentage(String percentageStr) {
try {
double percentage = Double.parseDouble(percentageStr);
return percentage >= 0 && percentage <= 100;
} catch (NumberFormatException e) {
return false;
}
}
}
Original file line number Diff line number Diff line change
@@ -1,22 +1,33 @@
package com.example.taba_project.handler;

import org.springframework.stereotype.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

@Component
public class FileStorageHandler {

public static void saveFile(String directoryPath, String fileName, byte[] data) throws IOException {
private static final Logger logger = LoggerFactory.getLogger(FileStorageHandler.class);

public String saveFile(String directoryPath, String fileName, byte[] data) throws IOException {
// 디렉토리 경로를 생성
Path dirPath = Paths.get(directoryPath);
if (!Files.exists(dirPath)) {
Files.createDirectories(dirPath); // 디렉토리가 없으면 생성
logger.info("디렉토리 생성 : {}", dirPath.toAbsolutePath());
}

// 파일 경로 생성 및 저장
Path filePath = Paths.get(directoryPath, fileName);
Files.write(filePath, data);
System.out.println("파일 저장 완료: " + filePath.toAbsolutePath());
logger.info("파일 저장 완료: {}", filePath.toAbsolutePath());

// 저장된 파일의 절대 경로 반환
return filePath.toAbsolutePath().toString();
}
}
}
Loading