Skip to content
Closed
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
47 changes: 47 additions & 0 deletions gateway/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<?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">
<parent>
<artifactId>shareit</artifactId>
<groupId>ru.practicum</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>

<artifactId>shareit-gateway</artifactId>

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

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
11 changes: 11 additions & 0 deletions gateway/src/main/java/ru/practicum/shareit/ShareItGateway.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package ru.practicum.shareit;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ShareItGateway {
public static void main(String[] args) {
SpringApplication.run(ShareItGateway.class, args);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package ru.practicum.shareit.booking;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.util.DefaultUriBuilderFactory;
import ru.practicum.shareit.booking.dto.BookingDto;
import ru.practicum.shareit.client.BaseClient;
import java.util.Map;

@Service
public class BookingClient extends BaseClient {
private static final String API_PREFIX = "/bookings";

@Autowired
public BookingClient(@Value("${shareit-server.url}") String serverUrl, RestTemplateBuilder builder) {
super(builder.uriTemplateHandler(new DefaultUriBuilderFactory(serverUrl + API_PREFIX))
.requestFactory(() -> new HttpComponentsClientHttpRequestFactory()).build());
}

public ResponseEntity<Object> create(Long userId, BookingDto requestDto) {
return post("", userId, requestDto);
}

public ResponseEntity<Object> approve(Long userId, Long bookingId, boolean approved) {
// ИЗМЕНЕНО: используем URI template для корректной передачи boolean параметра
Map<String, Object> parameters = Map.of("approved", approved);
return patch("/" + bookingId + "?approved={approved}", userId, parameters, null);
}

public ResponseEntity<Object> getById(Long userId, Long bookingId) {
return get("/" + bookingId, userId);
}

public ResponseEntity<Object> getAllByBooker(Long userId, String state, Integer from, Integer size) {
Map<String, Object> parameters = Map.of(
"state", state,
"from", from,
"size", size
);
return get("?state={state}&from={from}&size={size}", userId, parameters);
}

public ResponseEntity<Object> getAllByOwner(Long userId, String state, Integer from, Integer size) {
Map<String, Object> parameters = Map.of(
"state", state,
"from", from,
"size", size
);
return get("/owner?state={state}&from={from}&size={size}", userId, parameters);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package ru.practicum.shareit.booking;

import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import ru.practicum.shareit.booking.dto.BookingDto;

@Controller
@RequestMapping(path = "/bookings")
@RequiredArgsConstructor
@Validated
public class BookingController {
private final BookingClient bookingClient;
private static final String USER_ID_HEADER = "X-Sharer-User-Id";

@PostMapping
public ResponseEntity<Object> create(@RequestHeader(USER_ID_HEADER) Long userId,
@Valid @RequestBody BookingDto bookingDto) {
return bookingClient.create(userId, bookingDto);
}

@PatchMapping("/{bookingId}")
public ResponseEntity<Object> approve(@RequestHeader(USER_ID_HEADER) Long userId,
@PathVariable Long bookingId,
@RequestParam boolean approved) {
return bookingClient.approve(userId, bookingId, approved);
}

@GetMapping("/{bookingId}")
public ResponseEntity<Object> getById(@RequestHeader(USER_ID_HEADER) Long userId,
@PathVariable Long bookingId) {
return bookingClient.getById(userId, bookingId);
}

@GetMapping
public ResponseEntity<Object> getAllByBooker(
@RequestHeader(USER_ID_HEADER) Long userId,
@RequestParam(name = "state", defaultValue = "ALL") String state,
@RequestParam(name = "from", defaultValue = "0") Integer from,
@RequestParam(name = "size", defaultValue = "10") Integer size) {
return bookingClient.getAllByBooker(userId, state, from, size);
}

@GetMapping("/owner")
public ResponseEntity<Object> getAllByOwner(
@RequestHeader(USER_ID_HEADER) Long userId,
@RequestParam(name = "state", defaultValue = "ALL") String state,
@RequestParam(name = "from", defaultValue = "0") Integer from,
@RequestParam(name = "size", defaultValue = "10") Integer size) {
return bookingClient.getAllByOwner(userId, state, from, size);
}
}
Original file line number Diff line number Diff line change
@@ -1,27 +1,19 @@
package ru.practicum.shareit.booking.dto;

import jakarta.validation.constraints.Future;
import jakarta.validation.constraints.FutureOrPresent;
import jakarta.validation.constraints.NotNull;
import lombok.*;
import lombok.experimental.FieldDefaults;

import java.time.LocalDateTime;

@Data
@AllArgsConstructor
@NoArgsConstructor
@AllArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE)
public class BookingDto {

@NotNull
Long itemId;

@NotNull
@FutureOrPresent
LocalDateTime start;

@NotNull
@Future
LocalDateTime end;
}
121 changes: 121 additions & 0 deletions gateway/src/main/java/ru/practicum/shareit/client/BaseClient.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
package ru.practicum.shareit.client;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.lang.Nullable;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.RestTemplate;

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

public class BaseClient {
protected final RestTemplate rest;

public BaseClient(RestTemplate rest) {
this.rest = rest;
}

protected ResponseEntity<Object> get(String path) {
return get(path, null, null);
}

protected ResponseEntity<Object> get(String path, long userId) {
return get(path, userId, null);
}

protected ResponseEntity<Object> get(String path, Long userId, @Nullable Map<String, Object> parameters) {
return makeAndSendRequest(HttpMethod.GET, path, userId, parameters, null);
}

protected <T> ResponseEntity<Object> post(String path, T body) {
return post(path, null, null, body);
}

protected <T> ResponseEntity<Object> post(String path, long userId, T body) {
return post(path, userId, null, body);
}

protected <T> ResponseEntity<Object> post(String path, Long userId, @Nullable Map<String, Object> parameters, T body) {
return makeAndSendRequest(HttpMethod.POST, path, userId, parameters, body);
}

protected <T> ResponseEntity<Object> put(String path, long userId, T body) {
return put(path, userId, null, body);
}

protected <T> ResponseEntity<Object> put(String path, Long userId, @Nullable Map<String, Object> parameters, T body) {
return makeAndSendRequest(HttpMethod.PUT, path, userId, parameters, body);
}

protected <T> ResponseEntity<Object> patch(String path, T body) {
return patch(path, null, null, body);
}

protected <T> ResponseEntity<Object> patch(String path, long userId) {
return patch(path, userId, null, null);
}

protected <T> ResponseEntity<Object> patch(String path, long userId, T body) {
return patch(path, userId, null, body);
}

protected <T> ResponseEntity<Object> patch(String path, Long userId, @Nullable Map<String, Object> parameters, T body) {
return makeAndSendRequest(HttpMethod.PATCH, path, userId, parameters, body);
}

protected ResponseEntity<Object> delete(String path) {
return delete(path, null, null);
}

protected ResponseEntity<Object> delete(String path, long userId) {
return delete(path, userId, null);
}

protected ResponseEntity<Object> delete(String path, Long userId, @Nullable Map<String, Object> parameters) {
return makeAndSendRequest(HttpMethod.DELETE, path, userId, parameters, null);
}

private <T> ResponseEntity<Object> makeAndSendRequest(HttpMethod method, String path, Long userId, @Nullable Map<String, Object> parameters, @Nullable T body) {
HttpEntity<T> requestEntity = new HttpEntity<>(body, defaultHeaders(userId));

ResponseEntity<Object> shareitServerResponse;
try {
if (parameters != null) {
shareitServerResponse = rest.exchange(path, method, requestEntity, Object.class, parameters);
} else {
shareitServerResponse = rest.exchange(path, method, requestEntity, Object.class);
}
} catch (HttpStatusCodeException e) {
return ResponseEntity.status(e.getStatusCode()).body(e.getResponseBodyAsByteArray());
}
return prepareGatewayResponse(shareitServerResponse);
}

private HttpHeaders defaultHeaders(Long userId) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(List.of(MediaType.APPLICATION_JSON));
if (userId != null) {
headers.set("X-Sharer-User-Id", String.valueOf(userId));
}
return headers;
}

private static ResponseEntity<Object> prepareGatewayResponse(ResponseEntity<Object> response) {
if (response.getStatusCode().is2xxSuccessful()) {
return response;
}

ResponseEntity.BodyBuilder responseBuilder = ResponseEntity.status(response.getStatusCode());

if (response.hasBody()) {
return responseBuilder.body(response.getBody());
}

return responseBuilder.build();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package ru.practicum.shareit.client;

import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package ru.practicum.shareit.exception;

import jakarta.validation.ConstraintViolationException;
import org.springframework.http.HttpStatus;
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 java.util.Map;

@RestControllerAdvice
public class ErrorHandler {

@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Map<String, String> handleValidation(final MethodArgumentNotValidException e) {
return Map.of("error", "Ошибка валидации");
}

@ExceptionHandler(ConstraintViolationException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Map<String, String> handleConstraintViolation(final ConstraintViolationException e) {
return Map.of("error", e.getMessage());
}

@ExceptionHandler(Throwable.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public Map<String, String> handleThrowable(final Throwable e) {
return Map.of("error", "Непредвиденная ошибка");
}
}
Loading
Loading