Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
110 changes: 108 additions & 2 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -15,20 +15,99 @@
<description>SpringToDo</description>

<properties>
<java.version>21</java.version>
<java.version>17</java.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>

<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.skyscreamer</groupId>
<artifactId>jsonassert</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>postgresql</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</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-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.liquibase</groupId>
<artifactId>liquibase-core</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/io.micrometer/micrometer-core -->
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-core</artifactId>
<version>1.16.0-M2</version>
</dependency>
<dependency>
<groupId>jakarta.validation</groupId>
<artifactId>jakarta.validation-api</artifactId>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>1.6.3</version>
</dependency>
</dependencies>

<build>
Expand All @@ -37,6 +116,33 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.11.0</version>
<configuration>
<source>17</source>
<target>17</target>
<annotationProcessorPaths>
<path>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.5.5.Final</version>
</path>
<!-- если используешь Lombok -->
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.32</version>
</path>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok-mapstruct-binding</artifactId>
<version>0.2.0</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
</plugins>
</build>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,7 @@

@SpringBootApplication
public class SpringToDoApplication {

public static void main(String[] args) {
SpringApplication.run(SpringToDoApplication.class, args);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
package com.emobile.springtodo.configuration;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.fasterxml.jackson.databind.jsontype.BasicPolymorphicTypeValidator;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

@Configuration
@EnableCaching
public class RedisConfig {

@Bean
public GenericJackson2JsonRedisSerializer redisJsonSerializer() {
ObjectMapper om = JsonMapper.builder()
.findAndAddModules() // JavaTimeModule и др.
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.build();

// Важно: включаем type info, чтобы при чтении восстанавливался TaskResponse, а не LinkedHashMap
om.activateDefaultTyping(
BasicPolymorphicTypeValidator.builder()
.allowIfSubType("com.emobile.springtodo") // ограничь своими пакетами
.allowIfSubType("java.util")
.build(),
ObjectMapper.DefaultTyping.NON_FINAL
);

return new GenericJackson2JsonRedisSerializer(om);
}

@Bean
public CacheManager cacheManager(RedisConnectionFactory cf,
GenericJackson2JsonRedisSerializer jsonSer) {
RedisCacheConfiguration base = RedisCacheConfiguration.defaultCacheConfig()
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jsonSer))
.disableCachingNullValues()
.computePrefixWith(name -> "todo:" + name + "::")
.entryTtl(Duration.ofMinutes(30));

return RedisCacheManager.builder(cf)
.cacheDefaults(base)
.transactionAware()
.build();
}

@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory cf,
GenericJackson2JsonRedisSerializer jsonSer) {
RedisTemplate<String, Object> tpl = new RedisTemplate<>();
tpl.setConnectionFactory(cf);
tpl.setKeySerializer(new StringRedisSerializer());
tpl.setValueSerializer(jsonSer);
tpl.setHashKeySerializer(new StringRedisSerializer());
tpl.setHashValueSerializer(jsonSer);
return tpl;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package com.emobile.springtodo.controllers;

import com.emobile.springtodo.dto.ApiResponse;
import com.emobile.springtodo.exceptions.TaskNotFoundException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import com.emobile.springtodo.dto.ErrorResponse;
import org.springframework.web.bind.annotation.ResponseStatus;

@org.springframework.web.bind.annotation.ControllerAdvice
public class ControllerAdvice {
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(TaskNotFoundException.class)
public ApiResponse<ErrorResponse> TaskNotFoundExceptionHandler(TaskNotFoundException exception) {
return ApiResponse.error(new ErrorResponse("ACCESS_ERROR", exception.getMessage()));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
package com.emobile.springtodo.controllers;

import com.emobile.springtodo.dto.ApiResponse;
import com.emobile.springtodo.dto.ErrorResponse;
import jakarta.validation.ConstraintViolationException;
import org.springframework.http.*;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@RestControllerAdvice
@ResponseStatus(HttpStatus.BAD_REQUEST)
public class GlobalExceptionHandler {

@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
protected ApiResponse<ErrorResponse> handleMethodArgumentNotValid(
MethodArgumentNotValidException ex) {

List<Map<String, Object>> errors = ex.getBindingResult().getFieldErrors().stream()
.map(fe -> {
Map<String, Object> m = new LinkedHashMap<>();
m.put("field", fe.getField());
m.put("message", fe.getDefaultMessage() != null ? fe.getDefaultMessage() : "Invalid value");
Object rejected = fe.getRejectedValue();
if (rejected != null) {
m.put("rejectedValue", rejected);
}
return m;
})
.toList();

ProblemDetail pd = ProblemDetail.forStatus(HttpStatus.BAD_REQUEST);
pd.setTitle("Validation failed");
pd.setDetail("Invalid request body");
pd.setProperty("errors", errors);
return ApiResponse.error(new ErrorResponse("VALIDATION_ERROR", pd.toString()));
}

@ExceptionHandler(ConstraintViolationException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ApiResponse<ErrorResponse> handleConstraintViolation(ConstraintViolationException ex) {
List<Map<String, Object>> errors = ex.getConstraintViolations().stream()
.map(cv -> {
Map<String, Object> m = new LinkedHashMap<>();
m.put("field", cv.getPropertyPath().toString());
m.put("message", cv.getMessage() != null ? cv.getMessage() : "Invalid value");
Object invalid = cv.getInvalidValue();
if (invalid != null) {
m.put("rejectedValue", invalid);
}
return m;
})
.toList();

ProblemDetail pd = ProblemDetail.forStatus(HttpStatus.BAD_REQUEST);
pd.setTitle("Validation failed");
pd.setDetail("Invalid request parameters");
pd.setProperty("errors", errors);
return ApiResponse.error(new ErrorResponse("VALIDATION_ERROR", pd.toString()));
}

@ExceptionHandler(BindException.class)
protected ApiResponse<ErrorResponse> handleBindException(BindException ex) {

List<Map<String, Object>> errors = ex.getBindingResult().getFieldErrors().stream()
.map(fe -> {
Map<String, Object> m = new LinkedHashMap<>();
m.put("field", fe.getField());
m.put("message", fe.getDefaultMessage() != null ? fe.getDefaultMessage() : "Invalid value");
Object rejected = fe.getRejectedValue();
if (rejected != null) {
m.put("rejectedValue", rejected);
}
return m;
})
.toList();

ProblemDetail pd = ProblemDetail.forStatus(HttpStatus.BAD_REQUEST);
pd.setTitle("Validation failed");
pd.setDetail("Binding error");
pd.setProperty("errors", errors);
return ApiResponse.ok(new ErrorResponse("VALIDATION_ERROR", pd.toString()));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package com.emobile.springtodo.controllers;

import com.emobile.springtodo.dto.*;
import com.emobile.springtodo.services.TaskServiceInterface;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Positive;
import jakarta.validation.constraints.PositiveOrZero;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


import java.util.Collections;
import java.util.List;

@Slf4j
@RestController
@Validated
@RequiredArgsConstructor
@RequestMapping("/api/tasks")
public class TaskController {
private final TaskServiceInterface service;

@GetMapping
public ApiResponse<PageResponse<TaskResponse>> getAllTasks(
@RequestParam(defaultValue = "10") @Positive int limit,
@RequestParam(defaultValue = "0") @PositiveOrZero int offset) {

PaginatedResult<TaskResponse> taskResponses = service.getAllTasks(limit, offset);

PageResponse<TaskResponse> pageResponse = new PageResponse<>(
taskResponses.items(),
offset / limit,
limit,
taskResponses.totalCount()
);

return ApiResponse.ok(pageResponse);
}

@GetMapping("/{id}")
public ApiResponse<TaskResponse> getTaskById(@Positive @PathVariable Long id) {
return ApiResponse.ok(service.get(id));
}

@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public ApiResponse<TaskResponse> createTask(@Valid @RequestBody TaskCreateRequest taskCreateRequest) {
TaskResponse taskResponse = service.create(taskCreateRequest);
return ApiResponse.created(taskResponse);
}

@PutMapping("/{id}")
public ApiResponse<TaskResponse> updateTask(@Positive @PathVariable Long id,
@Valid @RequestBody TaskUpdateRequest taskUpdateRequest) {
return ApiResponse.ok(service.updateTask(id, taskUpdateRequest));
}

@DeleteMapping("/{id}")
public ApiResponse<String> deleteTask(@Positive @PathVariable Long id) {
service.deleteTask(id);
return ApiResponse.ok("Task delete successfully");
}
}
Loading