Добавил API для User, не работает

This commit is contained in:
Никита Потапов 2024-03-18 18:47:36 +04:00
parent a7c30530f6
commit e6923c88ba
16 changed files with 553 additions and 108 deletions

View File

@ -18,7 +18,7 @@ repositories {
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.3.0'
// implementation 'org.modelmapper:modelmapper:3.2.0'
implementation 'org.modelmapper:modelmapper:3.2.0'
// implementation 'com.fasterxml.jackson.core:jackson-databind:2.12.5'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

View File

@ -1,14 +1,34 @@
package com.example.nekontakte;
import java.util.Objects;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class NekontakteApplication {
public class NekontakteApplication implements CommandLineRunner {
private final Logger _logger = LoggerFactory.getLogger(NekontakteApplication.class);
public NekontakteApplication() {
}
public static void main(String[] args) {
SpringApplication.run(NekontakteApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
if (args.length > 0 && Objects.equals("--populate", args[0])) {
// todo: fill database with test data...
_logger.info("fill database with test data");
}
}
}

View File

@ -1,64 +0,0 @@
package com.example.nekontakte;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
import java.util.HashMap;
import java.util.List;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.PathVariable;
@RestController
@RequestMapping("/user")
public class UserApiEndpoint {
private Integer lastUserId = 0;
private HashMap<Integer, UserDTO> users = new HashMap<>();
@GetMapping()
public List<UserDTO> getUsers() {
return users.values().stream().toList();
}
@GetMapping("/{id}")
public UserDTO getUser(@PathVariable Integer id) {
if (users.containsKey(id)) {
return users.get(id);
}
throw new ResponseStatusException(HttpStatus.NOT_FOUND);
}
@PostMapping()
public UserDTO postUser(@RequestBody UserDTO entity) {
Integer currentUserId = lastUserId + 1;
entity.setId(currentUserId);
users.put(currentUserId, entity);
lastUserId++;
return entity;
}
@PutMapping("/{id}")
public UserDTO putUser(@PathVariable Integer id, @RequestBody UserDTO entity) {
if (users.containsKey(id)) {
entity.setId(id);
users.put(id, entity);
return entity;
}
throw new ResponseStatusException(HttpStatus.NOT_FOUND);
}
@DeleteMapping("/{id}")
public UserDTO deleteUser(@PathVariable Integer id) {
if (users.containsKey(id)) {
return users.remove(id);
}
throw new ResponseStatusException(HttpStatus.NOT_FOUND);
}
}

View File

@ -1,31 +0,0 @@
package com.example.nekontakte;
public class UserDTO {
private Integer id;
private String username;
private String password;
public Integer getId() {
return id;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public void setId(Integer id) {
this.id = id;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
}

View File

@ -0,0 +1,8 @@
package com.example.nekontakte.core.configurations;
public class Constants {
public static final String API_URL = "/api";
private Constants() {
}
}

View File

@ -0,0 +1,13 @@
package com.example.nekontakte.core.configurations;
import org.modelmapper.ModelMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MapperConfiguration {
@Bean
ModelMapper modelMapper() {
return new ModelMapper();
}
}

View File

@ -1,11 +1,8 @@
package com.example.nekontakte;
package com.example.nekontakte.core.configurations;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.NonNull;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.method.HandlerTypePredicate;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@ -16,9 +13,4 @@ public class WebConfig implements WebMvcConfigurer {
.allowedMethods("GET", "POST", "PUT", "DELETE");
}
@Override
public void configurePathMatch(@SuppressWarnings("null") PathMatchConfigurer configurer) {
configurer.addPathPrefix("api", HandlerTypePredicate.forAnnotation(RestController.class));
}
}

View File

@ -0,0 +1,7 @@
package com.example.nekontakte.core.errors;
public class NotFoundException extends RuntimeException {
public NotFoundException(Integer id) {
super(String.format("Entity with id <[%s]> not found", id));
}
}

View File

@ -0,0 +1,20 @@
package com.example.nekontakte.core.model;
public class BaseEntity {
public Integer id;
protected BaseEntity() {
}
protected BaseEntity(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}

View File

@ -0,0 +1,17 @@
package com.example.nekontakte.core.repository;
import java.util.List;
public interface BaseRepository<E, T> {
List<E> getAll();
E get(T id);
E create(E entity);
E update(E entity);
E delete(E entity);
void deleteAll();
}

View File

@ -0,0 +1,64 @@
package com.example.nekontakte.core.repository;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import com.example.nekontakte.core.model.BaseEntity;
public abstract class MapRepository<E extends BaseEntity> implements BaseRepository<E, Integer> {
private final Map<Integer, E> entities = new TreeMap<>();
private Integer lastId = 0;
private boolean checkNull(E entity) {
if (get(entity.getId()) == null)
return false;
return true;
}
protected MapRepository() {
}
@Override
public List<E> getAll() {
return entities.values().stream().toList();
}
@Override
public E get(Integer id) {
return entities.get(id);
}
@Override
public E create(E entity) {
lastId++;
entity.setId(lastId);
entities.put(lastId, entity);
return entity;
}
@Override
public E update(E entity) {
if (checkNull(entity)) {
entities.put(entity.getId(), entity);
return entity;
}
return null;
}
@Override
public E delete(E entity) {
if (checkNull(entity)) {
entities.remove(entity.getId());
return entity;
}
return null;
}
@Override
public void deleteAll() {
entities.clear();
lastId = 0;
}
}

View File

@ -0,0 +1,69 @@
package com.example.nekontakte.users.api;
import com.example.nekontakte.core.configurations.Constants;
import com.example.nekontakte.users.model.UserEntity;
import com.example.nekontakte.users.service.UserService;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import jakarta.validation.Valid;
import java.util.List;
import org.modelmapper.ModelMapper;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(Constants.API_URL + "/user")
public class UserController {
private final UserService userService;
private final ModelMapper modelMapper;
public UserController(UserService userService, ModelMapper modelMapper) {
this.modelMapper = modelMapper;
this.userService = userService;
}
private UserEntity toEntity(UserDTO dto) {
return modelMapper.map(dto, UserEntity.class);
}
private UserDTO toDTO(UserEntity entity) {
return modelMapper.map(entity, UserDTO.class);
}
@GetMapping
public List<UserDTO> getAll() {
return userService.getAll().stream().map(this::toDTO).toList();
}
@GetMapping("/{id}")
public UserDTO get(@PathVariable(name = "id") Integer id) {
return toDTO(userService.get(id));
}
@PostMapping
public UserDTO create(@RequestBody @Valid UserDTO userDTO) {
if (userDTO.getName() == null) {
throw new RuntimeException("What a f*ck????");
}
return toDTO(userService.create(toEntity(userDTO)));
}
@PutMapping("/{id}")
public UserDTO update(@PathVariable(name = "id") Integer id, @RequestBody UserDTO userDTO) {
return toDTO(userService.update(id, toEntity(userDTO)));
}
@DeleteMapping("/{id}")
public UserDTO delete(@PathVariable(name = "id") Integer id) {
return toDTO(userService.delete(id));
}
}

View File

@ -0,0 +1,119 @@
package com.example.nekontakte.users.api;
import java.sql.Date;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
public class UserDTO {
private Integer id;
@NotBlank
private String name;
@NotBlank
private String surname;
@NotNull
private Date birthday;
private String city;
private String avatarImg;
@NotBlank
private String username;
@NotBlank
private String password;
@NotNull
private boolean isAdmin;
private String status;
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getAvatarImg() {
return avatarImg;
}
public void setAvatarImg(String avatarImg) {
this.avatarImg = avatarImg;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean getIsAdmin() {
return isAdmin;
}
public void setIsAdmin(boolean isAdmin) {
this.isAdmin = isAdmin;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}

View File

@ -0,0 +1,150 @@
package com.example.nekontakte.users.model;
import java.sql.Date;
import java.util.Objects;
import com.example.nekontakte.core.model.BaseEntity;
public class UserEntity extends BaseEntity {
private String name;
private String surname;
private Date birthday;
private String city;
private String avatarImg;
private String username;
private String password;
private boolean isAdmin;
private String status;
public UserEntity() {
}
public UserEntity(
Integer id,
String username,
String password,
boolean isAdmin,
String name,
String surname,
Date birthday,
String city,
String avatarImg,
String status) {
super(id);
this.username = username;
this.password = password;
this.name = name;
this.surname = surname;
this.birthday = birthday;
this.city = city;
this.avatarImg = avatarImg;
this.status = status;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getAvatarImg() {
return avatarImg;
}
public void setAvatarImg(String avatarImg) {
this.avatarImg = avatarImg;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean getIsAdmin() {
return isAdmin;
}
public void setIsAdmin(boolean isAdmin) {
this.isAdmin = isAdmin;
}
@Override
public int hashCode() {
return Objects.hash(
id,
username,
password,
isAdmin,
name,
surname,
status,
city,
birthday,
avatarImg);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass())
return false;
final UserEntity other = (UserEntity) obj;
return Objects.equals(other.getId(), id) &&
Objects.equals(other.getUsername(), username) &&
Objects.equals(other.getIsAdmin(), isAdmin) &&
Objects.equals(other.getPassword(), password) &&
Objects.equals(other.getName(), name) &&
Objects.equals(other.getSurname(), surname) &&
Objects.equals(other.getStatus(), status) &&
Objects.equals(other.getCity(), city) &&
Objects.equals(other.getBirthday(), birthday) &&
Objects.equals(other.getAvatarImg(), avatarImg);
}
}

View File

@ -0,0 +1,10 @@
package com.example.nekontakte.users.repository;
import org.springframework.stereotype.Repository;
import com.example.nekontakte.core.repository.MapRepository;
import com.example.nekontakte.users.model.UserEntity;
@Repository
public class UserRepository extends MapRepository<UserEntity> {
}

View File

@ -0,0 +1,51 @@
package com.example.nekontakte.users.service;
import java.util.List;
import java.util.Optional;
import org.springframework.stereotype.Service;
import com.example.nekontakte.core.errors.NotFoundException;
import com.example.nekontakte.users.model.UserEntity;
import com.example.nekontakte.users.repository.UserRepository;
@Service
public class UserService {
private final UserRepository repository;
public UserService(UserRepository repository) {
this.repository = repository;
}
public List<UserEntity> getAll() {
return repository.getAll();
}
public UserEntity get(Integer id) {
return Optional.ofNullable(repository.get(id)).orElseThrow(() -> new NotFoundException(id));
}
public UserEntity create(UserEntity entity) {
return repository.create(entity);
}
public UserEntity update(Integer id, UserEntity entity) {
final UserEntity existsentity = get(id);
existsentity.setUsername(entity.getUsername());
existsentity.setPassword(entity.getPassword());
existsentity.setIsAdmin(entity.getIsAdmin());
existsentity.setName(entity.getName());
existsentity.setSurname(entity.getSurname());
existsentity.setStatus(entity.getStatus());
existsentity.setBirthday(entity.getBirthday());
existsentity.setCity(entity.getCity());
existsentity.setStatus(entity.getStatus());
return repository.update(existsentity);
}
public UserEntity delete(Integer id) {
final UserEntity existsentity = get(id);
return repository.delete(existsentity);
}
}