37 Commits

Author SHA1 Message Date
kimyonghwa
7cd4d602f7 bugfix
- update ftl path
- delete duplicate security settings
2019-11-14 11:36:35 +09:00
kimyonghwa
f7901cbd18 Update README.md 2019-08-08 02:08:17 +09:00
kimyonghwa
945b44fdc7 Redis Cache annotation 2019-08-08 01:52:39 +09:00
kimyonghwa
e729ff1504 Add Redis Configuration 2019-08-06 01:56:48 +09:00
codej99
bdd09eeaa9 Merge pull request #19 from codej99/feature/board
영속성 컨텍스트의 변경감지(dirty checking)가 적용으로 인한 소스 수정
2019-08-05 22:25:29 +09:00
kimyonghwa
458de9d927 영속성 컨텍스트의 변경감지(dirty checking)가 적용으로 인한 소스 수정 2019-05-16 22:07:28 +09:00
codej99
a03a263adf Merge pull request #18 from codej99/feature/board
게시판 업데이트 수정 - 변경감지 기능 이용
2019-05-16 16:40:29 +09:00
kimyonghwa
c6110eb806 게시판 업데이트 수정 - 변경감지 기능 이용
게시판 리퀘스트 파라미터 유효성 체크 수정
2019-05-16 16:39:45 +09:00
codej99
0bf89cc08b Update README.md 2019-05-15 02:18:06 +09:00
codej99
002ac18e4a Merge pull request #17 from codej99/feature/board
Feature/board
2019-05-10 23:43:44 +09:00
kimyonghwa
c25984207b Merge branch 'feature/board' of https://github.com/codej99/SpringRestApi into feature/board 2019-05-10 23:40:52 +09:00
kimyonghwa
2a0a9721ed Bugfix board 2019-05-10 23:40:33 +09:00
kimyonghwa
69f3053371 Modified the unit test 2019-05-10 10:27:03 +09:00
kimyonghwa
189e741ded Make board 2019-05-10 02:17:23 +09:00
kimyonghwa
2e5e6be283 Develop simple board 2019-05-09 19:43:48 +09:00
codej99
0bcbc81775 Merge pull request #16 from codej99/feature/security
Feature/security
2019-05-09 14:12:56 +09:00
codej99
951bd95faa Merge branch 'master' into feature/security 2019-05-09 14:12:24 +09:00
kimyonghwa
b23ca762bf Merge branch 'feature/security' of https://github.com/codej99/SpringRestApi into feature/security
# Conflicts:
#	src/main/java/com/rest/api/config/security/CustomAccessDeniedHandler.java
#	src/main/java/com/rest/api/config/security/SecurityConfiguration.java
2019-05-09 14:10:27 +09:00
kimyonghwa
695908e2c7 bugfix : exception process 2019-05-09 14:07:27 +09:00
kimyonghwa
dac4f282e3 Develop board 2019-05-09 13:56:27 +09:00
codej99
5f1bd9fdcc Update HelloController.java
helloworld -> helloworld-nice to meet you
2019-05-05 23:28:42 +09:00
codej99
8ad0baad33 Merge pull request #15 from codej99/feature/gracefullyshutdown
Blue / Green Deployment
2019-05-03 15:14:45 +09:00
kimyonghwa
b784ba6bdb Blue / Green Deployment 2019-05-03 15:12:40 +09:00
codej99
c2a2ba9b46 Merge pull request #14 from codej99/feature/gracefullyshutdown
Feature/gracefullyshutdown
2019-05-03 15:11:23 +09:00
kimyonghwa
b8b1f4c65f Blue / Green Deployment 2019-05-03 15:06:15 +09:00
kimyonghwa
4fb92209e6 update db password 2019-05-02 23:23:51 +09:00
kimyonghwa
3f3ff162b1 Merge branch 'master' into feature/gracefullyshutdown
# Conflicts:
#	src/main/java/com/rest/api/config/security/SecurityConfiguration.java
2019-05-02 22:48:29 +09:00
codej99
19d23f1bdd Merge pull request #13 from codej99/feature/security
Feature/security
2019-05-02 22:44:42 +09:00
codej99
49a244c970 Merge branch 'master' into feature/security 2019-05-02 22:44:35 +09:00
codej99
1eb3fe7486 Merge pull request #12 from codej99/feature/seperate-profile
Feature/seperate profile
2019-05-02 22:43:03 +09:00
kimyonghwa
b3da392b47 was gracefully shutdown 2019-05-02 19:08:43 +09:00
codej99
24192c2b72 Merge pull request #11 from codej99/feature/seperate-profile
Feature/seperate profile
2019-05-02 10:42:04 +09:00
codej99
8d1765a280 Merge pull request #10 from codej99/feature/seperate-profile
Add logging preferences
2019-05-01 00:56:53 +09:00
codej99
930ecb504f Merge pull request #9 from codej99/feature/seperate-profile
seperate environment profile
2019-04-30 16:23:07 +09:00
kimyonghwa
26b9321855 Merge branch 'feature/security' of https://github.com/codej99/SpringRestApi into feature/security 2019-04-17 23:09:29 +09:00
kimyonghwa
758c3a0799 Merge branch 'feature/security' of https://github.com/codej99/SpringRestApi into feature/security 2019-04-17 19:26:04 +09:00
kimyonghwa
4cb008c876 modify security matcher path 2019-04-17 19:25:48 +09:00
36 changed files with 853 additions and 44 deletions

View File

@@ -96,4 +96,27 @@ alter table user_roles
- Document
- https://daddyprogrammer.org/post/1012/springboot2-rest-api-social-login-kakao/
- Git
- https://github.com/codej99/SpringRestApi/tree/feature/social-kakao
- https://github.com/codej99/SpringRestApi/tree/feature/social-kakao
- SpringBoot2로 Rest api 만들기(11) profile을 이용한 환경별 설정 분리
- Document
- https://daddyprogrammer.org/post/2421/springboot2-seperate-environment-by-profile/
- Git
- https://github.com/codej99/SpringRestApi/tree/feature/seperate-profile
- SpringBoot2로 Rest api 만들기(12) Deploy & Nginx 연동 & 무중단 배포 하기
- Document
- https://daddyprogrammer.org/post/2445/springboot2-blue-green-deploy-nginx/
- Git
- https://github.com/codej99/SpringRestApi/tree/feature/gracefullyshutdown
- SpringBoot2로 Rest api 만들기(13) Jenkins 배포(Deploy) + Git Tag Rollback
- Document
- https://daddyprogrammer.org/post/2697/springboot2-jenkins-deploy-gittag-rollback/
- SpringBoot2로 Rest api 만들기(14) 간단한 JPA 게시판(board) 만들기
- Document
- https://daddyprogrammer.org/post/2695/springboot2-simple-jpa-board/
- Git
- https://github.com/codej99/SpringRestApi/tree/feature/board
- SpringBoot2로 Rest api 만들기(15) Redis로 api 결과 캐싱(Caching)처리
- Document
- https://daddyprogrammer.org/post/3870/spring-rest-api-redis-caching/
- Git
- https://github.com/codej99/SpringRestApi/tree/cache-data-redis

View File

@@ -25,6 +25,10 @@ dependencies {
implementation 'org.springframework.boot:spring-boot-starter-freemarker'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-actuator'
implementation 'org.springframework.boot:spring-boot-starter-data-redis'
//embedded-redis
implementation 'it.ozimov:embedded-redis:0.7.2'
implementation 'io.jsonwebtoken:jjwt:0.9.1'
implementation 'io.springfox:springfox-swagger2:2.6.1'
implementation 'io.springfox:springfox-swagger-ui:2.6.1'

66
deploy.sh Normal file
View File

@@ -0,0 +1,66 @@
#!/bin/bash
PROFILE=$1
PROJECT=SpringRestApi
PROJECT_HOME=/home/happydaddy/${PROJECT}
JAR_PATH=${PROJECT_HOME}/build/libs/api-0.0.1-SNAPSHOT.jar
SVR_LIST=server_${PROFILE}.list
SERVERS=`cat $SVR_LIST`
DEPLOY_PATH=/home/ec2-user/app
AWS_ID=ec2-user
DATE=`date +%Y-%m-%d-%H-%M-%S`
JAVA_OPTS="-XX:MaxMetaspaceSize=128m -XX:+UseG1GC -Xss1024k -Xms128m -Xmx128m -Dfile.encoding=UTF-8"
PEM=AwsFreetierKeyPair.pem
PORT=8083
echo Deploy Start
for server in $SERVERS; do
echo Target server - $server
# Target Server에 배포 디렉터리 생성
ssh -i $PEM $AWS_ID@$server "mkdir -p $DEPLOY_PATH/dist"
# Target Server에 jar 이동
echo 'Executable Jar Copying...'
scp -i $PEM $JAR_PATH $AWS_ID@$server:~/app/dist/$PROJECT-$DATE.jar
# 이동한 jar파일의 바로가기(SymbolicLink)생성
ssh -i $PEM $AWS_ID@$server "ln -Tfs $DEPLOY_PATH/dist/$PROJECT-$DATE.jar $DEPLOY_PATH/$PROJECT"
# 현재 실행중인 서버 PID 조회
runPid=$(ssh -i $PEM $AWS_ID@$server pgrep -f $PROJECT)
if [ -z $runPid ]; then
echo "No servers are running"
fi
# 현재 실행중인 서버의 포트를 조회. 추가로 실행할 서버의 포트 선정
runPortCount=$(ssh -i $PEM $AWS_ID@$server ps -ef | grep $PROJECT | grep -v grep | grep $PORT | wc -l)
if [ $runPortCount -gt 0 ]; then
PORT=8084
fi
echo "Server $PORT Starting..."
# 새로운 서버 실행
ssh -i $PEM $AWS_ID@$server "nohup java -jar -Dserver.port=$PORT -Dspring.profiles.active=$PROFILE $JAVA_OPTS $DEPLOY_PATH/$PROJECT < /dev/null > std.out 2> std.err &"
# 새롭게 실행한 서버의 health check
echo "Health check $PORT"
for retry in {1..10}
do
health=$(ssh -i $PEM $AWS_ID@$server curl -s http://localhost:$PORT/actuator/health)
checkCount=$(echo $health | grep 'UP' | wc -l)
if [ $checkCount -ge 1 ]; then
echo "Server $PORT Started Normaly"
# 기존 서버 Stop / Nginx 포트 변경 후 리스타트
if [ $runPid -gt 0 ]; then
echo "Server $runPid Stop"
ssh -i $PEM $AWS_ID@$server "kill -TERM $runPid"
sleep 5
echo "Nginx Port Change"
ssh -i $PEM $AWS_ID@$server "echo 'set \$service_addr http://127.0.0.1:$PORT;' | sudo tee /etc/nginx/conf.d/service_addr.inc"
echo "Nginx reload"
ssh -i $PEM $AWS_ID@$server "sudo service nginx reload"
fi
break;
else
echo "Check - false"
fi
sleep 5
done
if [ $retry -eq 10 ]; then
echo "Deploy Fail"
fi
done
echo Deploy End

View File

@@ -1,12 +1,17 @@
package com.rest.api;
import com.rest.api.config.GracefulShutdown;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.client.RestTemplate;
@EnableJpaAuditing
@SpringBootApplication
public class SpringRestApiApplication {
public static void main(String[] args) {
@@ -22,4 +27,16 @@ public class SpringRestApiApplication {
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
@Bean
public GracefulShutdown gracefulShutdown() {
return new GracefulShutdown();
}
@Bean
public ConfigurableServletWebServerFactory webServerFactory(final GracefulShutdown gracefulShutdown) {
TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
factory.addConnectorCustomizers(gracefulShutdown);
return factory;
}
}

View File

@@ -26,7 +26,7 @@ public class ExceptionAdvice {
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
protected CommonResult defaultException(HttpServletRequest request, Exception e) {
// 예외 처리의 메시지를 MessageSource에서 가져오도록 수정
return responseService.getFailResult(Integer.valueOf(getMessage("unKnown.code")), getMessage("unKnown.msg"));
return responseService.getFailResult(Integer.valueOf(getMessage("unKnown.code")), getMessage("unKnown.msg") + "(" + e.getMessage() + ")");
}
@ExceptionHandler(CUserNotFoundException.class)
@@ -48,7 +48,7 @@ public class ExceptionAdvice {
}
@ExceptionHandler(AccessDeniedException.class)
@ResponseStatus(HttpStatus.UNAUTHORIZED)
@ResponseStatus(HttpStatus.FORBIDDEN)
public CommonResult accessDeniedException(HttpServletRequest request, AccessDeniedException e) {
return responseService.getFailResult(Integer.valueOf(getMessage("accessDenied.code")), getMessage("accessDenied.msg"));
}
@@ -65,10 +65,23 @@ public class ExceptionAdvice {
return responseService.getFailResult(Integer.valueOf(getMessage("existingUser.code")), getMessage("existingUser.msg"));
}
@ExceptionHandler(CNotOwnerException.class)
@ResponseStatus(HttpStatus.NON_AUTHORITATIVE_INFORMATION)
public CommonResult notOwnerException(HttpServletRequest request, CNotOwnerException e) {
return responseService.getFailResult(Integer.valueOf(getMessage("notOwner.code")), getMessage("notOwner.msg"));
}
@ExceptionHandler(CResourceNotExistException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public CommonResult resourceNotExistException(HttpServletRequest request, CResourceNotExistException e) {
return responseService.getFailResult(Integer.valueOf(getMessage("resourceNotExist.code")), getMessage("resourceNotExist.msg"));
}
// code정보에 해당하는 메시지를 조회합니다.
private String getMessage(String code) {
return getMessage(code, null);
}
// code정보, 추가 argument로 현재 locale에 맞는 메시지를 조회합니다.
private String getMessage(String code, Object[] args) {
return messageSource.getMessage(code, args, LocaleContextHolder.getLocale());

View File

@@ -0,0 +1,18 @@
package com.rest.api.advice.exception;
public class CNotOwnerException extends RuntimeException {
private static final long serialVersionUID = 2241549550934267615L;
public CNotOwnerException(String msg, Throwable t) {
super(msg, t);
}
public CNotOwnerException(String msg) {
super(msg);
}
public CNotOwnerException() {
super();
}
}

View File

@@ -0,0 +1,15 @@
package com.rest.api.advice.exception;
public class CResourceNotExistException extends RuntimeException {
public CResourceNotExistException(String msg, Throwable t) {
super(msg, t);
}
public CResourceNotExistException(String msg) {
super(msg);
}
public CResourceNotExistException() {
super();
}
}

View File

@@ -0,0 +1,14 @@
package com.rest.api.common;
public class CacheKey {
public static final int DEFAULT_EXPIRE_SEC = 60; // 1 minutes
public static final String USER = "user";
public static final int USER_EXPIRE_SEC = 60 * 5; // 5 minutes
public static final String BOARD = "board";
public static final int BOARD_EXPIRE_SEC = 60 * 10; // 10 minutes
public static final String POST = "post";
public static final String POSTS = "posts";
public static final int POST_EXPIRE_SEC = 60 * 5; // 5 minutes
}

View File

@@ -0,0 +1,35 @@
package com.rest.api.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import redis.embedded.RedisServer;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
/**
* 로컬 환경일경우 내장 레디스가 실행된다.
*/
@Profile("local")
@Configuration
public class EmbeddedRedisConfig {
@Value("${spring.redis.port}")
private int redisPort;
private RedisServer redisServer;
@PostConstruct
public void redisServer() {
redisServer = new RedisServer(redisPort);
redisServer.start();
}
@PreDestroy
public void stopRedis() {
if (redisServer != null) {
redisServer.stop();
}
}
}

View File

@@ -0,0 +1,50 @@
package com.rest.api.config;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.connector.Connector;
import org.springframework.boot.web.embedded.tomcat.TomcatConnectorCustomizer;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
@Slf4j
public class GracefulShutdown implements TomcatConnectorCustomizer, ApplicationListener<ContextClosedEvent> {
private static final int TIMEOUT = 30;
private volatile Connector connector;
@Override
public void customize(Connector connector) {
this.connector = connector;
}
@Override
public void onApplicationEvent(ContextClosedEvent event) {
this.connector.pause();
Executor executor = this.connector.getProtocolHandler().getExecutor();
if (executor instanceof ThreadPoolExecutor) {
try {
ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) executor;
threadPoolExecutor.shutdown();
if (!threadPoolExecutor.awaitTermination(TIMEOUT, TimeUnit.SECONDS)) {
log.warn("Tomcat thread pool did not shut down gracefully within "
+ TIMEOUT + " seconds. Proceeding with forceful shutdown");
threadPoolExecutor.shutdownNow();
if (!threadPoolExecutor.awaitTermination(TIMEOUT, TimeUnit.SECONDS)) {
log.error("Tomcat thread pool did not terminate");
}
} else {
log.info("Tomcat thread pool has been gracefully shutdown");
}
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}
}

View File

@@ -0,0 +1,49 @@
package com.rest.api.config;
import com.rest.api.common.CacheKey;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.CacheKeyPrefix;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
@RequiredArgsConstructor
@EnableCaching
@Configuration
public class RedisConfig {
@Bean(name = "cacheManager")
public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig()
.disableCachingNullValues()
.entryTtl(Duration.ofSeconds(CacheKey.DEFAULT_EXPIRE_SEC))
.computePrefixWith(CacheKeyPrefix.simple())
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
Map<String, RedisCacheConfiguration> cacheConfigurations = new HashMap<>();
// 캐시 default 유효시간 설정
cacheConfigurations.put(CacheKey.USER, RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofSeconds(CacheKey.USER_EXPIRE_SEC)));
cacheConfigurations.put(CacheKey.BOARD, RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofSeconds(CacheKey.BOARD_EXPIRE_SEC)));
cacheConfigurations.put(CacheKey.POST, RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofSeconds(CacheKey.POST_EXPIRE_SEC)));
cacheConfigurations.put(CacheKey.POSTS, RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofSeconds(CacheKey.POST_EXPIRE_SEC)));
return RedisCacheManager.RedisCacheManagerBuilder.fromConnectionFactory(connectionFactory).cacheDefaults(configuration)
.withInitialCacheConfigurations(cacheConfigurations).build();
}
}

View File

@@ -5,8 +5,6 @@ import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@@ -16,9 +14,7 @@ import java.io.IOException;
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException exception) throws IOException,
ServletException {
RequestDispatcher dispatcher = request.getRequestDispatcher("/exception/accessdenied");
dispatcher.forward(request, response);
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException exception) throws IOException {
response.sendRedirect("/exception/accessdenied");
}
}
}

View File

@@ -5,8 +5,6 @@ import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@@ -14,11 +12,8 @@ import java.io.IOException;
@Slf4j
@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException ex) throws IOException,
ServletException {
RequestDispatcher dispatcher = request.getRequestDispatcher("/exception/entrypoint");
dispatcher.forward(request, response);
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException ex) throws IOException {
response.sendRedirect("/exception/entrypoint");
}
}
}

View File

@@ -32,8 +32,8 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
.and()
.authorizeRequests() // 다음 리퀘스트에 대한 사용권한 체크
.antMatchers("/*/signin", "/*/signin/**", "/*/signup", "/*/signup/**", "/social/**").permitAll() // 가입 및 인증 주소는 누구나 접근가능
.antMatchers(HttpMethod.GET, "/helloworld/**").permitAll() // hellowworld로 시작하는 GET요청 리소스는 누구나 접근가능
.anyRequest().hasRole("USER") // 그외 나머지 요청은 모두 인증된 회원만 접근 가능
.antMatchers(HttpMethod.GET, "/exception/**", "/helloworld/**","/actuator/health", "/v1/board/**", "/favicon.ico").permitAll() // 등록한 GET요청 리소스는 누구나 접근가능
.anyRequest().hasRole("USER") // 그외 나머지 요청은 모두 인증된 회원만 접근 가능
.and()
.exceptionHandling().accessDeniedHandler(new CustomAccessDeniedHandler())
.and()

View File

@@ -11,7 +11,7 @@ import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class HelloController {
private static final String HELLO = "helloworld";
private static final String HELLO = "helloworld-nice to meet you";
@Setter
@Getter
@@ -37,6 +37,13 @@ public class HelloController {
@GetMapping(value = "/helloworld/page")
public String helloworld() {
return HELLO;
return "helloworld";
}
@GetMapping("/helloworld/long-process")
@ResponseBody
public String pause() throws InterruptedException {
Thread.sleep(10000);
return "Process finished";
}
}

View File

@@ -51,12 +51,12 @@ public class UserController {
@ApiOperation(value = "회원 수정", notes = "회원정보를 수정한다")
@PutMapping(value = "/user")
public SingleResult<User> modify(
@ApiParam(value = "회원번호", required = true) @RequestParam long msrl,
@ApiParam(value = "회원이름", required = true) @RequestParam String name) {
User user = User.builder()
.msrl(msrl)
.name(name)
.build();
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String id = authentication.getName();
User user = userJpaRepo.findByUid(id).orElseThrow(CUserNotFoundException::new);
user.setName(name);
return responseService.getSingleResult(userJpaRepo.save(user));
}

View File

@@ -0,0 +1,82 @@
package com.rest.api.controller.v1.board;
import com.rest.api.entity.board.Board;
import com.rest.api.entity.board.Post;
import com.rest.api.model.board.ParamsPost;
import com.rest.api.model.response.CommonResult;
import com.rest.api.model.response.ListResult;
import com.rest.api.model.response.SingleResult;
import com.rest.api.service.ResponseService;
import com.rest.api.service.board.BoardService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
@Api(tags = {"3. Board"})
@RequiredArgsConstructor
@RestController
@RequestMapping(value = "/v1/board")
public class BoardController {
private final BoardService boardService;
private final ResponseService responseService;
@ApiOperation(value = "게시판 정보 조회", notes = "게시판 정보를 조회한다.")
@GetMapping(value = "/{boardName}")
public SingleResult<Board> boardInfo(@PathVariable String boardName) {
return responseService.getSingleResult(boardService.findBoard(boardName));
}
@ApiOperation(value = "게시글 리스트", notes = "게시글 리스트를 조회한다.")
@GetMapping(value = "/{boardName}/posts")
public ListResult<Post> posts(@PathVariable String boardName) {
return responseService.getListResult(boardService.findPosts(boardName));
}
@ApiImplicitParams({
@ApiImplicitParam(name = "X-AUTH-TOKEN", value = "로그인 성공 후 access_token", required = true, dataType = "String", paramType = "header")
})
@ApiOperation(value = "게시글 작성", notes = "게시글을 작성한다.")
@PostMapping(value = "/{boardName}")
public SingleResult<Post> post(@PathVariable String boardName, @Valid @ModelAttribute ParamsPost post) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String uid = authentication.getName();
return responseService.getSingleResult(boardService.writePost(uid, boardName, post));
}
@ApiOperation(value = "게시글 상세", notes = "게시글 상세정보를 조회한다.")
@GetMapping(value = "/post/{postId}")
public SingleResult<Post> post(@PathVariable long postId) {
return responseService.getSingleResult(boardService.getPost(postId));
}
@ApiImplicitParams({
@ApiImplicitParam(name = "X-AUTH-TOKEN", value = "로그인 성공 후 access_token", required = true, dataType = "String", paramType = "header")
})
@ApiOperation(value = "게시글 수정", notes = "게시판의 글을 수정한다.")
@PutMapping(value = "/post/{postId}")
public SingleResult<Post> post(@PathVariable long postId, @Valid @ModelAttribute ParamsPost post) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String uid = authentication.getName();
return responseService.getSingleResult(boardService.updatePost(postId, uid, post));
}
@ApiImplicitParams({
@ApiImplicitParam(name = "X-AUTH-TOKEN", value = "로그인 성공 후 access_token", required = true, dataType = "String", paramType = "header")
})
@ApiOperation(value = "게시글 삭제", notes = "게시글을 삭제한다.")
@DeleteMapping(value = "/post/{postId}")
public CommonResult deletePost(@PathVariable long postId) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String uid = authentication.getName();
boardService.deletePost(postId, uid);
return responseService.getSuccessResult();
}
}

View File

@@ -1,7 +1,10 @@
package com.rest.api.entity;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.rest.api.entity.common.CommonDateEntity;
import lombok.*;
import org.hibernate.annotations.Proxy;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
@@ -15,13 +18,16 @@ import java.util.stream.Collectors;
@Builder // builder를 사용할수 있게 합니다.
@Entity // jpa entity임을 알립니다.
@Getter // user 필드값의 getter를 자동으로 생성합니다.
@Setter
@NoArgsConstructor // 인자없는 생성자를 자동으로 생성합니다.
@AllArgsConstructor // 인자를 모두 갖춘 생성자를 자동으로 생성합니다.
@Table(name = "user") // 'user' 테이블과 매핑됨을 명시
public class User implements UserDetails {
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) // Post Entity에서 User와의 관계를 Json으로 변환시 오류 방지를 위한 코드
@Proxy(lazy = false)
public class User extends CommonDateEntity implements UserDetails {
@Id // pk
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long msrl;
private Long msrl;
@Column(nullable = false, unique = true, length = 50)
private String uid;
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)

View File

@@ -0,0 +1,19 @@
package com.rest.api.entity.board;
import com.rest.api.entity.common.CommonDateEntity;
import lombok.Getter;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.io.Serializable;
@Entity
@Getter
@NoArgsConstructor
public class Board extends CommonDateEntity implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long boardId;
@Column(nullable = false, length = 100)
private String name;
}

View File

@@ -0,0 +1,59 @@
package com.rest.api.entity.board;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.rest.api.entity.User;
import com.rest.api.entity.common.CommonDateEntity;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.hibernate.annotations.Proxy;
import javax.persistence.*;
import java.io.Serializable;
@Entity
@Getter
@Setter
@NoArgsConstructor
public class Post extends CommonDateEntity implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long postId;
@Column(nullable = false, length = 50)
private String author;
@Column(nullable = false, length = 100)
private String title;
@Column(length = 500)
private String content;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "board_id")
private Board board; // 게시글 - 게시판의 관계 - N:1
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "msrl")
private User user; // 게시글 - 회원의 관계 - N:1
// Join 테이블이 Json결과에 표시되지 않도록 처리.
@JsonIgnore
public Board getBoard() {
return board;
}
// 생성자
public Post(User user, Board board, String author, String title, String content) {
this.user = user;
this.board = board;
this.author = author;
this.title = title;
this.content = content;
}
// 수정시 데이터 처리
public Post setUpdate(String author, String title, String content) {
this.author = author;
this.title = title;
this.content = content;
return this;
}
}

View File

@@ -0,0 +1,20 @@
package com.rest.api.entity.common;
import lombok.Getter;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.EntityListeners;
import javax.persistence.MappedSuperclass;
import java.time.LocalDateTime;
@Getter
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public abstract class CommonDateEntity {
@CreatedDate
private LocalDateTime createdAt;
@LastModifiedDate
private LocalDateTime modifiedAt;
}

View File

@@ -0,0 +1,26 @@
package com.rest.api.model.board;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Size;
@Getter
@Setter
@NoArgsConstructor
public class ParamsPost {
@NotEmpty
@Size(min = 2, max = 50)
@ApiModelProperty(value = "작성자명", required = true)
private String author;
@NotEmpty
@Size(min = 2, max = 100)
@ApiModelProperty(value = "제목", required = true)
private String title;
@Size(min = 2, max = 500)
@ApiModelProperty(value = "내용", required = true)
private String content;
}

View File

@@ -0,0 +1,8 @@
package com.rest.api.repo.board;
import com.rest.api.entity.board.Board;
import org.springframework.data.jpa.repository.JpaRepository;
public interface BoardJpaRepo extends JpaRepository<Board, Long> {
Board findByName(String name);
}

View File

@@ -0,0 +1,11 @@
package com.rest.api.repo.board;
import com.rest.api.entity.board.Board;
import com.rest.api.entity.board.Post;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface PostJpaRepo extends JpaRepository<Post, Long> {
List<Post> findByBoard(Board board);
}

View File

@@ -0,0 +1,87 @@
package com.rest.api.service.board;
import com.rest.api.advice.exception.CNotOwnerException;
import com.rest.api.advice.exception.CResourceNotExistException;
import com.rest.api.advice.exception.CUserNotFoundException;
import com.rest.api.common.CacheKey;
import com.rest.api.entity.User;
import com.rest.api.entity.board.Board;
import com.rest.api.entity.board.Post;
import com.rest.api.model.board.ParamsPost;
import com.rest.api.repo.UserJpaRepo;
import com.rest.api.repo.board.BoardJpaRepo;
import com.rest.api.repo.board.PostJpaRepo;
import com.rest.api.service.cache.CacheSevice;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.List;
import java.util.Optional;
@Slf4j
@Service
@Transactional
@RequiredArgsConstructor
public class BoardService {
private final BoardJpaRepo boardJpaRepo;
private final PostJpaRepo postJpaRepo;
private final UserJpaRepo userJpaRepo;
private final CacheSevice cacheSevice;
// 게시판 이름으로 게시판을 조회. 없을경우 CResourceNotExistException 처리
@Cacheable(value = CacheKey.BOARD, key = "#boardName", unless = "#result == null")
public Board findBoard(String boardName) {
return Optional.ofNullable(boardJpaRepo.findByName(boardName)).orElseThrow(CResourceNotExistException::new);
}
// 게시판 이름으로 게시글 리스트 조회.
@Cacheable(value = CacheKey.POSTS, key = "#boardName", unless = "#result == null")
public List<Post> findPosts(String boardName) {
return postJpaRepo.findByBoard(findBoard(boardName));
}
// 게시글ID로 게시글 단건 조회. 없을경우 CResourceNotExistException 처리
@Cacheable(value = CacheKey.POST, key = "#postId", unless = "#result == null")
public Post getPost(long postId) {
return postJpaRepo.findById(postId).orElseThrow(CResourceNotExistException::new);
}
// 게시글을 등록합니다. 게시글의 회원UID가 조회되지 않으면 CUserNotFoundException 처리합니다.
@CacheEvict(value = CacheKey.POSTS, key = "#boardName")
public Post writePost(String uid, String boardName, ParamsPost paramsPost) {
Board board = findBoard(boardName);
Post post = new Post(userJpaRepo.findByUid(uid).orElseThrow(CUserNotFoundException::new), board, paramsPost.getAuthor(), paramsPost.getTitle(), paramsPost.getContent());
return postJpaRepo.save(post);
}
// 게시글을 수정합니다. 게시글 등록자와 로그인 회원정보가 틀리면 CNotOwnerException 처리합니다.
//@CachePut(value = CacheKey.POST, key = "#postId") 갱신된 정보만 캐시할경우에만 사용!
public Post updatePost(long postId, String uid, ParamsPost paramsPost) {
Post post = getPost(postId);
User user = post.getUser();
if (!uid.equals(user.getUid()))
throw new CNotOwnerException();
// 영속성 컨텍스트의 변경감지(dirty checking) 기능에 의해 조회한 Post내용을 변경만 해도 Update쿼리가 실행됩니다.
post.setUpdate(paramsPost.getAuthor(), paramsPost.getTitle(), paramsPost.getContent());
cacheSevice.deleteBoardCache(post.getPostId(), post.getBoard().getName());
return post;
}
// 게시글을 삭제합니다. 게시글 등록자와 로그인 회원정보가 틀리면 CNotOwnerException 처리합니다.
public boolean deletePost(long postId, String uid) {
Post post = getPost(postId);
User user = post.getUser();
if (!uid.equals(user.getUid()))
throw new CNotOwnerException();
postJpaRepo.delete(post);
cacheSevice.deleteBoardCache(post.getPostId(), post.getBoard().getName());
return true;
}
}

View File

@@ -0,0 +1,21 @@
package com.rest.api.service.cache;
import com.rest.api.common.CacheKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
@Slf4j
@Service
public class CacheSevice {
@Caching(evict = {
@CacheEvict(value = CacheKey.POST, key = "#postId"),
@CacheEvict(value = CacheKey.POSTS, key = "#boardName")
})
public boolean deleteBoardCache(long postId, String boardName) {
log.debug("deleteBoardCache - postId {}, boardName {}", postId, boardName);
return true;
}
}

View File

@@ -1,8 +1,10 @@
package com.rest.api.service.security;
import com.rest.api.advice.exception.CUserNotFoundException;
import com.rest.api.common.CacheKey;
import com.rest.api.repo.UserJpaRepo;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;
@@ -13,6 +15,7 @@ public class CustomUserDetailService implements UserDetailsService {
private final UserJpaRepo userJpaRepo;
@Cacheable(value = CacheKey.USER, key = "#userPk", unless = "#result == null")
public UserDetails loadUserByUsername(String userPk) {
return userJpaRepo.findById(Long.valueOf(userPk)).orElseThrow(CUserNotFoundException::new);
}

View File

@@ -2,17 +2,17 @@ logging:
level:
root: warn
com.rest.api: info
path: /home/ec2-user/api/log
path: /home/ec2-user/app/log
file:
max-history: 7
spring:
profiles: alpha
datasource:
url: jdbc:mysql://127.0.0.1:33060/daddyprogrammer?useUnicode=true&autoReconnect=true&characterEncoding=utf8&allowMultiQueries=true&useSSL=false
url: jdbc:mysql://127.0.0.1:33060/daddyprogrammer?useUnicode=true&autoReconnect=true&characterEncoding=utf8&allowMultiQueries=true&useSSL=false&serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
username: happydaddy
password: daddy1004
password: daddy!@#1004
jpa:
database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
properties.hibernate:
@@ -21,4 +21,7 @@ spring:
showSql: true
generate-ddl: false
url:
base: http://dev-api.daddyprogrammer.org
base: http://dev-api.daddyprogrammer.org
redis:
host: Standalone Redis 호스트
port: Standalone Redis 포트

View File

@@ -1,6 +1,6 @@
logging:
level:
root: warn
root: info
com.rest.api: debug
spring:
@@ -18,3 +18,6 @@ spring:
generate-ddl: true
url:
base: http://localhost:8080
redis:
host: localhost
port: 6379

View File

@@ -18,4 +18,10 @@ communicationError:
msg: "An error occurred during communication."
existingUser:
code: "-1005"
msg: "You are an existing member."
msg: "You are an existing member."
notOwner:
code: "-1006"
msg: "You are not the owner of this resource."
resourceNotExist:
code: "-1007"
msg: "This resource does not exist."

View File

@@ -1,6 +1,6 @@
unKnown:
code: "-9999"
msg: "알수 없는 오류가 발생하였습니다."
msg: "알수없는 오류가 발생하였습니다."
userNotFound:
code: "-1000"
msg: "존재하지 않는 회원입니다."
@@ -18,4 +18,10 @@ communicationError:
msg: "통신 중 오류가 발생하였습니다."
existingUser:
code: "-1005"
msg: "이미 가입한 회원입니다. 로그인을 해주십시오."
msg: "이미 가입한 회원입니다. 로그인을 해주십시오."
notOwner:
code: "-1006"
msg: "해당 자원의 소유자가 아닙니다."
resourceNotExist:
code: "-1007"
msg: "요청한 자원이 존재 하지 않습니다."

View File

@@ -0,0 +1,67 @@
package com.rest.api.cache;
import com.rest.api.entity.board.Post;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class CacheRepo {
private static final String CACHE_KEY = "CACHE_TEST";
@Cacheable(value = CACHE_KEY, key = "#postId")
public Post getPost(long postId) {
Post post = new Post();
post.setPostId(postId);
post.setTitle("title_" + postId);
post.setAuthor("author_" + postId);
post.setContent("content_" + postId);
return post;
}
@CachePut(value = CACHE_KEY, key = "#post.postId")
public Post updatePost(Post post) {
return post;
}
@Cacheable(value = CACHE_KEY, key = "{#postId, #title}")
public Post getPostMultiKey(long postId, String title) {
Post post = new Post();
post.setPostId(postId);
post.setTitle("title_" + postId);
post.setAuthor("author_" + postId);
post.setContent("content_" + postId);
return post;
}
@CachePut(value = CACHE_KEY, key = "{#post.postId, #post.title}")
// @CachePut(value = CACHE_KEY, key = "{#post.postId, #post.getTitle()}")
public Post updatePostMultiKey(Post post) {
return post;
}
@CacheEvict(cacheNames = {CACHE_KEY}, allEntries = true)
public void clearCache(){}
@Cacheable(value = CACHE_KEY, key = "{#postId}", condition="#postId > 10")
public Post getPostCondition(long postId) {
Post post = new Post();
post.setPostId(postId);
post.setTitle("title_" + postId);
post.setAuthor("author_" + postId);
post.setContent("content_" + postId);
return post;
}
@Cacheable(value = CACHE_KEY, key = "T(com.rest.api.cache.CustomKeyGenerator).create(#postId, #title)")
public Post getPostKeyGenerator(long postId, String title) {
Post post = new Post();
post.setPostId(postId);
post.setTitle("title_" + postId);
post.setAuthor("author_" + postId);
post.setContent("content_" + postId);
return post;
}
}

View File

@@ -0,0 +1,67 @@
package com.rest.api.cache;
import com.rest.api.entity.board.Post;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.*;
@RunWith(SpringRunner.class)
@SpringBootTest
public class CacheTest {
@Autowired
private CacheRepo cacheRepo;
@Test
public void cacheTest() throws Exception {
// get cache
Post post = cacheRepo.getPost(1L);
assertSame(1L, post.getPostId());
assertEquals("title_1", post.getTitle());
// update cache
post.setTitle("title_modified");
post.setContent("content_modified");
cacheRepo.updatePost(post);
// get cache
Post postModified = cacheRepo.getPost(1L);
assertEquals("title_modified", postModified.getTitle());
assertEquals("content_modified", postModified.getContent());
}
@Test
public void cacheTestMultiKey() throws Exception {
// get cache
Post post = cacheRepo.getPostMultiKey(1L, "title_1");
assertSame(1L, post.getPostId());
assertEquals("title_1", post.getTitle());
// update cache
post.setTitle("title_modified");
post.setContent("content_modified");
cacheRepo.updatePostMultiKey(post);
// get cache
Post postModified = cacheRepo.getPostMultiKey(1L, "title_modified");
assertEquals("title_modified", postModified.getTitle());
assertEquals("content_modified", postModified.getContent());
}
@Test
public void cacheTestCustomKeyGenerator() throws Exception {
// get cache
Post post = cacheRepo.getPostKeyGenerator(1L, "title_1");
assertSame(1L, post.getPostId());
assertEquals("title_1", post.getTitle());
}
@Test
public void deleteAllCache() {
cacheRepo.getPost(1L);
cacheRepo.getPost(2L);
cacheRepo.getPost(3L);
cacheRepo.getPost(4L);
cacheRepo.clearCache();
}
}

View File

@@ -0,0 +1,7 @@
package com.rest.api.cache;
public class CustomKeyGenerator {
public static Object create(Object o1, Object o2) {
return "FRONT:" + o1 + ":" + o2;
}
}

View File

@@ -47,7 +47,7 @@ public class UserControllerTest {
@Before
public void setUp() throws Exception {
userJpaRepo.save(User.builder().uid("happydaddy@naver.com").name("happydaddy").password(passwordEncoder.encode("1234")).roles(Collections.singletonList("ROLE_USER")).build());
//userJpaRepo.save(User.builder().uid("happydaddy@naver.com").name("happydaddy").password(passwordEncoder.encode("1234")).roles(Collections.singletonList("ROLE_USER")).build());
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("id", "happydaddy@naver.com");
params.add("password", "1234");
@@ -75,8 +75,8 @@ public class UserControllerTest {
.get("/v1/users")
.header("X-AUTH-TOKEN", "XXXXXXXXXX"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(forwardedUrl("/exception/entrypoint"));
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrl("/exception/entrypoint"));
}
@Test
@@ -86,8 +86,8 @@ public class UserControllerTest {
.get("/v1/users"))
//.header("X-AUTH-TOKEN", token))
.andDo(print())
.andExpect(status().isOk())
.andExpect(forwardedUrl("/exception/accessdenied"));
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrl("/exception/accessdenied"));
}
@Test
@@ -115,7 +115,7 @@ public class UserControllerTest {
@Test
public void modify() throws Exception {
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("msrl", "1");
params.add("uid", "happydaddy@naver.com");
params.add("name", "행복전도사");
mockMvc.perform(MockMvcRequestBuilders
.put("/v1/user")
@@ -123,7 +123,8 @@ public class UserControllerTest {
.params(params))
.andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("$.success").value(true));
.andExpect(jsonPath("$.success").value(true))
.andExpect(jsonPath("$.data.name").value("행복전도사"));
}
@Test

View File

@@ -0,0 +1,5 @@
package com.rest.api.controller.v1.board;
public class BoardControllerTest {
}