Merge remote-tracking branch 'origin/master'

This commit is contained in:
Vladimir Ivanov
2024-06-14 19:21:29 +03:00
73 changed files with 2221 additions and 0 deletions
+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-demo</module>
</modules>
</project>
@@ -0,0 +1,66 @@
<?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-demo</artifactId>
<version>1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.3.0</version>
<relativePath/>
</parent>
<properties>
<java.version>17</java.version>
<maven.compiler.target>17</maven.compiler.target>
<maven.compiler.source>17</maven.compiler.source>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<h2.version>2.2.220</h2.version>
<snakeyaml.version>2.0</snakeyaml.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>${snakeyaml.version}</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
<version>${h2.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</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 ru.otus.spring.domain.Person;
import ru.otus.spring.repostory.PersonRepository;
import jakarta.annotation.PostConstruct;
@SpringBootApplication
public class Main {
// http://localhost:8080/server/system/info
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,21 @@
package ru.otus.spring.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import ru.otus.spring.rest.resolvers.SystemInfoMethodArgumentResolver;
import java.util.List;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Autowired
private SystemInfoMethodArgumentResolver systemInfoMethodArgumentResolver;
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
resolvers.add(systemInfoMethodArgumentResolver);
}
}
@@ -0,0 +1,40 @@
package ru.otus.spring.domain;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
@Entity
public class Person {
@Id
private long id;
private String name;
public Person() {
}
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,31 @@
package ru.otus.spring.domain;
public class SystemInfo {
private final String osName;
private final String timeZone;
private final String osArch;
private final int processorsCount;
public SystemInfo(String osName, String timeZone, String osArch, int processorsCount) {
this.osName = osName;
this.timeZone = timeZone;
this.osArch = osArch;
this.processorsCount = processorsCount;
}
public String getOsName() {
return osName;
}
public String getTimeZone() {
return timeZone;
}
public String getOsArch() {
return osArch;
}
public int getProcessorsCount() {
return processorsCount;
}
}
@@ -0,0 +1,12 @@
package ru.otus.spring.repostory;
import org.springframework.data.repository.ListCrudRepository;
import ru.otus.spring.domain.Person;
import java.util.List;
public interface PersonRepository extends ListCrudRepository<Person, Long> {
List<Person> findAll();
List<Person> findByName(String name);
}
@@ -0,0 +1,64 @@
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 ru.otus.spring.rest.dto.PersonDto;
import ru.otus.spring.rest.exceptions.NotFoundException;
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", method = RequestMethod.GET)
public List<PersonDto> getAllPersons() {
return repository.findAll().stream()
.map(PersonDto::toDto)
.collect(Collectors.toList());
}
@RequestMapping(value = "/persons", method = RequestMethod.GET, params = "name")
public PersonDto getPersonByNameInRequest(@RequestParam("name") String name) {
Person person = repository.findByName(name).stream().findFirst().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);
}
@PatchMapping("/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,14 @@
package ru.otus.spring.rest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import ru.otus.spring.domain.SystemInfo;
@RestController
public class SystemInfoController {
@GetMapping("/server/system/info")
public SystemInfo getServerSystemInfo(SystemInfo systemInfo) {
return systemInfo;
}
}
@@ -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.dto;
import ru.otus.spring.domain.Person;
/**
* DTO that represents Person
*/
@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 person) {
return new PersonDto(person.getId(), person.getName());
}
}
@@ -0,0 +1,7 @@
package ru.otus.spring.rest.exceptions;
public class NotFoundException extends RuntimeException{
public NotFoundException() {
}
}
@@ -0,0 +1,33 @@
package ru.otus.spring.rest.resolvers;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import ru.otus.spring.domain.SystemInfo;
import ru.otus.spring.service.SystemInfoService;
@Component
public class SystemInfoMethodArgumentResolver implements HandlerMethodArgumentResolver {
private final SystemInfoService systemInfoService;
public SystemInfoMethodArgumentResolver(SystemInfoService systemInfoService) {
this.systemInfoService = systemInfoService;
}
@Override
public boolean supportsParameter(MethodParameter parameter) {
return parameter.getParameterType().equals(SystemInfo.class);
}
@Override
public Object resolveArgument(MethodParameter parameter,
ModelAndViewContainer mavContainer,
NativeWebRequest webRequest,
WebDataBinderFactory binderFactory) throws Exception {
return systemInfoService.getSystemInfo();
}
}
@@ -0,0 +1,17 @@
package ru.otus.spring.service;
import org.springframework.stereotype.Service;
import ru.otus.spring.domain.SystemInfo;
@Service
public class SystemInfoService {
public SystemInfo getSystemInfo(){
String osName = System.getProperty("os.name");
String timeZone = System.getProperty("user.timezone");
String osArch = System.getProperty("os.arch");
int processorsCount = Runtime.getRuntime().availableProcessors();
return new SystemInfo(osName, timeZone, osArch, processorsCount);
}
}
@@ -0,0 +1,127 @@
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 ru.otus.spring.rest.dto.PersonDto;
import ru.otus.spring.service.SystemInfoService;
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;
@MockBean
private SystemInfoService systemInfoService;
@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"))
.andExpect(status().isOk())
.andExpect(content().json(mapper.writeValueAsString(expectedResult)));
}
@Test
void shouldReturnCorrectPersonByNameInRequest() throws Exception {
Person person = new Person(1, "Person1");
given(repository.findByName(person.getName())).willReturn(List.of(person));
PersonDto expectedResult = PersonDto.toDto(person);
mvc.perform(get("/persons").param("name", person.getName()))
.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("name", "Person1"))
.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(patch("/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);
}
}
@@ -0,0 +1,39 @@
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.context.annotation.Import;
import org.springframework.test.web.servlet.MockMvc;
import ru.otus.spring.domain.SystemInfo;
import ru.otus.spring.repostory.PersonRepository;
import ru.otus.spring.service.SystemInfoService;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
@WebMvcTest(SystemInfoController.class)
@Import(SystemInfoService.class)
class SystemInfoControllerTest {
@Autowired
private MockMvc mvc;
@Autowired
private ObjectMapper mapper;
@MockBean
private PersonRepository repository;
@Autowired
private SystemInfoService systemInfoService;
@Test
void shouldReturnCorrectServerSystemInfo() throws Exception {
SystemInfo expectedSystemInfo = systemInfoService.getSystemInfo();
mvc.perform(get("/server/system/info"))
.andExpect(content().json(mapper.writeValueAsString(expectedSystemInfo)));
}
}
@@ -0,0 +1,65 @@
<?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>3.3.0</version>
<relativePath/>
</parent>
<properties>
<java.version>17</java.version>
<maven.compiler.target>17</maven.compiler.target>
<maven.compiler.source>17</maven.compiler.source>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<h2.version>2.2.220</h2.version>
<snakeyaml.version>2.0</snakeyaml.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>${snakeyaml.version}</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
<version>${h2.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,26 @@
package ru.otus.spring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import ru.otus.spring.domain.Person;
import ru.otus.spring.repostory.PersonRepository;
import jakarta.annotation.PostConstruct;
@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,40 @@
package ru.otus.spring.domain;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
@Entity
public class Person {
@Id
private long id;
private String name;
public Person() {
}
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,12 @@
package ru.otus.spring.repostory;
import org.springframework.data.repository.ListCrudRepository;
import ru.otus.spring.domain.Person;
import java.util.List;
public interface PersonRepository extends ListCrudRepository<Person, Long> {
List<Person> findAll();
List<Person> findByName(String name);
}
@@ -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.dto;
import ru.otus.spring.domain.Person;
/**
* DTO that represents Person
*/
@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 person) {
return new PersonDto(person.getId(), person.getName());
}
}
@@ -0,0 +1,7 @@
package ru.otus.spring.rest.exeptions;
public class NotFoundException extends RuntimeException{
public NotFoundException() {
}
}
@@ -0,0 +1,83 @@
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 ru.otus.spring.rest.dto.PersonDto;
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"))
.andExpect(status().isOk())
.andExpect(content().json(mapper.writeValueAsString(expectedResult)));
}
@Test
void shouldReturnCorrectPersonByNameInRequest() throws Exception {
Person person = new Person(1, "Person1");
given(repository.findByName(person.getName())).willReturn(List.of(person));
PersonDto expectedResult = PersonDto.toDto(person);
mvc.perform(get("/persons").param("name", person.getName()))
.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("name", "Person1"))
.andExpect(status().isBadRequest())
.andExpect(content().string(ERROR_STRING));
mvc.perform(get("/persons/1"))
.andExpect(status().isBadRequest())
.andExpect(content().string(ERROR_STRING));
}
}
@@ -0,0 +1,65 @@
<?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>3.3.0</version>
<relativePath/>
</parent>
<properties>
<java.version>17</java.version>
<maven.compiler.target>17</maven.compiler.target>
<maven.compiler.source>17</maven.compiler.source>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<h2.version>2.2.220</h2.version>
<snakeyaml.version>2.0</snakeyaml.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>${snakeyaml.version}</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
<version>${h2.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,26 @@
package ru.otus.spring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import ru.otus.spring.domain.Person;
import ru.otus.spring.repostory.PersonRepository;
import jakarta.annotation.PostConstruct;
@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,40 @@
package ru.otus.spring.domain;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
@Entity
public class Person {
@Id
private long id;
private String name;
public Person() {
}
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,12 @@
package ru.otus.spring.repostory;
import org.springframework.data.repository.ListCrudRepository;
import ru.otus.spring.domain.Person;
import java.util.List;
public interface PersonRepository extends ListCrudRepository<Person, Long> {
List<Person> findAll();
List<Person> findByName(String name);
}
@@ -0,0 +1,27 @@
package ru.otus.spring.rest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import ru.otus.spring.repostory.PersonRepository;
import ru.otus.spring.rest.dto.PersonDto;
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", 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.dto;
import ru.otus.spring.domain.Person;
/**
* DTO that represents Person
*/
@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 person) {
return new PersonDto(person.getId(), person.getName());
}
}
@@ -0,0 +1,7 @@
package ru.otus.spring.rest.exceptions;
public class NotFoundException extends RuntimeException{
public NotFoundException() {
}
}
@@ -0,0 +1,83 @@
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 ru.otus.spring.rest.dto.PersonDto;
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"))
.andExpect(status().isOk())
.andExpect(content().json(mapper.writeValueAsString(expectedResult)));
}
@Test
void shouldReturnCorrectPersonByNameInRequest() throws Exception {
Person person = new Person(1, "Person1");
given(repository.findByName(person.getName())).willReturn(List.of(person));
PersonDto expectedResult = PersonDto.toDto(person);
mvc.perform(get("/persons").param("name", person.getName()))
.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("name", "Person1"))
.andExpect(status().isBadRequest())
.andExpect(content().string(ERROR_STRING));
mvc.perform(get("/persons/1"))
.andExpect(status().isBadRequest())
.andExpect(content().string(ERROR_STRING));
}
}
@@ -0,0 +1,66 @@
<?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>3.3.0</version>
<relativePath/>
</parent>
<properties>
<java.version>17</java.version>
<maven.compiler.target>17</maven.compiler.target>
<maven.compiler.source>17</maven.compiler.source>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<h2.version>2.2.220</h2.version>
<snakeyaml.version>2.0</snakeyaml.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>${snakeyaml.version}</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
<version>${h2.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,26 @@
package ru.otus.spring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import ru.otus.spring.domain.Person;
import ru.otus.spring.repostory.PersonRepository;
import jakarta.annotation.PostConstruct;
@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,40 @@
package ru.otus.spring.domain;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
@Entity
public class Person {
@Id
private long id;
private String name;
public Person() {
}
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,12 @@
package ru.otus.spring.repostory;
import org.springframework.data.repository.ListCrudRepository;
import ru.otus.spring.domain.Person;
import java.util.List;
public interface PersonRepository extends ListCrudRepository<Person, Long> {
List<Person> findAll();
List<Person> findByName(String name);
}
@@ -0,0 +1,40 @@
package ru.otus.spring.rest;
import org.springframework.web.bind.annotation.*;
import ru.otus.spring.domain.Person;
import ru.otus.spring.repostory.PersonRepository;
import ru.otus.spring.rest.dto.PersonDto;
import ru.otus.spring.rest.exceptions.NotFoundException;
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", method = RequestMethod.GET)
public List<PersonDto> getAllPersons() {
return repository.findAll().stream()
.map(PersonDto::toDto)
.collect(Collectors.toList());
}
@RequestMapping(value = "/persons", method = RequestMethod.GET, params = "name")
public PersonDto getPersonByNameInRequest(@RequestParam("name") String name) {
Person person = repository.findByName(name).stream().findFirst().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.dto;
import ru.otus.spring.domain.Person;
/**
* DTO that represents Person
*/
@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 person) {
return new PersonDto(person.getId(), person.getName());
}
}
@@ -0,0 +1,7 @@
package ru.otus.spring.rest.exceptions;
public class NotFoundException extends RuntimeException{
public NotFoundException() {
}
}
@@ -0,0 +1,83 @@
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 ru.otus.spring.rest.dto.PersonDto;
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.get;
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"))
.andExpect(status().isOk())
.andExpect(content().json(mapper.writeValueAsString(expectedResult)));
}
@Test
void shouldReturnCorrectPersonByNameInRequest() throws Exception {
Person person = new Person(1, "Person1");
given(repository.findByName(person.getName())).willReturn(List.of(person));
PersonDto expectedResult = PersonDto.toDto(person);
mvc.perform(get("/persons").param("name", person.getName()))
.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("name", "Person1"))
.andExpect(status().isBadRequest())
.andExpect(content().string(ERROR_STRING));
mvc.perform(get("/persons/1"))
.andExpect(status().isBadRequest())
.andExpect(content().string(ERROR_STRING));
}
}
@@ -0,0 +1,66 @@
<?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>3.3.0</version>
<relativePath/>
</parent>
<properties>
<java.version>17</java.version>
<maven.compiler.target>17</maven.compiler.target>
<maven.compiler.source>17</maven.compiler.source>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<h2.version>2.2.220</h2.version>
<snakeyaml.version>2.0</snakeyaml.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>${snakeyaml.version}</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
<version>${h2.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,10 @@
POST http://localhost:8080/person
Content-Type: application/json
{
"id": "2",
"name": "Pushkin"
}
###
GET http://localhost:8080/persons/all
@@ -0,0 +1,26 @@
package ru.otus.spring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import ru.otus.spring.domain.Person;
import ru.otus.spring.repostory.PersonRepository;
import jakarta.annotation.PostConstruct;
@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,40 @@
package ru.otus.spring.domain;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
@Entity
public class Person {
@Id
private long id;
private String name;
public Person() {
}
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,12 @@
package ru.otus.spring.repostory;
import org.springframework.data.repository.ListCrudRepository;
import ru.otus.spring.domain.Person;
import java.util.List;
public interface PersonRepository extends ListCrudRepository<Person, Long> {
List<Person> findAll();
List<Person> findByName(String name);
}
@@ -0,0 +1,45 @@
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 ru.otus.spring.rest.dto.PersonDto;
import ru.otus.spring.rest.exceptions.NotFoundException;
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", method = RequestMethod.GET)
public List<PersonDto> getAllPersons() {
return repository.findAll().stream()
.map(PersonDto::toDto)
.collect(Collectors.toList());
}
@RequestMapping(value = "/persons", method = RequestMethod.GET, params = "name")
public PersonDto getPersonByNameInRequest(@RequestParam("name") String name) {
Person person = repository.findByName(name).stream().findFirst().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.dto;
import ru.otus.spring.domain.Person;
/**
* DTO that represents Person
*/
@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 person) {
return new PersonDto(person.getId(), person.getName());
}
}
@@ -0,0 +1,7 @@
package ru.otus.spring.rest.exceptions;
public class NotFoundException extends RuntimeException{
public NotFoundException() {
}
}
@@ -0,0 +1,83 @@
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 ru.otus.spring.rest.dto.PersonDto;
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.get;
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"))
.andExpect(status().isOk())
.andExpect(content().json(mapper.writeValueAsString(expectedResult)));
}
@Test
void shouldReturnCorrectPersonByNameInRequest() throws Exception {
Person person = new Person(1, "Person1");
given(repository.findByName(person.getName())).willReturn(List.of(person));
PersonDto expectedResult = PersonDto.toDto(person);
mvc.perform(get("/persons").param("name", person.getName()))
.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("name", "Person1"))
.andExpect(status().isBadRequest())
.andExpect(content().string(ERROR_STRING));
mvc.perform(get("/persons/1"))
.andExpect(status().isBadRequest())
.andExpect(content().string(ERROR_STRING));
}
}
+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/
+17
View File
@@ -0,0 +1,17 @@
<?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-03</artifactId>
<version>1.0</version>
<packaging>pom</packaging>
<modules>
<module>spring-03-exercise</module>
<module>spring-03-solution</module>
</modules>
</project>
@@ -0,0 +1,24 @@
<?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-03-exercise</artifactId>
<version>1.0</version>
<properties>
<maven.compiler.target>17</maven.compiler.target>
<maven.compiler.source>17</maven.compiler.source>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.1.8</version>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,17 @@
package ru.otus.spring;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import ru.otus.spring.domain.Person;
import ru.otus.spring.service.PersonService;
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = null;
PersonService service = context.getBean(PersonService.class);
Person ivan = service.getByName("Ivan");
System.out.println("name: " + ivan.getName() + " age: " + ivan.getAge());
}
}
@@ -0,0 +1,11 @@
package ru.otus.spring.config;
import ru.otus.spring.dao.PersonDao;
import ru.otus.spring.dao.PersonDaoSimple;
public class DaoConfig {
public PersonDao personDaoSimple() {
return new PersonDaoSimple();
}
}
@@ -0,0 +1,12 @@
package ru.otus.spring.config;
import ru.otus.spring.dao.PersonDao;
import ru.otus.spring.service.PersonService;
import ru.otus.spring.service.PersonServiceImpl;
public class ServicesConfig {
public PersonService personService(PersonDao dao) {
return new PersonServiceImpl(dao);
}
}
@@ -0,0 +1,8 @@
package ru.otus.spring.dao;
import ru.otus.spring.domain.Person;
public interface PersonDao {
Person findByName(String name);
}
@@ -0,0 +1,10 @@
package ru.otus.spring.dao;
import ru.otus.spring.domain.Person;
public class PersonDaoSimple implements PersonDao {
public Person findByName(String name) {
return new Person(name, 18);
}
}
@@ -0,0 +1,10 @@
package ru.otus.spring.dao;
import ru.otus.spring.domain.Person;
public class PersonDaoSmart implements PersonDao {
public Person findByName(String name) {
return new Person(name, 21);
}
}
@@ -0,0 +1,20 @@
package ru.otus.spring.domain;
public class Person {
private final String name;
private final int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
@@ -0,0 +1,8 @@
package ru.otus.spring.service;
import ru.otus.spring.domain.Person;
public interface PersonService {
Person getByName(String name);
}
@@ -0,0 +1,17 @@
package ru.otus.spring.service;
import ru.otus.spring.dao.PersonDao;
import ru.otus.spring.domain.Person;
public class PersonServiceImpl implements PersonService {
private final PersonDao dao;
public PersonServiceImpl(PersonDao dao) {
this.dao = dao;
}
public Person getByName(String name) {
return dao.findByName(name);
}
}
@@ -0,0 +1,40 @@
<?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-03-solution</artifactId>
<version>1.0</version>
<properties>
<maven.compiler.target>17</maven.compiler.target>
<maven.compiler.source>17</maven.compiler.source>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.1.8</version>
</dependency>
</dependencies>
<!-- https://stackoverflow.com/questions/74600681/warning-printed-after-migrating-to-spring-boot-3-0-spring-integration-6-0 -->
<!-- <build>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.11.0</version>
<configuration>
<parameters>true</parameters>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>-->
</project>
@@ -0,0 +1,22 @@
package ru.otus.spring;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import ru.otus.spring.domain.Person;
import ru.otus.spring.service.PersonService;
@Configuration
@ComponentScan
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(Main.class);
PersonService service = context.getBean(PersonService.class);
Person ivan = service.getByName("Ivan");
System.out.println("name: " + ivan.getName() + " age: " + ivan.getAge());
}
}
@@ -0,0 +1,21 @@
package ru.otus.spring.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import ru.otus.spring.dao.PersonDao;
import ru.otus.spring.dao.PersonDaoSimple;
import ru.otus.spring.dao.PersonDaoSmart;
@Configuration
public class DaoConfig {
@Bean
public PersonDao personDaoSimple() {
return new PersonDaoSimple();
}
@Bean
public PersonDao personDaoSmart() {
return new PersonDaoSmart();
}
}
@@ -0,0 +1,17 @@
package ru.otus.spring.config;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import ru.otus.spring.dao.PersonDao;
import ru.otus.spring.service.PersonService;
import ru.otus.spring.service.PersonServiceImpl;
@Configuration
public class ServicesConfig {
@Bean
public PersonService personService(@Qualifier("personDaoSmart") PersonDao dao) {
return new PersonServiceImpl(dao);
}
}
@@ -0,0 +1,8 @@
package ru.otus.spring.dao;
import ru.otus.spring.domain.Person;
public interface PersonDao {
Person findByName(String name);
}
@@ -0,0 +1,10 @@
package ru.otus.spring.dao;
import ru.otus.spring.domain.Person;
public class PersonDaoSimple implements PersonDao {
public Person findByName(String name) {
return new Person(name, 18);
}
}
@@ -0,0 +1,10 @@
package ru.otus.spring.dao;
import ru.otus.spring.domain.Person;
public class PersonDaoSmart implements PersonDao {
public Person findByName(String name) {
return new Person(name, 21);
}
}
@@ -0,0 +1,20 @@
package ru.otus.spring.domain;
public class Person {
private final String name;
private final int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
@@ -0,0 +1,8 @@
package ru.otus.spring.service;
import ru.otus.spring.domain.Person;
public interface PersonService {
Person getByName(String name);
}
@@ -0,0 +1,17 @@
package ru.otus.spring.service;
import ru.otus.spring.dao.PersonDao;
import ru.otus.spring.domain.Person;
public class PersonServiceImpl implements PersonService {
private final PersonDao dao;
public PersonServiceImpl(PersonDao dao) {
this.dao = dao;
}
public Person getByName(String name) {
return dao.findByName(name);
}
}
@@ -4,4 +4,8 @@ public class QuestionReadException extends RuntimeException {
public QuestionReadException(String message, Throwable ex) {
super(message, ex);
}
public QuestionReadException(String message) {
super(message);
}
}
@@ -4,4 +4,8 @@ public class QuestionReadException extends RuntimeException {
public QuestionReadException(String message, Throwable ex) {
super(message, ex);
}
public QuestionReadException(String message) {
super(message);
}
}
@@ -4,4 +4,8 @@ public class QuestionReadException extends RuntimeException {
public QuestionReadException(String message, Throwable ex) {
super(message, ex);
}
public QuestionReadException(String message) {
super(message);
}
}