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
33 changes: 33 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
version: '3.8'
services:
gateway:
build: gateway
container_name: shareit_gateway_container
ports:
- "8080:8080"
depends_on:
- server
environment:
- SHAREIT_SERVER_URL=http://server:9090

server:
build: server
container_name: shareit_server_container
ports:
- "9090:9090"
depends_on:
- db
environment:
- SPRING_DATASOURCE_URL=jdbc:postgresql://db:5432/shareit
- SPRING_DATASOURCE_USERNAME=shareit
- SPRING_DATASOURCE_PASSWORD=root

db:
image: postgres:13.7-alpine
container_name: shareit_db_container
ports:
- "6541:5432"
environment:
- POSTGRES_DB=shareit
- POSTGRES_USER=shareit
- POSTGRES_PASSWORD=root
3 changes: 3 additions & 0 deletions gateway/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
FROM amazoncorretto:11
COPY target/*.jar app.jar
ENTRYPOINT ["java","-jar","/app.jar"]
73 changes: 73 additions & 0 deletions gateway/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>ru.practicum</groupId>
<artifactId>shareit</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>

<artifactId>shareit-gateway</artifactId>
<version>0.0.1-SNAPSHOT</version>

<name>ShareIt Gateway</name>

<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.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>

<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>
12 changes: 12 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,12 @@
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,51 @@
package ru.practicum.shareit.booking.client;

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.BookingRequestDto;
import ru.practicum.shareit.booking.dto.State;
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(HttpComponentsClientHttpRequestFactory::new)
.build());
}

public ResponseEntity<Object> getAllBookingsForUser(Long userId, State 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> getBooking(Long userId, Long bookingId) {
return get("/" + bookingId, userId);
}

public ResponseEntity<Object> getAllItemsBookingForUser(Long ownerId, State state, Integer from, Integer size) {
Map<String, Object> parameters = Map.of("state", state.name(), "from", from, "size", size);
return get("/owner?state={state}&from={from}&size={size}", ownerId, parameters);
}

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

public ResponseEntity<Object> updateStatus(Long userId, Long bookingId, Boolean approved) {
Map<String, Object> parameters = Map.of("approved", approved);
return patch("/" + bookingId + "?approved={approved}", userId, parameters, null);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
package ru.practicum.shareit.booking.controller;

import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import ru.practicum.shareit.booking.client.BookingClient;
import ru.practicum.shareit.booking.dto.BookingRequestDto;
import ru.practicum.shareit.booking.dto.State;
import ru.practicum.shareit.exeption.StateException;
import ru.practicum.shareit.utils.HttpHeaders;

import javax.validation.Valid;
import javax.validation.constraints.Positive;
import javax.validation.constraints.PositiveOrZero;

@Validated
@RestController
@RequiredArgsConstructor
@RequestMapping(path = "/bookings")
public class BookingController {

private final BookingClient bookingClient;

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

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

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

@PostMapping
public ResponseEntity<Object> create(@RequestHeader(name = HttpHeaders.USER_ID_HEADER) Long userId,
@Valid @RequestBody BookingRequestDto bookingRequestDto) {
return bookingClient.create(userId, bookingRequestDto);
}

@PatchMapping("/{bookingId}")
public ResponseEntity<Object> updateStatus(@RequestHeader(name = HttpHeaders.USER_ID_HEADER) Long userId,
@PathVariable Long bookingId, @RequestParam Boolean approved) {
return bookingClient.updateStatus(userId, bookingId, approved);
}

private State parseState(String state) {
try {
return State.valueOf(state);
} catch (IllegalArgumentException e) {
throw new StateException(String.format("Unknown state: %s", state));
}
}

}
10 changes: 10 additions & 0 deletions gateway/src/main/java/ru/practicum/shareit/booking/dto/State.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package ru.practicum.shareit.booking.dto;

public enum State {
ALL,
CURRENT,
PAST,
FUTURE,
WAITING,
REJECTED
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package ru.practicum.shareit.booking.dto;

public enum Status {
WAITING,
APPROVED,
REJECTED
}
126 changes: 126 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,126 @@
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 ResponseEntity<Object> get(String path, @Nullable Map<String, Object> parameters) {
return makeAndSendRequest(HttpMethod.GET, path, null, 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();
}
}
Loading