Compare commits
13 Commits
feature/se
...
jpa_study
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
73703c10a5 | ||
|
|
e736b92975 | ||
|
|
a03a263adf | ||
|
|
c6110eb806 | ||
|
|
0bf89cc08b | ||
|
|
002ac18e4a | ||
|
|
c25984207b | ||
|
|
2a0a9721ed | ||
|
|
69f3053371 | ||
|
|
189e741ded | ||
|
|
2e5e6be283 | ||
|
|
0bcbc81775 | ||
|
|
dac4f282e3 |
18
README.md
18
README.md
@@ -97,3 +97,21 @@ alter table user_roles
|
|||||||
- https://daddyprogrammer.org/post/1012/springboot2-rest-api-social-login-kakao/
|
- https://daddyprogrammer.org/post/1012/springboot2-rest-api-social-login-kakao/
|
||||||
- Git
|
- 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
|
||||||
|
|||||||
@@ -6,10 +6,12 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
|
|||||||
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
|
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
|
||||||
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
|
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
|
||||||
import org.springframework.context.annotation.Bean;
|
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.factory.PasswordEncoderFactories;
|
||||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||||
import org.springframework.web.client.RestTemplate;
|
import org.springframework.web.client.RestTemplate;
|
||||||
|
|
||||||
|
@EnableJpaAuditing
|
||||||
@SpringBootApplication
|
@SpringBootApplication
|
||||||
public class SpringRestApiApplication {
|
public class SpringRestApiApplication {
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ public class ExceptionAdvice {
|
|||||||
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
|
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||||
protected CommonResult defaultException(HttpServletRequest request, Exception e) {
|
protected CommonResult defaultException(HttpServletRequest request, Exception e) {
|
||||||
// 예외 처리의 메시지를 MessageSource에서 가져오도록 수정
|
// 예외 처리의 메시지를 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)
|
@ExceptionHandler(CUserNotFoundException.class)
|
||||||
@@ -48,7 +48,7 @@ public class ExceptionAdvice {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@ExceptionHandler(AccessDeniedException.class)
|
@ExceptionHandler(AccessDeniedException.class)
|
||||||
@ResponseStatus(HttpStatus.UNAUTHORIZED)
|
@ResponseStatus(HttpStatus.FORBIDDEN)
|
||||||
public CommonResult accessDeniedException(HttpServletRequest request, AccessDeniedException e) {
|
public CommonResult accessDeniedException(HttpServletRequest request, AccessDeniedException e) {
|
||||||
return responseService.getFailResult(Integer.valueOf(getMessage("accessDenied.code")), getMessage("accessDenied.msg"));
|
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"));
|
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정보에 해당하는 메시지를 조회합니다.
|
// code정보에 해당하는 메시지를 조회합니다.
|
||||||
private String getMessage(String code) {
|
private String getMessage(String code) {
|
||||||
return getMessage(code, null);
|
return getMessage(code, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
// code정보, 추가 argument로 현재 locale에 맞는 메시지를 조회합니다.
|
// code정보, 추가 argument로 현재 locale에 맞는 메시지를 조회합니다.
|
||||||
private String getMessage(String code, Object[] args) {
|
private String getMessage(String code, Object[] args) {
|
||||||
return messageSource.getMessage(code, args, LocaleContextHolder.getLocale());
|
return messageSource.getMessage(code, args, LocaleContextHolder.getLocale());
|
||||||
|
|||||||
@@ -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();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,8 +5,6 @@ import org.springframework.security.core.AuthenticationException;
|
|||||||
import org.springframework.security.web.AuthenticationEntryPoint;
|
import org.springframework.security.web.AuthenticationEntryPoint;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
import javax.servlet.RequestDispatcher;
|
|
||||||
import javax.servlet.ServletException;
|
|
||||||
import javax.servlet.http.HttpServletRequest;
|
import javax.servlet.http.HttpServletRequest;
|
||||||
import javax.servlet.http.HttpServletResponse;
|
import javax.servlet.http.HttpServletResponse;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
@@ -14,10 +12,8 @@ import java.io.IOException;
|
|||||||
@Slf4j
|
@Slf4j
|
||||||
@Component
|
@Component
|
||||||
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
|
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException ex) throws IOException,
|
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException ex) throws IOException {
|
||||||
ServletException {
|
|
||||||
response.sendRedirect("/exception/entrypoint");
|
response.sendRedirect("/exception/entrypoint");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -32,8 +32,7 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
|
|||||||
.and()
|
.and()
|
||||||
.authorizeRequests() // 다음 리퀘스트에 대한 사용권한 체크
|
.authorizeRequests() // 다음 리퀘스트에 대한 사용권한 체크
|
||||||
.antMatchers("/*/signin", "/*/signin/**", "/*/signup", "/*/signup/**", "/social/**").permitAll() // 가입 및 인증 주소는 누구나 접근가능
|
.antMatchers("/*/signin", "/*/signin/**", "/*/signup", "/*/signup/**", "/social/**").permitAll() // 가입 및 인증 주소는 누구나 접근가능
|
||||||
.antMatchers(HttpMethod.GET, "/exception/**","/helloworld/**").permitAll() // hellowworld로 시작하는 GET요청 리소스는 누구나 접근가능
|
.antMatchers(HttpMethod.GET, "/exception/**", "/helloworld/**","/actuator/health", "/v1/board/**", "/favicon.ico").permitAll() // 등록한 GET요청 리소스는 누구나 접근가능
|
||||||
.antMatchers(HttpMethod.GET, "/helloworld/**","/actuator/health").permitAll() // hellowworld로 시작하는 GET요청 리소스는 누구나 접근가능
|
|
||||||
.anyRequest().hasRole("USER") // 그외 나머지 요청은 모두 인증된 회원만 접근 가능
|
.anyRequest().hasRole("USER") // 그외 나머지 요청은 모두 인증된 회원만 접근 가능
|
||||||
.and()
|
.and()
|
||||||
.exceptionHandling().accessDeniedHandler(new CustomAccessDeniedHandler())
|
.exceptionHandling().accessDeniedHandler(new CustomAccessDeniedHandler())
|
||||||
|
|||||||
@@ -1,19 +1,27 @@
|
|||||||
package com.rest.api.controller;
|
package com.rest.api.controller;
|
||||||
|
|
||||||
|
import com.rest.api.entity.Employ;
|
||||||
|
import com.rest.api.entity.Member;
|
||||||
|
import com.rest.api.repo.EmployJpaRepo;
|
||||||
|
import com.rest.api.repo.MemberJpaRepo;
|
||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.Setter;
|
import lombok.Setter;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.stereotype.Controller;
|
import org.springframework.stereotype.Controller;
|
||||||
import org.springframework.web.bind.annotation.GetMapping;
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
import org.springframework.web.bind.annotation.RequestMapping;
|
|
||||||
import org.springframework.web.bind.annotation.ResponseBody;
|
import org.springframework.web.bind.annotation.ResponseBody;
|
||||||
|
|
||||||
|
@RequiredArgsConstructor
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@Controller
|
@Controller
|
||||||
public class HelloController {
|
public class HelloController {
|
||||||
|
|
||||||
private static final String HELLO = "helloworld-nice to meet you";
|
private static final String HELLO = "helloworld-nice to meet you";
|
||||||
|
|
||||||
|
private final EmployJpaRepo employJpaRepo;
|
||||||
|
private final MemberJpaRepo memberJpaRepo;
|
||||||
|
|
||||||
@Setter
|
@Setter
|
||||||
@Getter
|
@Getter
|
||||||
public static class Hello {
|
public static class Hello {
|
||||||
@@ -22,23 +30,27 @@ public class HelloController {
|
|||||||
|
|
||||||
@GetMapping(value = "/helloworld/string")
|
@GetMapping(value = "/helloworld/string")
|
||||||
@ResponseBody
|
@ResponseBody
|
||||||
public String helloworldString() {
|
public Employ helloworldString() {
|
||||||
|
|
||||||
|
Employ employ = Employ.builder().employee(memberJpaRepo.findById(1L).get()).build();
|
||||||
|
employ = employJpaRepo.save(employ);
|
||||||
log.debug("Helloworld");
|
log.debug("Helloworld");
|
||||||
log.info("Helloworld");
|
log.info("Helloworld");
|
||||||
return HELLO;
|
return employ;
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping(value = "/helloworld/json")
|
@GetMapping(value = "/helloworld/json")
|
||||||
@ResponseBody
|
@ResponseBody
|
||||||
public Hello helloworldJson() {
|
public Employ helloworldJson() {
|
||||||
Hello hello = new Hello();
|
return employJpaRepo.findById(2L).get();
|
||||||
hello.message = HELLO;
|
|
||||||
return hello;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping(value = "/helloworld/page")
|
@GetMapping(value = "/helloworld/page")
|
||||||
public String helloworld() {
|
public String helloworld() {
|
||||||
return HELLO;
|
memberJpaRepo.save(Member.builder().email("happydaddy@naver.com").name("happydaddy").build());
|
||||||
|
memberJpaRepo.save(Member.builder().email("angrydaddy@naver.com").name("angrydaddy").build());
|
||||||
|
return "true";
|
||||||
|
// return HELLO;
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/helloworld/long-process")
|
@GetMapping("/helloworld/long-process")
|
||||||
|
|||||||
@@ -51,12 +51,12 @@ public class UserController {
|
|||||||
@ApiOperation(value = "회원 수정", notes = "회원정보를 수정한다")
|
@ApiOperation(value = "회원 수정", notes = "회원정보를 수정한다")
|
||||||
@PutMapping(value = "/user")
|
@PutMapping(value = "/user")
|
||||||
public SingleResult<User> modify(
|
public SingleResult<User> modify(
|
||||||
@ApiParam(value = "회원번호", required = true) @RequestParam long msrl,
|
|
||||||
@ApiParam(value = "회원이름", required = true) @RequestParam String name) {
|
@ApiParam(value = "회원이름", required = true) @RequestParam String name) {
|
||||||
User user = User.builder()
|
|
||||||
.msrl(msrl)
|
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||||
.name(name)
|
String id = authentication.getName();
|
||||||
.build();
|
User user = userJpaRepo.findByUid(id).orElseThrow(CUserNotFoundException::new);
|
||||||
|
user.setName(name);
|
||||||
return responseService.getSingleResult(userJpaRepo.save(user));
|
return responseService.getSingleResult(userJpaRepo.save(user));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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();
|
||||||
|
}
|
||||||
|
}
|
||||||
29
src/main/java/com/rest/api/entity/Employ.java
Normal file
29
src/main/java/com/rest/api/entity/Employ.java
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
package com.rest.api.entity;
|
||||||
|
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Getter;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
import javax.persistence.*;
|
||||||
|
|
||||||
|
@NoArgsConstructor
|
||||||
|
@Entity
|
||||||
|
@Getter
|
||||||
|
public class Employ {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
private long employId;
|
||||||
|
@OneToOne
|
||||||
|
@JoinColumn(name = "employer_id")
|
||||||
|
private Member employer;
|
||||||
|
@OneToOne
|
||||||
|
@JoinColumn(name = "employee_id")
|
||||||
|
private Member employee;
|
||||||
|
|
||||||
|
@Builder
|
||||||
|
public Employ(Member employer, Member employee) {
|
||||||
|
this.employer = employer;
|
||||||
|
this.employee = employee;
|
||||||
|
}
|
||||||
|
}
|
||||||
28
src/main/java/com/rest/api/entity/Member.java
Normal file
28
src/main/java/com/rest/api/entity/Member.java
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
package com.rest.api.entity;
|
||||||
|
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Getter;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
import javax.persistence.*;
|
||||||
|
import java.util.Date;
|
||||||
|
|
||||||
|
@NoArgsConstructor
|
||||||
|
@Entity
|
||||||
|
@Getter
|
||||||
|
public class Member {
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
private long uid;
|
||||||
|
@Column(name = "email", unique = true)
|
||||||
|
private String email;
|
||||||
|
private String name;
|
||||||
|
private Date createDate;
|
||||||
|
|
||||||
|
@Builder
|
||||||
|
public Member(String email, String name) {
|
||||||
|
this.email = email;
|
||||||
|
this.name = name;
|
||||||
|
this.createDate = new Date();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,8 @@
|
|||||||
package com.rest.api.entity;
|
package com.rest.api.entity;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||||
|
import com.rest.api.entity.common.CommonDateEntity;
|
||||||
import lombok.*;
|
import lombok.*;
|
||||||
import org.springframework.security.core.GrantedAuthority;
|
import org.springframework.security.core.GrantedAuthority;
|
||||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||||
@@ -15,13 +17,15 @@ import java.util.stream.Collectors;
|
|||||||
@Builder // builder를 사용할수 있게 합니다.
|
@Builder // builder를 사용할수 있게 합니다.
|
||||||
@Entity // jpa entity임을 알립니다.
|
@Entity // jpa entity임을 알립니다.
|
||||||
@Getter // user 필드값의 getter를 자동으로 생성합니다.
|
@Getter // user 필드값의 getter를 자동으로 생성합니다.
|
||||||
|
@Setter
|
||||||
@NoArgsConstructor // 인자없는 생성자를 자동으로 생성합니다.
|
@NoArgsConstructor // 인자없는 생성자를 자동으로 생성합니다.
|
||||||
@AllArgsConstructor // 인자를 모두 갖춘 생성자를 자동으로 생성합니다.
|
@AllArgsConstructor // 인자를 모두 갖춘 생성자를 자동으로 생성합니다.
|
||||||
@Table(name = "user") // 'user' 테이블과 매핑됨을 명시
|
@Table(name = "user") // 'user' 테이블과 매핑됨을 명시
|
||||||
public class User implements UserDetails {
|
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) // Post Entity에서 User와의 관계를 Json으로 변환시 오류 방지를 위한 코드
|
||||||
|
public class User extends CommonDateEntity implements UserDetails {
|
||||||
@Id // pk
|
@Id // pk
|
||||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
private long msrl;
|
private Long msrl;
|
||||||
@Column(nullable = false, unique = true, length = 50)
|
@Column(nullable = false, unique = true, length = 50)
|
||||||
private String uid;
|
private String uid;
|
||||||
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
|
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
|
||||||
|
|||||||
18
src/main/java/com/rest/api/entity/board/Board.java
Normal file
18
src/main/java/com/rest/api/entity/board/Board.java
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
package com.rest.api.entity.board;
|
||||||
|
|
||||||
|
import com.rest.api.entity.common.CommonDateEntity;
|
||||||
|
import lombok.Getter;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
import javax.persistence.*;
|
||||||
|
|
||||||
|
@Entity
|
||||||
|
@Getter
|
||||||
|
@NoArgsConstructor
|
||||||
|
public class Board extends CommonDateEntity {
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
private Long boardId;
|
||||||
|
@Column(nullable = false, length = 100)
|
||||||
|
private String name;
|
||||||
|
}
|
||||||
54
src/main/java/com/rest/api/entity/board/Post.java
Normal file
54
src/main/java/com/rest/api/entity/board/Post.java
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
package com.rest.api.entity.board;
|
||||||
|
|
||||||
|
import com.rest.api.entity.User;
|
||||||
|
import com.rest.api.entity.common.CommonDateEntity;
|
||||||
|
import lombok.Getter;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
import javax.persistence.*;
|
||||||
|
|
||||||
|
@Entity
|
||||||
|
@Getter
|
||||||
|
@NoArgsConstructor
|
||||||
|
public class Post extends CommonDateEntity {
|
||||||
|
@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결과에 표시되지 않도록 처리.
|
||||||
|
protected 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
26
src/main/java/com/rest/api/model/board/ParamsPost.java
Normal file
26
src/main/java/com/rest/api/model/board/ParamsPost.java
Normal 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;
|
||||||
|
}
|
||||||
7
src/main/java/com/rest/api/repo/EmployJpaRepo.java
Normal file
7
src/main/java/com/rest/api/repo/EmployJpaRepo.java
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
package com.rest.api.repo;
|
||||||
|
|
||||||
|
import com.rest.api.entity.Employ;
|
||||||
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
|
||||||
|
public interface EmployJpaRepo extends JpaRepository<Employ, Long> {
|
||||||
|
}
|
||||||
7
src/main/java/com/rest/api/repo/MemberJpaRepo.java
Normal file
7
src/main/java/com/rest/api/repo/MemberJpaRepo.java
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
package com.rest.api.repo;
|
||||||
|
|
||||||
|
import com.rest.api.entity.Member;
|
||||||
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
|
||||||
|
public interface MemberJpaRepo extends JpaRepository<Member, Long> {
|
||||||
|
}
|
||||||
8
src/main/java/com/rest/api/repo/board/BoardJpaRepo.java
Normal file
8
src/main/java/com/rest/api/repo/board/BoardJpaRepo.java
Normal 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);
|
||||||
|
}
|
||||||
11
src/main/java/com/rest/api/repo/board/PostJpaRepo.java
Normal file
11
src/main/java/com/rest/api/repo/board/PostJpaRepo.java
Normal 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);
|
||||||
|
}
|
||||||
71
src/main/java/com/rest/api/service/board/BoardService.java
Normal file
71
src/main/java/com/rest/api/service/board/BoardService.java
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
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.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 lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import javax.transaction.Transactional;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
@Transactional
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class BoardService {
|
||||||
|
|
||||||
|
private final BoardJpaRepo boardJpaRepo;
|
||||||
|
private final PostJpaRepo postJpaRepo;
|
||||||
|
private final UserJpaRepo userJpaRepo;
|
||||||
|
|
||||||
|
// 게시판 이름으로 게시판을 조회. 없을경우 CResourceNotExistException 처리
|
||||||
|
public Board findBoard(String boardName) {
|
||||||
|
return Optional.ofNullable(boardJpaRepo.findByName(boardName)).orElseThrow(CResourceNotExistException::new);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 게시판 이름으로 게시물 리스트 조회.
|
||||||
|
public List<Post> findPosts(String boardName) {
|
||||||
|
return postJpaRepo.findByBoard(findBoard(boardName));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 게시물ID로 게시물 단건 조회. 없을경우 CResourceNotExistException 처리
|
||||||
|
public Post getPost(long postId) {
|
||||||
|
return postJpaRepo.findById(postId).orElseThrow(CResourceNotExistException::new);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 게시물을 등록합니다. 게시물의 회원UID가 조회되지 않으면 CUserNotFoundException 처리합니다.
|
||||||
|
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 처리합니다.
|
||||||
|
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();
|
||||||
|
|
||||||
|
post.setUpdate(paramsPost.getAuthor(), paramsPost.getTitle(), paramsPost.getContent());
|
||||||
|
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);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
logging:
|
logging:
|
||||||
level:
|
level:
|
||||||
root: warn
|
root: info
|
||||||
com.rest.api: debug
|
com.rest.api: debug
|
||||||
|
|
||||||
spring:
|
spring:
|
||||||
|
|||||||
@@ -19,3 +19,9 @@ communicationError:
|
|||||||
existingUser:
|
existingUser:
|
||||||
code: "-1005"
|
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."
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
unKnown:
|
unKnown:
|
||||||
code: "-9999"
|
code: "-9999"
|
||||||
msg: "알수 없는 오류가 발생하였습니다."
|
msg: "알수없는 오류가 발생하였습니다."
|
||||||
userNotFound:
|
userNotFound:
|
||||||
code: "-1000"
|
code: "-1000"
|
||||||
msg: "존재하지 않는 회원입니다."
|
msg: "존재하지 않는 회원입니다."
|
||||||
@@ -19,3 +19,9 @@ communicationError:
|
|||||||
existingUser:
|
existingUser:
|
||||||
code: "-1005"
|
code: "-1005"
|
||||||
msg: "이미 가입한 회원입니다. 로그인을 해주십시오."
|
msg: "이미 가입한 회원입니다. 로그인을 해주십시오."
|
||||||
|
notOwner:
|
||||||
|
code: "-1006"
|
||||||
|
msg: "해당 자원의 소유자가 아닙니다."
|
||||||
|
resourceNotExist:
|
||||||
|
code: "-1007"
|
||||||
|
msg: "요청한 자원이 존재 하지 않습니다."
|
||||||
@@ -47,7 +47,7 @@ public class UserControllerTest {
|
|||||||
|
|
||||||
@Before
|
@Before
|
||||||
public void setUp() throws Exception {
|
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<>();
|
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
|
||||||
params.add("id", "happydaddy@naver.com");
|
params.add("id", "happydaddy@naver.com");
|
||||||
params.add("password", "1234");
|
params.add("password", "1234");
|
||||||
@@ -75,8 +75,8 @@ public class UserControllerTest {
|
|||||||
.get("/v1/users")
|
.get("/v1/users")
|
||||||
.header("X-AUTH-TOKEN", "XXXXXXXXXX"))
|
.header("X-AUTH-TOKEN", "XXXXXXXXXX"))
|
||||||
.andDo(print())
|
.andDo(print())
|
||||||
.andExpect(status().isOk())
|
.andExpect(status().is3xxRedirection())
|
||||||
.andExpect(forwardedUrl("/exception/entrypoint"));
|
.andExpect(redirectedUrl("/exception/entrypoint"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -86,8 +86,8 @@ public class UserControllerTest {
|
|||||||
.get("/v1/users"))
|
.get("/v1/users"))
|
||||||
//.header("X-AUTH-TOKEN", token))
|
//.header("X-AUTH-TOKEN", token))
|
||||||
.andDo(print())
|
.andDo(print())
|
||||||
.andExpect(status().isOk())
|
.andExpect(status().is3xxRedirection())
|
||||||
.andExpect(forwardedUrl("/exception/accessdenied"));
|
.andExpect(redirectedUrl("/exception/accessdenied"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -115,7 +115,7 @@ public class UserControllerTest {
|
|||||||
@Test
|
@Test
|
||||||
public void modify() throws Exception {
|
public void modify() throws Exception {
|
||||||
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
|
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
|
||||||
params.add("msrl", "1");
|
params.add("uid", "happydaddy@naver.com");
|
||||||
params.add("name", "행복전도사");
|
params.add("name", "행복전도사");
|
||||||
mockMvc.perform(MockMvcRequestBuilders
|
mockMvc.perform(MockMvcRequestBuilders
|
||||||
.put("/v1/user")
|
.put("/v1/user")
|
||||||
@@ -123,7 +123,8 @@ public class UserControllerTest {
|
|||||||
.params(params))
|
.params(params))
|
||||||
.andDo(print())
|
.andDo(print())
|
||||||
.andExpect(status().isOk())
|
.andExpect(status().isOk())
|
||||||
.andExpect(jsonPath("$.success").value(true));
|
.andExpect(jsonPath("$.success").value(true))
|
||||||
|
.andExpect(jsonPath("$.data.name").value("행복전도사"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
package com.rest.api.controller.v1.board;
|
||||||
|
|
||||||
|
public class BoardControllerTest {
|
||||||
|
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user