로그설정 완료

dev
minuk926 3 years ago
parent 39df7f7dd6
commit 5647d83377

2
gradlew.bat vendored

@ -21,7 +21,7 @@
@rem @rem
@rem ########################################################################## @rem ##########################################################################
set JAVA_HOME=D:\tools\java\jdk8144 set JAVA_HOME=C:\tools\java\azul-11.0.13
@rem Set local scope for the variables with windows NT shell @rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal if "%OS%"=="Windows_NT" setlocal

@ -34,7 +34,7 @@ public class CmmFileDtl extends AuditEntity implements Serializable {
@Id @Id
@Schema(required = true, title = "파일ID", example = " ", description = "UUID로 자동 생성") @Schema(required = true, title = "파일ID", example = " ", description = "UUID로 자동 생성")
@Column(name = "file_id", nullable = false, length = 50) @Column(name = "file_id", nullable = false, length = 50)
private String fileId;// = UUID.randomUUID().toString().replaceAll("-", ""); private String fileId;// = CommUtil.getStringFromUUID();
// @EmbeddedId // @EmbeddedId
// private CmmFileDtlIds cmmFileDtlIds; // private CmmFileDtlIds cmmFileDtlIds;

@ -8,6 +8,7 @@ import com.xit.biz.cmm.repository.ICmmFileMstRepository;
import com.xit.biz.cmm.service.ICmmFileService; import com.xit.biz.cmm.service.ICmmFileService;
import com.xit.core.util.AssertUtils; import com.xit.core.util.AssertUtils;
import com.xit.core.util.CommUtil;
import com.xit.core.util.DateUtil; import com.xit.core.util.DateUtil;
import io.jsonwebtoken.lang.Assert; import io.jsonwebtoken.lang.Assert;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
@ -75,7 +76,7 @@ public class CmmFileService implements ICmmFileService {
// file Master key set // file Master key set
// file Master 생성 // file Master 생성
if(isCheckExists) fileMstId = cmmFileMst.getFileMstId(); if(isCheckExists) fileMstId = cmmFileMst.getFileMstId();
else fileMstId = UUID.randomUUID().toString().replaceAll("-", ""); else fileMstId = CommUtil.getStringFromUUID();
cmmFileMst.setFileMstId(fileMstId); cmmFileMst.setFileMstId(fileMstId);
CmmFileMst savedCmmFileMst = cmmFileMstRepository.save(cmmFileMst); CmmFileMst savedCmmFileMst = cmmFileMstRepository.save(cmmFileMst);
@ -92,7 +93,7 @@ public class CmmFileService implements ICmmFileService {
orgFileName = StringUtils.cleanPath(Objects.requireNonNull(mf.getOriginalFilename())); orgFileName = StringUtils.cleanPath(Objects.requireNonNull(mf.getOriginalFilename()));
CmmFileDtl cmmFileDtl = CmmFileDtl.builder() CmmFileDtl cmmFileDtl = CmmFileDtl.builder()
.fileMstId(savedCmmFileMst.getFileMstId()) .fileMstId(savedCmmFileMst.getFileMstId())
.fileId(UUID.randomUUID().toString().replaceAll("-", "")) .fileId(CommUtil.getStringFromUUID())
.fileUpldPath(makePath) .fileUpldPath(makePath)
.contentType(mf.getContentType()) .contentType(mf.getContentType())
.orgFileNm(orgFileName) .orgFileNm(orgFileName)

@ -20,10 +20,17 @@ import java.util.LinkedHashMap;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
/**
* RequestBody
* ReadableRequestWrapperFilter WebFillter
*
* @see com.xit.core.config.filter.log.ReadableRequestWrapperFilter
*/
@Component @Component
@Aspect @Aspect
@Slf4j @Slf4j
public class LoggerAspect { public class LoggerAspect {
// respons 출력 여부
@Value("${api.reponse.logging}") @Value("${api.reponse.logging}")
private boolean isResLogging; private boolean isResLogging;
@ -71,8 +78,8 @@ public class LoggerAspect {
/** /**
* request JSONObject . * request JSONObject .
* @param request * @param request HttpServletRequest
* @return * @return JSONObject
*/ */
private static JSONObject getParams(HttpServletRequest request) { private static JSONObject getParams(HttpServletRequest request) {
JSONObject jsonObject = new JSONObject(); JSONObject jsonObject = new JSONObject();

@ -14,27 +14,22 @@ import org.apache.ibatis.type.JdbcType;
import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate; import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan; import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties; import org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings; import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties; import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder; import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary; import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Profile;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing; import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.transaction.ChainedTransactionManager;
import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.transaction.annotation.EnableTransactionManagement;
@ -92,19 +87,12 @@ public class DataSourceConfig {
return new JpaProperties(); return new JpaProperties();
} }
//@Profile("!test")
@Bean @Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(@Value("${spring.jpa.properties.hibernate.hbm2ddl.auto}") String hbm2ddlAuto) { public LocalContainerEntityManagerFactoryBean entityManagerFactory(@Value("${spring.jpa.properties.hibernate.hbm2ddl.auto}") String hbm2ddlAuto) {
// return builder
// .dataSource(dataSource)
// .properties(jpaProperties.getProperties())
// .packages(ENTITY_PACKAGES)
// .persistenceUnit("default")
// .build();
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setDatabasePlatform(jpaProperties().getDatabasePlatform()); vendorAdapter.setDatabasePlatform(jpaProperties().getDatabasePlatform());
vendorAdapter.setDatabase(jpaProperties().getDatabase()); vendorAdapter.setDatabase(jpaProperties().getDatabase());
vendorAdapter.setShowSql(jpaProperties().isShowSql());
HibernateProperties hibernateProperties = new HibernateProperties(); HibernateProperties hibernateProperties = new HibernateProperties();
hibernateProperties.setDdlAuto(hbm2ddlAuto); hibernateProperties.setDdlAuto(hbm2ddlAuto);
@ -118,6 +106,7 @@ public class DataSourceConfig {
emf.setPersistenceUnitName("default"); emf.setPersistenceUnitName("default");
emf.setJpaVendorAdapter(vendorAdapter); emf.setJpaVendorAdapter(vendorAdapter);
emf.setJpaPropertyMap(propMap); //jpaProperties().getProperties()); emf.setJpaPropertyMap(propMap); //jpaProperties().getProperties());
//emf.getJpaPropertyMap().put(AvailableSettings.BEAN_CONTAINER, new SpringBeanContainer(entityManagerFactory))
return emf; return emf;
} }

@ -13,6 +13,7 @@ import java.io.IOException;
import java.util.regex.Pattern; import java.util.regex.Pattern;
/** /**
* <pre>
* WebFilter * WebFilter
* Application main @ServletComponentScan annotation * Application main @ServletComponentScan annotation
* logging.level.org.springframework.web.filter=debug ( ) * logging.level.org.springframework.web.filter=debug ( )
@ -20,9 +21,12 @@ import java.util.regex.Pattern;
* logback CustomCommonsRequestLoggingFilter logger level=debug or info * logback CustomCommonsRequestLoggingFilter logger level=debug or info
* CommonsRequestLoggingFilter * CommonsRequestLoggingFilter
* logging url * logging url
*
* LoggerAspect
* </pre>
*/ */
@WebFilter(urlPatterns = "/api/*") //@WebFilter(urlPatterns = "/api/*")
@Order(Ordered.HIGHEST_PRECEDENCE) //@Order(Ordered.HIGHEST_PRECEDENCE)
public class CustomCommonsRequestLoggingFilter extends CommonsRequestLoggingFilter { public class CustomCommonsRequestLoggingFilter extends CommonsRequestLoggingFilter {
private static final Pattern ONLY_LOGGING_PATTERN = Pattern.compile(XitConstants.EXCLUDE_LOGGING_URL_PATTERN); private static final Pattern ONLY_LOGGING_PATTERN = Pattern.compile(XitConstants.EXCLUDE_LOGGING_URL_PATTERN);
CatchLocation catchLocation = CatchLocation.AFTER; CatchLocation catchLocation = CatchLocation.AFTER;

@ -7,9 +7,12 @@ import org.apache.http.entity.ContentType;
import org.json.simple.JSONArray; import org.json.simple.JSONArray;
import org.json.simple.JSONObject; import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser; import org.json.simple.parser.JSONParser;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import javax.servlet.*; import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper; import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*; import java.io.*;
@ -18,9 +21,12 @@ import java.nio.charset.StandardCharsets;
import java.util.*; import java.util.*;
import java.util.stream.Collectors; import java.util.stream.Collectors;
/**
* Post parameter log
*/
@Slf4j @Slf4j
//@WebFilter(urlPatterns = "/api/*") @WebFilter(urlPatterns = "/api/*")
//@Order(Ordered.HIGHEST_PRECEDENCE) @Order(Ordered.HIGHEST_PRECEDENCE)
public class ReadableRequestWrapperFilter implements Filter { public class ReadableRequestWrapperFilter implements Filter {
@Override @Override
public void init(FilterConfig filterConfig) { public void init(FilterConfig filterConfig) {
@ -30,7 +36,7 @@ public class ReadableRequestWrapperFilter implements Filter {
@Override @Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException { throws IOException, ServletException {
ReadableRequestWrapper wrapper = new ReadableRequestWrapper((HttpServletRequest)request); ReadableRequestWrapper wrapper = new ReadableRequestWrapper((HttpServletRequest) request);
chain.doFilter(wrapper, response); chain.doFilter(wrapper, response);
} }
@ -39,7 +45,7 @@ public class ReadableRequestWrapperFilter implements Filter {
// Do nothing // Do nothing
} }
public class ReadableRequestWrapper extends HttpServletRequestWrapper { public static class ReadableRequestWrapper extends HttpServletRequestWrapper {
private final Charset encoding; private final Charset encoding;
private byte[] rawData; private byte[] rawData;
private Map<String, String[]> params = new HashMap<>(); private Map<String, String[]> params = new HashMap<>();

@ -10,6 +10,7 @@ import com.xit.core.oauth2.api.service.IUserService;
import com.xit.core.oauth2.oauth.entity.ProviderType; import com.xit.core.oauth2.oauth.entity.ProviderType;
import com.xit.core.oauth2.oauth.entity.RoleType; import com.xit.core.oauth2.oauth.entity.RoleType;
import com.xit.core.oauth2.utils.SecurityUtil; import com.xit.core.oauth2.utils.SecurityUtil;
import com.xit.core.util.CommUtil;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder;
@ -40,7 +41,7 @@ public class UserService implements IUserService {
if (cmmUserRepository.existsByUserId(cmmUser.getUserId())) { if (cmmUserRepository.existsByUserId(cmmUser.getUserId())) {
throw new UserExistedException(ErrorCode.MEMBER_EXISTS); throw new UserExistedException(ErrorCode.MEMBER_EXISTS);
} }
cmmUser.setCmmUserId(UUID.randomUUID().toString().replaceAll("-", "")); cmmUser.setCmmUserId(CommUtil.getStringFromUUID());
cmmUser.setCreatedBy(cmmUser.getUserId()); cmmUser.setCreatedBy(cmmUser.getUserId());
//cmmUser.setCreatedDate(LocalDateTime.now()); //cmmUser.setCreatedDate(LocalDateTime.now());
cmmUser.setRoleType(RoleType.USER); cmmUser.setRoleType(RoleType.USER);

@ -8,6 +8,7 @@ import com.xit.core.oauth2.oauth.entity.UserPrincipal;
import com.xit.core.oauth2.oauth.exception.OAuthProviderMissMatchException; import com.xit.core.oauth2.oauth.exception.OAuthProviderMissMatchException;
import com.xit.core.oauth2.oauth.info.AbstractOAuth2UserInfo; import com.xit.core.oauth2.oauth.info.AbstractOAuth2UserInfo;
import com.xit.core.oauth2.oauth.info.OAuth2UserInfoFactory; import com.xit.core.oauth2.oauth.info.OAuth2UserInfoFactory;
import com.xit.core.util.CommUtil;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.InternalAuthenticationServiceException; import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.AuthenticationException;
@ -90,7 +91,7 @@ public class CustomOAuth2UserService extends DefaultOAuth2UserService {
RoleType.USER RoleType.USER
); );
LocalDateTime localDateTime = LocalDateTime.now(); LocalDateTime localDateTime = LocalDateTime.now();
user.setCmmUserId(UUID.randomUUID().toString().replaceAll("-", "")); user.setCmmUserId(CommUtil.getStringFromUUID());
user.setCreatedBy(userInfo.getId()); user.setCreatedBy(userInfo.getId());
user.setModifiedBy(userInfo.getId()); user.setModifiedBy(userInfo.getId());
user.setCreatedDate(localDateTime); user.setCreatedDate(localDateTime);

@ -232,7 +232,7 @@ public class AwsFileUtil {
return folder return folder
+ ((folder.substring(folder.length() - 1)).equals("/") ? DateUtil.getToday("") + ((folder.substring(folder.length() - 1)).equals("/") ? DateUtil.getToday("")
: ("/" + DateUtil.getToday("")) + "/") : ("/" + DateUtil.getToday("")) + "/")
+ UUID.randomUUID().toString().replaceAll("-", "") + System.currentTimeMillis() + ext; + CommUtil.getStringFromUUID() + System.currentTimeMillis() + ext;
} }
// /** // /**

@ -20,14 +20,15 @@ import java.lang.reflect.Method;
import java.net.URL; import java.net.URL;
import java.net.URLEncoder; import java.net.URLEncoder;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.HashMap; import java.util.*;
import java.util.List;
import java.util.Map;
import java.util.Random;
@Slf4j @Slf4j
public class CommUtil { public class CommUtil {
public static String getStringFromUUID(){
return UUID.randomUUID().toString().replaceAll("-", "");
}
/** /**
* *
* *

@ -32,15 +32,12 @@ spring:
# ================================================================================================================== # ==================================================================================================================
jpa: jpa:
database-platform: org.hibernate.dialect.PostgreSQLDialect database-platform: org.hibernate.dialect.PostgreSQLDialect
#show-sql: false
properties: properties:
hibernate: hibernate:
format_sql: true
use_sql_comments: false
hbm2ddl: hbm2ddl:
# create / create-drop / update / validate / none # create / create-drop / update / validate / none
auto: update auto: update
# hibernate sql log
#show-sql: false
# h2: # h2:
# console: # console:

@ -32,15 +32,13 @@ spring:
# ================================================================================================================== # ==================================================================================================================
jpa: jpa:
database-platform: org.hibernate.dialect.H2Dialect database-platform: org.hibernate.dialect.H2Dialect
# hibernate sql log #show-sql: false
show-sql: false
properties: properties:
hibernate: hibernate:
format_sql: true
use_sql_comments: false
hbm2ddl: hbm2ddl:
# create / create-drop / update / validate / none # create / create-drop / update / validate / none
auto: create-drop auto: create-drop
h2: h2:
console: console:
enabled: true enabled: true
@ -61,13 +59,9 @@ logging:
level: level:
root: info root: info
org: org:
hibernate: # hibernate sql log 출력시 변수 바인딩
# hibernate sql log 출력시 변수 바인딩 #hibernate:
#type: trace #type: trace
springframework:
web:
#CommonsRequestLoggingFilter(RequestLoggingConfig) 를 이용한 로그출력을 위해 필수 debug
filter: error
# ================================================================================================================== # ==================================================================================================================
# Spring-doc 활성 # Spring-doc 활성

@ -2,15 +2,16 @@ spring:
application: application:
name: xit-framework name: xit-framework
#description: XIT api for development #description: XIT api for development
config: config:
import: classpath:config/conf.yml import: classpath:config/conf.yml
profiles: profiles:
active: local active: local
include: oauth include: oauth
# bean name 중복 허용 - junit 사용시 true??
main: main:
# bean name 중복 허용 - junit 사용시 true??
allow-bean-definition-overriding: true allow-bean-definition-overriding: true
# 순환참조 제거
#allow-circular-references: true
# ================================================================================================================== # ==================================================================================================================
# spring message # spring message
@ -100,8 +101,6 @@ spring:
# JPA setting # JPA setting
# ================================================================================================================== # ==================================================================================================================
jpa: jpa:
hibernate:
ddl-auto: none
# 템플릿 view 화면의 렌더링이 끝날 때 까지 Lazy fetch 가 가능하도록 해주는 속성 # 템플릿 view 화면의 렌더링이 끝날 때 까지 Lazy fetch 가 가능하도록 해주는 속성
open-in-view: false open-in-view: false
generate-ddl: false generate-ddl: false
@ -117,6 +116,8 @@ spring:
hbm2ddl: hbm2ddl:
auto: none auto: none
import_files_sql_extractor: org.hibernate.tool.hbm2ddl.MultipleLinesSqlCommandExtractor import_files_sql_extractor: org.hibernate.tool.hbm2ddl.MultipleLinesSqlCommandExtractor
format_sql: true
use_sql_comments: false
jdbc: jdbc:
batch_size: 20 batch_size: 20
lob: lob:

@ -4,11 +4,11 @@
<springProfile name="local"> <springProfile name="local">
<property name="LOG_PATH" value="/Users/minuk/data/xit/logs"/> <property name="LOG_PATH" value="/data/xit/logs"/>
</springProfile> </springProfile>
<springProfile name="dev,prod"> <springProfile name="dev,prod">
<!-- <property name="LOG_PATH" value="/data/xit/logs"/>--> <!-- <property name="LOG_PATH" value="/data/xit/logs"/>-->
<proßperty name="LOG_PATH" value="/Users/minuk/data/xit/logs"/> <proßperty name="LOG_PATH" value="/data/xit/logs"/>
</springProfile> </springProfile>
<include resource="org/springframework/boot/logging/logback/defaults.xml"/> <include resource="org/springframework/boot/logging/logback/defaults.xml"/>
@ -105,14 +105,6 @@
<springProfile name="dev,prod"><appender-ref ref="ASYNC_ROLLING"/></springProfile> <springProfile name="dev,prod"><appender-ref ref="ASYNC_ROLLING"/></springProfile>
</logger> </logger>
<!-- CommonsRequestLoggingFilter 를 이용한 로그출력을 위해 필수 -->
<!--
<logger name="com.xit.core.config.filter.log.CustomCommonsRequestLoggingFilter" level="debug" additivity="false">
<appender-ref ref="CONSOLE"/>
<appender-ref ref="ASYNC_ERROR_ROLLING" />
<springProfile name="dev,prod"><appender-ref ref="ASYNC_ROLLING"/></springProfile>
</logger>
-->
<!-- ============================================================================= --> <!-- ============================================================================= -->
<!-- ============================================================================= --> <!-- ============================================================================= -->

@ -100,7 +100,7 @@ class ICmmCodeRepositoryTest {
System.out.println(comboCodeDtos); System.out.println(comboCodeDtos);
// cmmFileDtlIds.setFileMstId(savedCmmFileMst.getFileMstId()); // cmmFileDtlIds.setFileMstId(savedCmmFileMst.getFileMstId());
// //cmmFileDtlIds.setFileId(UUID.randomUUID().toString().replaceAll("-", "")); // //cmmFileDtlIds.setFileId(CommUtil.getStringFromUUID());
// CmmFileDtl cmmFileDtl = CmmFileDtl.builder() // CmmFileDtl cmmFileDtl = CmmFileDtl.builder()
// .fileMstId(cmmFileDtlIds.getFileMstId()) // .fileMstId(cmmFileDtlIds.getFileMstId())
// .fileId(cmmFileDtlIds.getFileId()) // .fileId(cmmFileDtlIds.getFileId())

@ -3,6 +3,7 @@ package com.xit.biz.cmm.repository;
import com.xit.biz.cmm.entity.CmmFileDtl; import com.xit.biz.cmm.entity.CmmFileDtl;
import com.xit.biz.cmm.entity.CmmFileMst; import com.xit.biz.cmm.entity.CmmFileMst;
import com.xit.biz.cmm.entity.ids.CmmFileDtlIds; import com.xit.biz.cmm.entity.ids.CmmFileDtlIds;
import com.xit.core.util.CommUtil;
import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@ -31,7 +32,7 @@ class ICmmFileRepositoryTest {
@Test @Test
void crud(){ void crud(){
CmmFileMst cmmFileMst = CmmFileMst.builder() CmmFileMst cmmFileMst = CmmFileMst.builder()
.fileMstId(UUID.randomUUID().toString().replaceAll("-", "")) .fileMstId(CommUtil.getStringFromUUID())
.fileCtgCd("BOARD") .fileCtgCd("BOARD")
.fileBizId("BOARD1") .fileBizId("BOARD1")
.build() .build()
@ -43,7 +44,7 @@ class ICmmFileRepositoryTest {
CmmFileMst savedCmmFileMst = cmmFileMstRepository.save(cmmFileMst); CmmFileMst savedCmmFileMst = cmmFileMstRepository.save(cmmFileMst);
CmmFileDtlIds cmmFileDtlIds = new CmmFileDtlIds(); CmmFileDtlIds cmmFileDtlIds = new CmmFileDtlIds();
cmmFileDtlIds.setFileMstId(savedCmmFileMst.getFileMstId()); cmmFileDtlIds.setFileMstId(savedCmmFileMst.getFileMstId());
//cmmFileDtlIds.setFileId(UUID.randomUUID().toString().replaceAll("-", "")); //cmmFileDtlIds.setFileId(CommUtil.getStringFromUUID());
CmmFileDtl cmmFileDtl = CmmFileDtl.builder() CmmFileDtl cmmFileDtl = CmmFileDtl.builder()
.fileMstId(cmmFileDtlIds.getFileMstId()) .fileMstId(cmmFileDtlIds.getFileMstId())
.fileId(cmmFileDtlIds.getFileId()) .fileId(cmmFileDtlIds.getFileId())

@ -13,6 +13,8 @@ import com.xit.core.oauth2.api.dto.TokenDto;
import com.xit.core.oauth2.api.service.IAuthService; import com.xit.core.oauth2.api.service.IAuthService;
import com.xit.core.oauth2.oauth.entity.ProviderType; import com.xit.core.oauth2.oauth.entity.ProviderType;
import com.xit.core.oauth2.oauth.entity.RoleType; import com.xit.core.oauth2.oauth.entity.RoleType;
import com.xit.core.util.CommUtil;
import com.xit.core.util.JsonUtil;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.junit.Assert; import org.junit.Assert;
import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.AfterEach;
@ -34,6 +36,7 @@ import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.ComponentScan;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.mock.web.MockServletContext; import org.springframework.mock.web.MockServletContext;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
@ -44,6 +47,8 @@ import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MockMvcBuilder; import org.springframework.test.web.servlet.MockMvcBuilder;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.LinkedMultiValueMap;
@ -53,9 +58,13 @@ import org.springframework.web.filter.CharacterEncodingFilter;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
import java.util.Arrays; import java.util.Arrays;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID; import java.util.UUID;
import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
@ -79,15 +88,16 @@ class OAuth2LocalControllerTest {
private WebApplicationContext webApplicationContext; private WebApplicationContext webApplicationContext;
CmmUser user = CmmUser.builder() private CmmUser user;
.providerType(ProviderType.LOCAL) // = CmmUser.builder()
.userId("minuk926") // .cmmUserId(CommUtil.getStringFromUUID())
.userName("임종욱") // .providerType(ProviderType.LOCAL)
.password("Minuk926!@") // .userId("minuk926")
.email("minuk926@gmail.com") // .userName("임종욱")
.build(); // .password("Minuk926!@")
// .email("minuk926@gmail.com")
// .roleType(RoleType.USER)
// .build();
//@InjectMocks //@InjectMocks
@ -103,7 +113,9 @@ class OAuth2LocalControllerTest {
void setUp() { void setUp() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).build(); this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).build();
CmmUser user = CmmUser.builder()
this.user = CmmUser.builder()
.cmmUserId(CommUtil.getStringFromUUID())
.providerType(ProviderType.LOCAL) .providerType(ProviderType.LOCAL)
.userId("minuk926") .userId("minuk926")
.userName("임종욱") .userName("임종욱")
@ -111,10 +123,10 @@ class OAuth2LocalControllerTest {
.email("minuk926@gmail.com") .email("minuk926@gmail.com")
.roleType(RoleType.USER) .roleType(RoleType.USER)
.build(); .build();
user.setCmmUserId(UUID.randomUUID().toString().replaceAll("-", "")); // user.setCmmUserId(CommUtil.getStringFromUUID());
CmmUser cmmUser = userRepository.save(user); // CmmUser cmmUser = userRepository.save(user);
// userRepository.save(user); // userRepository.save(user);
} }
@AfterEach @AfterEach
@ -132,18 +144,47 @@ class OAuth2LocalControllerTest {
assertNotNull(webApplicationContext.getBean("OAuth2LocalController")); assertNotNull(webApplicationContext.getBean("OAuth2LocalController"));
MultiValueMap<String, String> params = new LinkedMultiValueMap<>(); // MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("providerType", ProviderType.LOCAL.name()); // params.add("providerType", ProviderType.LOCAL.name());
params.add("userId", "minuk926"); // params.add("userId", "minuk926");
params.add("password", "Minuk926!@"); // params.add("password", "Minuk926!@");
mockMvc.perform(post("/api/vi/auth/login").params(params)) // mockMvc.perform(post("/api/vi/auth/login").params(params))
.andDo(print()) // .andDo(print())
// .andExpect(status().isOk())
// .andExpect(jsonPath("$.success").value(true))
// .andExpect(jsonPath("$.data").exists())
// //.andExpect(jsonPath("$.success").value(true))
// //.andExpect(jsonPath("$.success").value(true))
// ;
// given
userRepository.save(user);
//given(userRepository.save(user)).willReturn(user);
//when(userRepository.findByUserId(user.getUserId())).thenReturn(user);
// when
// then
//given(userRepository.save(user)).willReturn(user);
//when(userRepository.findByUserId(user.getUserId())).thenReturn()
LoginRequestDto loginRequestDto = new LoginRequestDto();
loginRequestDto.setProviderType(ProviderType.LOCAL);
loginRequestDto.setUserId(user.getUserId());
loginRequestDto.setPassword("Minuk926!@");
MvcResult result = mockMvc.perform(
MockMvcRequestBuilders.post("/api/v1/auth/login")
.content(Objects.requireNonNull(JsonUtil.toJson(loginRequestDto)))
.contentType(MediaType.APPLICATION_JSON)
//.accept(MediaType.APPLICATION_JSON)
.characterEncoding("UTF-8")
).andDo(print())
.andExpect(status().isOk()) .andExpect(status().isOk())
.andExpect(jsonPath("$.success").value(true)) .andReturn();
.andExpect(jsonPath("$.data").exists())
//.andExpect(jsonPath("$.success").value(true))
//.andExpect(jsonPath("$.success").value(true)) //.andExpect(jsonPath("$.success").value(true))
; //.andExpect(jsonPath("$.data").exists());
} }
@Test @Test

@ -1,83 +0,0 @@
package com.xit.core.oauth2.api.dto;
import com.xit.core.oauth2.oauth.entity.ProviderType;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.validation.ConstraintViolation;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.*;
// test runner를 통해 Junit Framework 호출
// SpringRunner는 SpringJunit4ClassRunner의 단축어
// @Autowired @MockBean에 해당 하는 것들에만 application context loading
// 1. component가 주입 되어야 할 때
// 2. 설정 데이타가 주입되어야 할 때
// 3. Spring과 관련 없는 기능 테스트시 금지(SpringRunner는 overhead가 크다)
// @RunWith(SpringRunner.class)
// @RunWith(SpringRunner.class) : Junit4, @RunWith(MockitoJUnitRunner.class) : Junit 5
// @Mock : Mock 객체 생성 - mapper에 사용
// @InjectMocks : Mock 객체 주입 - service 에 사용
//@RunWith(SpringRunner.class)
//@RunWith(MockitoJUnitRunner.class)
@ExtendWith(MockitoExtension.class)
// 1. 메모리 데이타 베이스 설정
// 2. @Entity class scan
// 3. Spring Data JAP Repository 설정
// 4. 테스트 종료시 Rollback
//@DataJpaTest
// Junit5
// Spring Test & Spring Boot Test
// AssertJ
// Hamcrest
// Mockito
// JSONassert
// JsonPath
// @ExtendWith(SpringExtention.class)도 적용 되어있어 생략 가능
// Junit4 사용시 @SpringBootTest는 SpringJUnit4ClassRunner를 상속받는 @RunWhith(SpringRynver.class)와 함께 사용
//@SpringBootTest
public class LoginRequestDtoTest {
@BeforeEach
void setUp() {
}
@AfterEach
void tearDown() {
}
@Test
public void whenAllInvalid_thenViolationsShouldBeReported() {
LoginRequestDto dto = new LoginRequestDto();
//dto.setProviderType(ProviderType.GOOGLE.name());
//customer.setCustomerTypeOfSubset(CustomerType.DEFAULT);
//customer.setCustomerTypeMatchesPattern(CustomerType.OLD);
// Set<ConstraintViolation> violations = validator.validate(customer);
// assertThat(violations.size()).isEqualTo(3);
// assertThat(violations)
// .anyMatch(havingPropertyPath("customerTypeString")
// .and(havingMessage("must be any of enum class com.baeldung.javaxval.enums.demo.CustomerType")));
// assertThat(violations)
// .anyMatch(havingPropertyPath("customerTypeOfSubset")
// .and(havingMessage("must be any of [NEW, OLD]")));
// assertThat(violations)
// .anyMatch(havingPropertyPath("customerTypeMatchesPattern")
// .and(havingMessage("must match \"NEW|DEFAULT\"")));
}
}
Loading…
Cancel
Save