2021-03 spring-15-mvc added

This commit is contained in:
Александр Оруджев
2021-05-24 00:17:24 +04:00
parent 5402736e76
commit 90665acc51
53 changed files with 1792 additions and 0 deletions
+24
View File
@@ -0,0 +1,24 @@
target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/build/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
+20
View File
@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>ru.otus</groupId>
<artifactId>spring-mvc-class-work</artifactId>
<version>1.0</version>
<packaging>pom</packaging>
<modules>
<module>spring-mvc-exercise</module>
<module>spring-mvc-solution-1</module>
<module>spring-mvc-solution-2</module>
<module>spring-mvc-solution-3</module>
<module>spring-mvc-solution-4</module>
</modules>
</project>
+11
View File
@@ -0,0 +1,11 @@
POST http://localhost:8080/person
Content-Type: application/json
{
"id": "1",
"name": "Gogol'"
}
###
GET http://localhost:8080/person
@@ -0,0 +1,24 @@
target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/build/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
@@ -0,0 +1,54 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>ru.otus</groupId>
<artifactId>spring-mvc-exercise</artifactId>
<version>1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.5</version>
</parent>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-keyvalue</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,28 @@
package ru.otus.spring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.map.repository.config.EnableMapRepositories;
import ru.otus.spring.domain.Person;
import ru.otus.spring.repostory.PersonRepository;
import javax.annotation.PostConstruct;
@EnableMapRepositories
@SpringBootApplication
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class);
}
@SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection")
@Autowired
private PersonRepository repository;
@PostConstruct
public void init() {
repository.save(new Person(1, "Pushkin"));
}
}
@@ -0,0 +1,20 @@
package ru.otus.spring.domain;
public class Email {
private long id;
private String email;
public Email(String email) {
this.email = email;
}
public long getId() {
return id;
}
public String getEmail() {
return email;
}
}
@@ -0,0 +1,37 @@
package ru.otus.spring.domain;
import org.springframework.data.annotation.Id;
import org.springframework.data.keyvalue.annotation.KeySpace;
@KeySpace("person")
public class Person {
@Id
private long id;
private String name;
public Person(String name) {
this.name = name;
}
public Person(long id, String name) {
this.id = id;
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@@ -0,0 +1,11 @@
package ru.otus.spring.repostory;
import org.springframework.data.repository.PagingAndSortingRepository;
import ru.otus.spring.domain.Person;
import java.util.List;
public interface PersonRepository extends PagingAndSortingRepository<Person, Long> {
List<Person> findAll();
}
@@ -0,0 +1,7 @@
package ru.otus.spring.rest;
public class NotFoundException extends RuntimeException{
public NotFoundException() {
}
}
@@ -0,0 +1,13 @@
package ru.otus.spring.rest;
import ru.otus.spring.repostory.PersonRepository;
public class PersonController {
private final PersonRepository repository;
public PersonController(PersonRepository repository) {
this.repository = repository;
}
}
@@ -0,0 +1,54 @@
/*
* Copyright 2016 Russian Post
*
* This source code is Russian Post Confidential Proprietary.
* This software is protected by copyright. All rights and titles are reserved.
* You shall not use, copy, distribute, modify, decompile, disassemble or reverse engineer the software.
* Otherwise this violation would be treated by law and would be subject to legal prosecution.
* Legal use of the software provides receipt of a license from the right name only.
*/
package ru.otus.spring.rest;
import ru.otus.spring.domain.Person;
/**
* DTO that represents Account
*/
@SuppressWarnings("all")
public class PersonDto {
private long id;
private String name;
public PersonDto() {
}
public PersonDto(long id, String name) {
this.id = id;
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static Person toDomainObject(PersonDto dto) {
return new Person(dto.getId(), dto.getName());
}
public static PersonDto toDto(Person account) {
return new PersonDto(account.getId(), account.getName());
}
}
@@ -0,0 +1,84 @@
package ru.otus.spring.rest;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.web.servlet.MockMvc;
import ru.otus.spring.domain.Person;
import ru.otus.spring.repostory.PersonRepository;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@WebMvcTest(PersonController.class)
class PersonControllerTest {
public static final String ERROR_STRING = "Таких тут нет!";
@Autowired
private MockMvc mvc;
@Autowired
private ObjectMapper mapper;
@MockBean
private PersonRepository repository;
@Test
void shouldReturnCorrectPersonsList() throws Exception {
List<Person> persons = List.of(new Person(1, "Person1"), new Person(2, "Person2"));
given(repository.findAll()).willReturn(persons);
List<PersonDto> expectedResult = persons.stream()
.map(PersonDto::toDto).collect(Collectors.toList());
mvc.perform(get("/persons/all"))
.andExpect(status().isOk())
.andExpect(content().json(mapper.writeValueAsString(expectedResult)));
}
@Test
void shouldReturnCorrectPersonByIdInRequest() throws Exception {
Person person = new Person(1, "Person1");
given(repository.findById(1L)).willReturn(Optional.of(person));
PersonDto expectedResult = PersonDto.toDto(person);
mvc.perform(get("/persons").param("id", "1"))
.andExpect(status().isOk())
.andExpect(content().json(mapper.writeValueAsString(expectedResult)));
}
@Test
void shouldReturnCorrectPersonByIdInPath() throws Exception {
Person person = new Person(1, "Person1");
given(repository.findById(1L)).willReturn(Optional.of(person));
PersonDto expectedResult = PersonDto.toDto(person);
mvc.perform(get("/persons/1"))
.andExpect(status().isOk())
.andExpect(content().json(mapper.writeValueAsString(expectedResult)));
}
@Test
void shouldReturnExpectedErrorWhenPersonNotFound() throws Exception {
given(repository.findById(1L)).willReturn(Optional.empty());
mvc.perform(get("/persons").param("id", "1"))
.andExpect(status().isBadRequest())
.andExpect(content().string(ERROR_STRING));
mvc.perform(get("/persons/1"))
.andExpect(status().isBadRequest())
.andExpect(content().string(ERROR_STRING));
}
}
@@ -0,0 +1,24 @@
target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/build/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
@@ -0,0 +1,52 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>ru.otus</groupId>
<artifactId>spring-mvc-solution-1</artifactId>
<version>1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.5</version>
</parent>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-keyvalue</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,28 @@
package ru.otus.spring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.map.repository.config.EnableMapRepositories;
import ru.otus.spring.domain.Person;
import ru.otus.spring.repostory.PersonRepository;
import javax.annotation.PostConstruct;
@EnableMapRepositories
@SpringBootApplication
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class);
}
@SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection")
@Autowired
private PersonRepository repository;
@PostConstruct
public void init() {
repository.save(new Person(1, "Pushkin"));
}
}
@@ -0,0 +1,37 @@
package ru.otus.spring.domain;
import org.springframework.data.annotation.Id;
import org.springframework.data.keyvalue.annotation.KeySpace;
@KeySpace("person")
public class Person {
@Id
private long id;
private String name;
public Person(String name) {
this.name = name;
}
public Person(long id, String name) {
this.id = id;
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@@ -0,0 +1,11 @@
package ru.otus.spring.repostory;
import org.springframework.data.repository.PagingAndSortingRepository;
import ru.otus.spring.domain.Person;
import java.util.List;
public interface PersonRepository extends PagingAndSortingRepository<Person, Long> {
List<Person> findAll();
}
@@ -0,0 +1,4 @@
package ru.otus.spring.rest;
public class ErrorHandler {
}
@@ -0,0 +1,7 @@
package ru.otus.spring.rest;
public class NotFoundException extends RuntimeException{
public NotFoundException() {
}
}
@@ -0,0 +1,24 @@
package ru.otus.spring.rest;
import org.springframework.web.bind.annotation.*;
import ru.otus.spring.repostory.PersonRepository;
import java.util.List;
import java.util.stream.Collectors;
@RestController
public class PersonController {
private final PersonRepository repository;
public PersonController(PersonRepository repository) {
this.repository = repository;
}
@RequestMapping(value = "/persons/all", method = RequestMethod.GET)
public List<PersonDto> getAllPersons() {
return repository.findAll().stream()
.map(PersonDto::toDto)
.collect(Collectors.toList());
}
}
@@ -0,0 +1,54 @@
/*
* Copyright 2016 Russian Post
*
* This source code is Russian Post Confidential Proprietary.
* This software is protected by copyright. All rights and titles are reserved.
* You shall not use, copy, distribute, modify, decompile, disassemble or reverse engineer the software.
* Otherwise this violation would be treated by law and would be subject to legal prosecution.
* Legal use of the software provides receipt of a license from the right name only.
*/
package ru.otus.spring.rest;
import ru.otus.spring.domain.Person;
/**
* DTO that represents Account
*/
@SuppressWarnings("all")
public class PersonDto {
private long id;
private String name;
public PersonDto() {
}
public PersonDto(long id, String name) {
this.id = id;
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static Person toDomainObject(PersonDto dto) {
return new Person(dto.getId(), dto.getName());
}
public static PersonDto toDto(Person account) {
return new PersonDto(account.getId(), account.getName());
}
}
@@ -0,0 +1,84 @@
package ru.otus.spring.rest;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.web.servlet.MockMvc;
import ru.otus.spring.domain.Person;
import ru.otus.spring.repostory.PersonRepository;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@WebMvcTest(PersonController.class)
class PersonControllerTest {
public static final String ERROR_STRING = "Таких тут нет!";
@Autowired
private MockMvc mvc;
@Autowired
private ObjectMapper mapper;
@MockBean
private PersonRepository repository;
@Test
void shouldReturnCorrectPersonsList() throws Exception {
List<Person> persons = List.of(new Person(1, "Person1"), new Person(2, "Person2"));
given(repository.findAll()).willReturn(persons);
List<PersonDto> expectedResult = persons.stream()
.map(PersonDto::toDto).collect(Collectors.toList());
mvc.perform(get("/persons/all"))
.andExpect(status().isOk())
.andExpect(content().json(mapper.writeValueAsString(expectedResult)));
}
@Test
void shouldReturnCorrectPersonByIdInRequest() throws Exception {
Person person = new Person(1, "Person1");
given(repository.findById(1L)).willReturn(Optional.of(person));
PersonDto expectedResult = PersonDto.toDto(person);
mvc.perform(get("/persons").param("id", "1"))
.andExpect(status().isOk())
.andExpect(content().json(mapper.writeValueAsString(expectedResult)));
}
@Test
void shouldReturnCorrectPersonByIdInPath() throws Exception {
Person person = new Person(1, "Person1");
given(repository.findById(1L)).willReturn(Optional.of(person));
PersonDto expectedResult = PersonDto.toDto(person);
mvc.perform(get("/persons/1"))
.andExpect(status().isOk())
.andExpect(content().json(mapper.writeValueAsString(expectedResult)));
}
@Test
void shouldReturnExpectedErrorWhenPersonNotFound() throws Exception {
given(repository.findById(1L)).willReturn(Optional.empty());
mvc.perform(get("/persons").param("id", "1"))
.andExpect(status().isBadRequest())
.andExpect(content().string(ERROR_STRING));
mvc.perform(get("/persons/1"))
.andExpect(status().isBadRequest())
.andExpect(content().string(ERROR_STRING));
}
}
@@ -0,0 +1,24 @@
target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/build/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
@@ -0,0 +1,53 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>ru.otus</groupId>
<artifactId>spring-mvc-solution-2</artifactId>
<version>1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.5</version>
</parent>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-keyvalue</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,28 @@
package ru.otus.spring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.map.repository.config.EnableMapRepositories;
import ru.otus.spring.domain.Person;
import ru.otus.spring.repostory.PersonRepository;
import javax.annotation.PostConstruct;
@EnableMapRepositories
@SpringBootApplication
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class);
}
@SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection")
@Autowired
private PersonRepository repository;
@PostConstruct
public void init() {
repository.save(new Person(1, "Pushkin"));
}
}
@@ -0,0 +1,37 @@
package ru.otus.spring.domain;
import org.springframework.data.annotation.Id;
import org.springframework.data.keyvalue.annotation.KeySpace;
@KeySpace("person")
public class Person {
@Id
private long id;
private String name;
public Person(String name) {
this.name = name;
}
public Person(long id, String name) {
this.id = id;
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@@ -0,0 +1,11 @@
package ru.otus.spring.repostory;
import org.springframework.data.repository.PagingAndSortingRepository;
import ru.otus.spring.domain.Person;
import java.util.List;
public interface PersonRepository extends PagingAndSortingRepository<Person, Long> {
List<Person> findAll();
}
@@ -0,0 +1,2 @@
package ru.otus.spring.rest;public class ErrorHandler {
}
@@ -0,0 +1,7 @@
package ru.otus.spring.rest;
public class NotFoundException extends RuntimeException{
public NotFoundException() {
}
}
@@ -0,0 +1,38 @@
package ru.otus.spring.rest;
import org.springframework.web.bind.annotation.*;
import ru.otus.spring.domain.Person;
import ru.otus.spring.repostory.PersonRepository;
import java.util.List;
import java.util.stream.Collectors;
@RestController
public class PersonController {
private final PersonRepository repository;
public PersonController(PersonRepository repository) {
this.repository = repository;
}
@RequestMapping(value = "/persons/all", method = RequestMethod.GET, params = {})
public List<PersonDto> getAllPersons() {
return repository.findAll().stream()
.map(PersonDto::toDto)
.collect(Collectors.toList());
}
@RequestMapping(value = "/persons", method = RequestMethod.GET)
public PersonDto getPersonByIdInRequest(@RequestParam("id") long id) {
Person person = repository.findById(id).orElseThrow(NotFoundException::new);
return PersonDto.toDto(person);
}
@GetMapping("/persons/{id}")
public PersonDto getPersonByIdInPath(@PathVariable("id") long id) {
Person person = repository.findById(id).orElseThrow(NotFoundException::new);
return PersonDto.toDto(person);
}
}
@@ -0,0 +1,54 @@
/*
* Copyright 2016 Russian Post
*
* This source code is Russian Post Confidential Proprietary.
* This software is protected by copyright. All rights and titles are reserved.
* You shall not use, copy, distribute, modify, decompile, disassemble or reverse engineer the software.
* Otherwise this violation would be treated by law and would be subject to legal prosecution.
* Legal use of the software provides receipt of a license from the right name only.
*/
package ru.otus.spring.rest;
import ru.otus.spring.domain.Person;
/**
* DTO that represents Account
*/
@SuppressWarnings("all")
public class PersonDto {
private long id;
private String name;
public PersonDto() {
}
public PersonDto(long id, String name) {
this.id = id;
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static Person toDomainObject(PersonDto dto) {
return new Person(dto.getId(), dto.getName());
}
public static PersonDto toDto(Person account) {
return new PersonDto(account.getId(), account.getName());
}
}
@@ -0,0 +1,84 @@
package ru.otus.spring.rest;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.web.servlet.MockMvc;
import ru.otus.spring.domain.Person;
import ru.otus.spring.repostory.PersonRepository;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@WebMvcTest(PersonController.class)
class PersonControllerTest {
public static final String ERROR_STRING = "Таких тут нет!";
@Autowired
private MockMvc mvc;
@Autowired
private ObjectMapper mapper;
@MockBean
private PersonRepository repository;
@Test
void shouldReturnCorrectPersonsList() throws Exception {
List<Person> persons = List.of(new Person(1, "Person1"), new Person(2, "Person2"));
given(repository.findAll()).willReturn(persons);
List<PersonDto> expectedResult = persons.stream()
.map(PersonDto::toDto).collect(Collectors.toList());
mvc.perform(get("/persons/all"))
.andExpect(status().isOk())
.andExpect(content().json(mapper.writeValueAsString(expectedResult)));
}
@Test
void shouldReturnCorrectPersonByIdInRequest() throws Exception {
Person person = new Person(1, "Person1");
given(repository.findById(1L)).willReturn(Optional.of(person));
PersonDto expectedResult = PersonDto.toDto(person);
mvc.perform(get("/persons").param("id", "1"))
.andExpect(status().isOk())
.andExpect(content().json(mapper.writeValueAsString(expectedResult)));
}
@Test
void shouldReturnCorrectPersonByIdInPath() throws Exception {
Person person = new Person(1, "Person1");
given(repository.findById(1L)).willReturn(Optional.of(person));
PersonDto expectedResult = PersonDto.toDto(person);
mvc.perform(get("/persons/1"))
.andExpect(status().isOk())
.andExpect(content().json(mapper.writeValueAsString(expectedResult)));
}
@Test
void shouldReturnExpectedErrorWhenPersonNotFound() throws Exception {
given(repository.findById(1L)).willReturn(Optional.empty());
mvc.perform(get("/persons").param("id", "1"))
.andExpect(status().isBadRequest())
.andExpect(content().string(ERROR_STRING));
mvc.perform(get("/persons/1"))
.andExpect(status().isBadRequest())
.andExpect(content().string(ERROR_STRING));
}
}
@@ -0,0 +1,24 @@
target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/build/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
@@ -0,0 +1,53 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>ru.otus</groupId>
<artifactId>spring-mvc-solution-3</artifactId>
<version>1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.5</version>
</parent>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-keyvalue</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,28 @@
package ru.otus.spring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.map.repository.config.EnableMapRepositories;
import ru.otus.spring.domain.Person;
import ru.otus.spring.repostory.PersonRepository;
import javax.annotation.PostConstruct;
@EnableMapRepositories
@SpringBootApplication
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class);
}
@SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection")
@Autowired
private PersonRepository repository;
@PostConstruct
public void init() {
repository.save(new Person(1, "Pushkin"));
}
}
@@ -0,0 +1,37 @@
package ru.otus.spring.domain;
import org.springframework.data.annotation.Id;
import org.springframework.data.keyvalue.annotation.KeySpace;
@KeySpace("person")
public class Person {
@Id
private long id;
private String name;
public Person(String name) {
this.name = name;
}
public Person(long id, String name) {
this.id = id;
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@@ -0,0 +1,11 @@
package ru.otus.spring.repostory;
import org.springframework.data.repository.PagingAndSortingRepository;
import ru.otus.spring.domain.Person;
import java.util.List;
public interface PersonRepository extends PagingAndSortingRepository<Person, Long> {
List<Person> findAll();
}
@@ -0,0 +1,2 @@
package ru.otus.spring.rest;public class ErrorHandler {
}
@@ -0,0 +1,7 @@
package ru.otus.spring.rest;
public class NotFoundException extends RuntimeException{
public NotFoundException() {
}
}
@@ -0,0 +1,43 @@
package ru.otus.spring.rest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import ru.otus.spring.domain.Person;
import ru.otus.spring.repostory.PersonRepository;
import java.util.List;
import java.util.stream.Collectors;
@RestController
public class PersonController {
private final PersonRepository repository;
public PersonController(PersonRepository repository) {
this.repository = repository;
}
@RequestMapping(value = "/persons/all", method = RequestMethod.GET, params = {})
public List<PersonDto> getAllPersons() {
return repository.findAll().stream()
.map(PersonDto::toDto)
.collect(Collectors.toList());
}
@RequestMapping(value = "/persons", method = RequestMethod.GET)
public PersonDto getPersonByIdInRequest(@RequestParam("id") long id) {
Person person = repository.findById(id).orElseThrow(NotFoundException::new);
return PersonDto.toDto(person);
}
@GetMapping("/persons/{id}")
public PersonDto getPersonByIdInPath(@PathVariable("id") long id) {
Person person = repository.findById(id).orElseThrow(NotFoundException::new);
return PersonDto.toDto(person);
}
@ExceptionHandler(NotFoundException.class)
public ResponseEntity<String> handleNotFound(NotFoundException ex) {
return ResponseEntity.badRequest().body("Таких тут нет!");
}
}
@@ -0,0 +1,54 @@
/*
* Copyright 2016 Russian Post
*
* This source code is Russian Post Confidential Proprietary.
* This software is protected by copyright. All rights and titles are reserved.
* You shall not use, copy, distribute, modify, decompile, disassemble or reverse engineer the software.
* Otherwise this violation would be treated by law and would be subject to legal prosecution.
* Legal use of the software provides receipt of a license from the right name only.
*/
package ru.otus.spring.rest;
import ru.otus.spring.domain.Person;
/**
* DTO that represents Account
*/
@SuppressWarnings("all")
public class PersonDto {
private long id;
private String name;
public PersonDto() {
}
public PersonDto(long id, String name) {
this.id = id;
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static Person toDomainObject(PersonDto dto) {
return new Person(dto.getId(), dto.getName());
}
public static PersonDto toDto(Person account) {
return new PersonDto(account.getId(), account.getName());
}
}
@@ -0,0 +1,84 @@
package ru.otus.spring.rest;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import ru.otus.spring.domain.Person;
import ru.otus.spring.repostory.PersonRepository;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@WebMvcTest(PersonController.class)
class PersonControllerTest {
public static final String ERROR_STRING = "Таких тут нет!";
@Autowired
private MockMvc mvc;
@Autowired
private ObjectMapper mapper;
@MockBean
private PersonRepository repository;
@Test
void shouldReturnCorrectPersonsList() throws Exception {
List<Person> persons = List.of(new Person(1, "Person1"), new Person(2, "Person2"));
given(repository.findAll()).willReturn(persons);
List<PersonDto> expectedResult = persons.stream()
.map(PersonDto::toDto).collect(Collectors.toList());
mvc.perform(get("/persons/all"))
.andExpect(status().isOk())
.andExpect(content().json(mapper.writeValueAsString(expectedResult)));
}
@Test
void shouldReturnCorrectPersonByIdInRequest() throws Exception {
Person person = new Person(1, "Person1");
given(repository.findById(1L)).willReturn(Optional.of(person));
PersonDto expectedResult = PersonDto.toDto(person);
mvc.perform(get("/persons").param("id", "1"))
.andExpect(status().isOk())
.andExpect(content().json(mapper.writeValueAsString(expectedResult)));
}
@Test
void shouldReturnCorrectPersonByIdInPath() throws Exception {
Person person = new Person(1, "Person1");
given(repository.findById(1L)).willReturn(Optional.of(person));
PersonDto expectedResult = PersonDto.toDto(person);
mvc.perform(get("/persons/1"))
.andExpect(status().isOk())
.andExpect(content().json(mapper.writeValueAsString(expectedResult)));
}
@Test
void shouldReturnExpectedErrorWhenPersonNotFound() throws Exception {
given(repository.findById(1L)).willReturn(Optional.empty());
mvc.perform(get("/persons").param("id", "1"))
.andExpect(status().isBadRequest())
.andExpect(content().string(ERROR_STRING));
mvc.perform(get("/persons/1"))
.andExpect(status().isBadRequest())
.andExpect(content().string(ERROR_STRING));
}
}
@@ -0,0 +1,24 @@
target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/build/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
@@ -0,0 +1,52 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>ru.otus</groupId>
<artifactId>spring-mvc-solution-4</artifactId>
<version>1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.5</version>
</parent>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-keyvalue</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,28 @@
package ru.otus.spring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.map.repository.config.EnableMapRepositories;
import ru.otus.spring.domain.Person;
import ru.otus.spring.repostory.PersonRepository;
import javax.annotation.PostConstruct;
@EnableMapRepositories
@SpringBootApplication
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class);
}
@SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection")
@Autowired
private PersonRepository repository;
@PostConstruct
public void init() {
repository.save(new Person(1, "Pushkin"));
}
}
@@ -0,0 +1,37 @@
package ru.otus.spring.domain;
import org.springframework.data.annotation.Id;
import org.springframework.data.keyvalue.annotation.KeySpace;
@KeySpace("person")
public class Person {
@Id
private long id;
private String name;
public Person(String name) {
this.name = name;
}
public Person(long id, String name) {
this.id = id;
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@@ -0,0 +1,11 @@
package ru.otus.spring.repostory;
import org.springframework.data.repository.PagingAndSortingRepository;
import ru.otus.spring.domain.Person;
import java.util.List;
public interface PersonRepository extends PagingAndSortingRepository<Person, Long> {
List<Person> findAll();
}
@@ -0,0 +1,2 @@
package ru.otus.spring.rest;public class ErrorHandler {
}
@@ -0,0 +1,7 @@
package ru.otus.spring.rest;
public class NotFoundException extends RuntimeException{
public NotFoundException() {
}
}
@@ -0,0 +1,62 @@
package ru.otus.spring.rest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import ru.otus.spring.domain.Person;
import ru.otus.spring.repostory.PersonRepository;
import java.util.List;
import java.util.stream.Collectors;
@RestController
public class PersonController {
private final PersonRepository repository;
public PersonController(PersonRepository repository) {
this.repository = repository;
}
@RequestMapping(value = "/persons/all", method = RequestMethod.GET, params = {})
public List<PersonDto> getAllPersons() {
return repository.findAll().stream()
.map(PersonDto::toDto)
.collect(Collectors.toList());
}
@RequestMapping(value = "/persons", method = RequestMethod.GET)
public PersonDto getPersonByIdInRequest(@RequestParam("id") long id) {
Person person = repository.findById(id).orElseThrow(NotFoundException::new);
return PersonDto.toDto(person);
}
@GetMapping("/persons/{id}")
public PersonDto getPersonByIdInPath(@PathVariable("id") long id) {
Person person = repository.findById(id).orElseThrow(NotFoundException::new);
return PersonDto.toDto(person);
}
@PostMapping("/persons")
public PersonDto createNewPerson(@RequestBody PersonDto dto) {
Person person = PersonDto.toDomainObject(dto);
Person savedPerson = repository.save(person);
return PersonDto.toDto(savedPerson);
}
@PutMapping("/persons/{id}/name")
public PersonDto updateNameById(@PathVariable("id") long id, @RequestParam("name") String name) {
Person person = repository.findById(id).orElseThrow(NotFoundException::new);
person.setName(name);
return PersonDto.toDto(repository.save(person));
}
@DeleteMapping("/persons/{id}")
public void deleteById(@PathVariable("id") long id) {
repository.deleteById(id);
}
@ExceptionHandler(NotFoundException.class)
public ResponseEntity<String> handleNotFound(NotFoundException ex) {
return ResponseEntity.badRequest().body("Таких тут нет!");
}
}
@@ -0,0 +1,54 @@
/*
* Copyright 2016 Russian Post
*
* This source code is Russian Post Confidential Proprietary.
* This software is protected by copyright. All rights and titles are reserved.
* You shall not use, copy, distribute, modify, decompile, disassemble or reverse engineer the software.
* Otherwise this violation would be treated by law and would be subject to legal prosecution.
* Legal use of the software provides receipt of a license from the right name only.
*/
package ru.otus.spring.rest;
import ru.otus.spring.domain.Person;
/**
* DTO that represents Account
*/
@SuppressWarnings("all")
public class PersonDto {
private long id;
private String name;
public PersonDto() {
}
public PersonDto(long id, String name) {
this.id = id;
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static Person toDomainObject(PersonDto dto) {
return new Person(dto.getId(), dto.getName());
}
public static PersonDto toDto(Person account) {
return new PersonDto(account.getId(), account.getName());
}
}
@@ -0,0 +1,122 @@
package ru.otus.spring.rest;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.web.servlet.MockMvc;
import ru.otus.spring.domain.Person;
import ru.otus.spring.repostory.PersonRepository;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@WebMvcTest(PersonController.class)
class PersonControllerTest {
public static final String ERROR_STRING = "Таких тут нет!";
@Autowired
private MockMvc mvc;
@Autowired
private ObjectMapper mapper;
@MockBean
private PersonRepository repository;
@Test
void shouldReturnCorrectPersonsList() throws Exception {
List<Person> persons = List.of(new Person(1, "Person1"), new Person(2, "Person2"));
given(repository.findAll()).willReturn(persons);
List<PersonDto> expectedResult = persons.stream()
.map(PersonDto::toDto).collect(Collectors.toList());
mvc.perform(get("/persons/all"))
.andExpect(status().isOk())
.andExpect(content().json(mapper.writeValueAsString(expectedResult)));
}
@Test
void shouldReturnCorrectPersonByIdInRequest() throws Exception {
Person person = new Person(1, "Person1");
given(repository.findById(1L)).willReturn(Optional.of(person));
PersonDto expectedResult = PersonDto.toDto(person);
mvc.perform(get("/persons").param("id", "1"))
.andExpect(status().isOk())
.andExpect(content().json(mapper.writeValueAsString(expectedResult)));
}
@Test
void shouldReturnCorrectPersonByIdInPath() throws Exception {
Person person = new Person(1, "Person1");
given(repository.findById(1L)).willReturn(Optional.of(person));
PersonDto expectedResult = PersonDto.toDto(person);
mvc.perform(get("/persons/1"))
.andExpect(status().isOk())
.andExpect(content().json(mapper.writeValueAsString(expectedResult)));
}
@Test
void shouldReturnExpectedErrorWhenPersonNotFound() throws Exception {
given(repository.findById(1L)).willReturn(Optional.empty());
mvc.perform(get("/persons").param("id", "1"))
.andExpect(status().isBadRequest())
.andExpect(content().string(ERROR_STRING));
mvc.perform(get("/persons/1"))
.andExpect(status().isBadRequest())
.andExpect(content().string(ERROR_STRING));
}
@Test
void shouldCorrectSaveNewPerson() throws Exception {
Person person = new Person(1, "Person1");
given(repository.save(any())).willReturn(person);
String expectedResult = mapper.writeValueAsString(PersonDto.toDto(person));
mvc.perform(post("/persons").contentType(APPLICATION_JSON)
.content(expectedResult))
.andExpect(status().isOk())
.andExpect(content().json(expectedResult));
}
@Test
void shouldCorrectUpdatePersonName() throws Exception {
Person person = new Person(1, "Person1");
given(repository.findById(1L)).willReturn(Optional.of(person));
given(repository.save(any())).willAnswer(invocation -> invocation.getArgument(0));
Person expectedPerson = new Person(1, "Person2");
String expectedResult = mapper.writeValueAsString(PersonDto.toDto(expectedPerson));
mvc.perform(put("/persons/{id}/name", 1).param("name", expectedPerson.getName())
.content(expectedResult))
.andExpect(status().isOk())
.andExpect(content().json(expectedResult));
}
@Test
void shouldCorrectDeletePerson() throws Exception {
mvc.perform(delete("/persons/1"))
.andExpect(status().isOk());
verify(repository, times(1)).deleteById(1L);
}
}