Skip to content

Commit

Permalink
checkStyle
Browse files Browse the repository at this point in the history
  • Loading branch information
SergeyMalyuga committed Nov 29, 2023
1 parent bc6a46c commit 2b32710
Show file tree
Hide file tree
Showing 17 changed files with 87 additions and 81 deletions.
1 change: 0 additions & 1 deletion src/main/java/ru/practicum/shareit/booking/Booking.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Accessors;
import ru.practicum.shareit.item.model.Item;
import ru.practicum.shareit.user.User;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,19 +80,15 @@ public List<BookingDto> getAllBookingCurrentUser(int userId, String state, Optio
switch (state) {
case "ALL":
if (from.isPresent() && size.isPresent()) {
int totalPages = bookingRepository.findByBookerIdWithPagination(userId, PageRequest.of(from.get(),
size.get())).getTotalPages();
if (totalPages > from.get()) {
return bookingRepository.findByBookerIdWithPagination(userId, PageRequest.of(from.get(),
size.get())).getContent()
if (from.isPresent() && from.get() >= 0 && size.isPresent() && size.get() > 0) {
return bookingRepository.findByBookerIdWithPagination(userId,
PageRequest.of((int) Math.ceil((double) from.get() / size.get()),
size.get())).getContent()
.stream().sorted((e1, e2) -> e2.getStart().compareTo(e1.getStart()))
.map(e -> bookingMapper.bookingDto(e))
.collect(Collectors.toList());
} else {
return bookingRepository.findByBookerIdWithPagination(userId,
PageRequest.of(totalPages - 1, size.get())).getContent()
.stream().map(e -> bookingMapper.bookingDto(e))
.collect(Collectors.toList());
throw new UnavailableItemException("Не допустимое значение.");
}
} else {
return bookingRepository.findByBookerEquals(user).stream().sorted((e1, e2) ->
Expand Down Expand Up @@ -143,18 +139,14 @@ public List<BookingDto> getAllBookingCurrentOwner(int userId, String state,
switch (state) {
case "ALL":
if (from.isPresent() && size.isPresent()) {
int totalPages = bookingRepository.findByItemOwnerId(userId, PageRequest.of(from.get(),
size.get())).getTotalPages();
if (totalPages > from.get()) {
if (from.isPresent() && from.get() >= 0 && size.isPresent() && size.get() > 0) {
return bookingRepository.findByItemOwnerId(userId,
PageRequest.of(from.get(), size.get(), Sort.by("id").descending()))
PageRequest.of((int) Math.ceil((double) from.get() / size.get()),
size.get(), Sort.by("id").descending()))
.getContent().stream()
.map(e -> bookingMapper.bookingDto(e)).collect(Collectors.toList());
} else {
return bookingRepository.findByItemOwnerId(userId,
PageRequest.of(totalPages - 1, size.get(), Sort.by("id")
.descending())).getContent().stream()
.map(e -> bookingMapper.bookingDto(e)).collect(Collectors.toList());
throw new UnavailableItemException("Не допустимое значение.");
}
} else {
return ownerBookingList.stream().sorted((e1, e2) -> e2.getStart().compareTo(e1.getStart()))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,8 @@ private ItemDto addBookingToItem(Item item, ItemDto itemDto) {
.filter(e -> e.getEnd().isBefore(LocalDateTime.now()))
.sorted((e1, e2) -> e2.getEnd().compareTo(e1.getEnd())).collect(Collectors.toList());
List<Booking> bookingListLastAfterNow = item.getBookingList().stream()
.filter(e -> e.getEnd().isAfter(LocalDateTime.now()) && !e.getStatus().toString().equals("REJECTED")).collect(Collectors.toList());
.filter(e -> e.getEnd().isAfter(LocalDateTime.now()) && !e.getStatus()
.toString().equals("REJECTED")).collect(Collectors.toList());
if (bookingListLast.size() >= 1 && bookingListNext.size() >= 1) {
itemDto.setLastBooking(bookingMapper.bookingDto(bookingListLast.get(0)));
itemDto.getLastBooking().setBookerId(bookingListLast.get(0).getBooker().getId());
Expand All @@ -133,16 +134,13 @@ public Item getItemById(int itemId, int userId) {
@Override
public List<ItemDto> getAllItemForOwner(int ownerId, Optional<Integer> from, Optional<Integer> size) {
if (from.isPresent() && size.isPresent()) {
int totalPages = itemRepository.findByOwnerId(ownerId,
PageRequest.of(from.get(), size.get())).getTotalPages();
if (totalPages > from.get()) {
if (from.isPresent() && from.get() >= 0 && size.isPresent() && size.get() > 0) {
return itemRepository.findByOwnerId(ownerId,
PageRequest.of(from.get(), size.get(), Sort.by("id").descending())).stream()
PageRequest.of((int) Math.ceil((double)from.get() / size.get()),
size.get(), Sort.by("id").descending())).stream()
.map(e -> itemMapper.itemDto(e)).collect(Collectors.toList());
} else {
return itemRepository.findByOwnerId(ownerId,
PageRequest.of(totalPages - 1, size.get(), Sort.by("id").descending())).stream()
.map(e -> itemMapper.itemDto(e)).collect(Collectors.toList());
throw new UnavailableItemException("Не допустимое значение.");
}
}
List<Item> itemList = itemRepository.findByOwnerId(ownerId).stream()
Expand All @@ -162,19 +160,14 @@ public List<ItemDto> searchItem(String request, Optional<Integer> from, Optional
return new ArrayList<>();
}
if (from.isPresent() && size.isPresent()) {
int totalPages = itemRepository
.findByNameOrDescriptionWithPagination(request, PageRequest.of(from.get(),
size.get())).getTotalPages();
if (totalPages > from.get()) {
if (from.isPresent() && from.get() >= 0 && size.isPresent() && size.get() > 0) {
return itemRepository
.findByNameOrDescriptionWithPagination(request, PageRequest.of(from.get(), size.get(),
Sort.by("id").descending())).getContent().stream()
.findByNameOrDescriptionWithPagination(request,
PageRequest.of((int) Math.ceil((double)from.get() / size.get()), size.get(),
Sort.by("id").descending())).getContent().stream()
.map(e -> itemMapper.itemDto(e)).collect(Collectors.toList());
} else {
return itemRepository
.findByNameOrDescriptionWithPagination(request, PageRequest.of(totalPages - 1, size.get(),
Sort.by("id").descending())).getContent().stream()
.map(e -> itemMapper.itemDto(e)).collect(Collectors.toList());
throw new UnavailableItemException("Не допустимое значение.");
}
} else {
itemsList.addAll(itemRepository.findByNameIgnoreCaseContaining(request));
Expand Down Expand Up @@ -203,7 +196,8 @@ public CommentDto addComment(int itemId, int userId, Comment comment) {
}
List<Booking> itemListBooking = bookingRepository.findByBookerEquals(user).stream()
.filter(e -> e.getItem().getId() == itemId && !e.getStatus().toString()
.equals("REJECTED") && !e.getStart().isAfter(LocalDateTime.now())).collect(Collectors.toList());
.equals("REJECTED") && !e.getStart()
.isAfter(LocalDateTime.now())).collect(Collectors.toList());
if (!itemListBooking.isEmpty()) {
itemDto.getComments().add(commentMapper.toCommentDto(comment));
} else {
Expand Down
6 changes: 4 additions & 2 deletions src/main/java/ru/practicum/shareit/request/Request.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package ru.practicum.shareit.request;

import lombok.*;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Accessors;
import ru.practicum.shareit.user.User;

import javax.persistence.*;
import javax.validation.constraints.NotBlank;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
import ru.practicum.shareit.request.service.RequestService;

import javax.validation.Valid;
import javax.validation.constraints.Min;
import java.util.List;
import java.util.Optional;

Expand All @@ -27,15 +26,15 @@ public List<RequestDto> getRequestsList(@RequestHeader("X-Sharer-User-Id") int u
}

@GetMapping("/{requestId}")
public RequestDto getRequestById(@RequestHeader("X-Sharer-User-Id") int userId
, @PathVariable(name = "requestId") int requestId) {
public RequestDto getRequestById(@RequestHeader("X-Sharer-User-Id") int userId,
@PathVariable(name = "requestId") int requestId) {
return requestService.getRequestById(requestId, userId);
}

@GetMapping("/all")
public List<RequestDto> getAllRequestsList(@RequestHeader("X-Sharer-User-Id") int userId
, @RequestParam(name = "from", required = false) Optional<Integer> from
, @RequestParam(name = "size", required = false) Optional<Integer> size) {
public List<RequestDto> getAllRequestsList(@RequestHeader("X-Sharer-User-Id") int userId,
@RequestParam(name = "from", required = false) Optional<Integer> from,
@RequestParam(name = "size", required = false) Optional<Integer> size) {
return requestService.getAllRequests(userId, from, size);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
public class RequestMapper {
public RequestDto toRequestDto(Request request) {
return new RequestDto().setId(request.getId())
//.setRequesterId(request.getRequesterId())
.setDescription(request.getDescription())
.setCreated(request.getCreated());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@

public interface RequestService {
RequestDto addRequest(Request request, int userId);
List<RequestDto> getRequestsList(int UserId);

List<RequestDto> getRequestsList(int userId);

RequestDto getRequestById(int requestId, int userId);

List<RequestDto> getAllRequests(int userId, Optional<Integer> from, Optional<Integer> size);
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import ru.practicum.shareit.exception.NoDataFoundException;
import ru.practicum.shareit.exception.UnavailableItemException;
import ru.practicum.shareit.item.dao.ItemRepository;
import ru.practicum.shareit.item.dto.ItemRequestDto;
import ru.practicum.shareit.item.dto.ItemRequestDtoMapper;
Expand Down Expand Up @@ -77,9 +78,15 @@ public List<RequestDto> getAllRequests(int userId, Optional<Integer> from, Optio
if (from.isPresent() && size.isPresent()) {
List<RequestDto> requestDtoList = new ArrayList<>();
List<ItemRequestDto> itemRequestDtoList = new ArrayList<>();
List<Request> requestList = requestRepository
.findAllRequests(userId, PageRequest.of(from.get(), size.get()))
.getContent();
List<Request> requestList;
if (from.isPresent() && from.get() >= 0 && size.isPresent() && size.get() > 0) {
requestList = requestRepository
.findAllRequests(userId, PageRequest.of((int) Math.ceil((double) from.get() / size.get()),
size.get()))
.getContent();
} else {
throw new UnavailableItemException("Не допустимое значение.");
}
for (Request request : requestList) {
itemRequestDtoList.addAll(itemRepository.findByRequestId(request.getId())
.stream().map(e -> itemRequestDtoMapper.toItemRequestDto(e)).collect(Collectors.toList()));
Expand Down
15 changes: 5 additions & 10 deletions src/main/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,12 @@ logging.level.org.springframework.transaction=INFO
logging.level.org.springframework.transaction.interceptor=TRACE
logging.level.org.springframework.orm.jpa.JpaTransactionManager=DEBUG

#---
# TODO Append connection to DB
#---
spring.config.activate.on-profile=ci,test
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:shareit
spring.datasource.username=test
spring.datasource.password=test

spring.datasource.driverClassName=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/${db.name}
spring.datasource.username=andersen
spring.datasource.password=maluga4381457


db.name=shareit



Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,12 @@
import java.util.*;

import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import static org.junit.jupiter.api.Assertions.*;

@WebMvcTest(controllers = BookingController.class)
class BookingControllerTest {

Expand Down Expand Up @@ -91,18 +89,28 @@ void addBooking() throws Exception {
}

@Test
void confirmationOrRejectionBooking() {
}

@Test
void getBookingById() {
void getBookingById() throws Exception {
when(bookingService.getBookingById(Mockito.anyInt(), Mockito.anyInt()))
.thenReturn(bookingMapper.bookingDto(booking3));
mvc.perform(get("/bookings/3").header("X-Sharer-User-Id", 3))
.andExpect(status().isOk());
}

@Test
void getAllBookingCurrentUser() {
void getAllBookingCurrentUser() throws Exception {
when(bookingService.getAllBookingCurrentUser(Mockito.anyInt(), Mockito.anyString(),
Mockito.any(Optional.class), Mockito.any(Optional.class)))
.thenReturn(bookingDtoList);
mvc.perform(get("/bookings").header("X-Sharer-User-Id", 3))
.andExpect(status().isOk());
}

@Test
void getAllBookingCurrentOwner() {
void getAllBookingCurrentOwner() throws Exception {
when(bookingService.getAllBookingCurrentOwner(Mockito.anyInt(), Mockito.anyString(),
Mockito.any(Optional.class), Mockito.any(Optional.class)))
.thenReturn(bookingDtoList);
mvc.perform(get("/bookings/owner").header("X-Sharer-User-Id", 3))
.andExpect(status().isOk());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.annotation.DirtiesContext;
import ru.practicum.shareit.booking.Booking;
import ru.practicum.shareit.booking.BookingMapper;
import ru.practicum.shareit.booking.BookingStatus;
Expand All @@ -19,6 +20,7 @@
import static org.junit.jupiter.api.Assertions.assertEquals;

@DataJpaTest
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
class BookingRepositoryTest {
@Autowired
private EntityManager entityManager;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.data.domain.PageRequest;
import org.springframework.test.annotation.DirtiesContext;
import ru.practicum.shareit.item.model.Item;
import ru.practicum.shareit.user.User;

Expand All @@ -14,6 +15,7 @@
import static org.junit.jupiter.api.Assertions.assertEquals;

@DataJpaTest
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
class ItemRepositoryTest {

private Item item;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -109,15 +109,16 @@ void getItemById() {

@Test
void getAllItemForOwner() {
List<ItemDto> itemDtoList = itemService.getAllItemForOwner(1, Optional.of(0), Optional.of(3));
List<ItemDto> itemDtoList = itemService.getAllItemForOwner(1, Optional.of(0),
Optional.of(3));
List<Item> dbItem = entityManager.createQuery("FROM Item WHERE ownerId = 1").getResultList();
assertThat(dbItem.size(), equalTo(itemDtoList.size()));
}

@Test
void searchItem() {
List<ItemDto> itemDtoList = itemService.searchItem("Молоток", Optional.ofNullable(null)
, Optional.ofNullable(null));
List<ItemDto> itemDtoList = itemService.searchItem("Молоток", Optional.ofNullable(null),
Optional.ofNullable(null));
List<Item> dbItem = entityManager.createQuery("FROM Item WHERE name LIKE('%Молоток%')").getResultList();
assertThat(dbItem.size(), equalTo(itemDtoList.size()));
}
Expand All @@ -126,7 +127,8 @@ void searchItem() {
void addComment() throws InterruptedException {
TimeUnit.SECONDS.sleep(3);
CommentDto newComment = itemService.addComment(1, 2, comment);
Comment dbComment = entityManager.createQuery("FROM Comment WHERE author = 2", Comment.class).getSingleResult();
Comment dbComment = entityManager.createQuery("FROM Comment WHERE author = 2",
Comment.class).getSingleResult();
assertThat(newComment.getId(), equalTo(dbComment.getId()));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.data.domain.PageRequest;
import org.springframework.test.annotation.DirtiesContext;
import ru.practicum.shareit.request.Request;
import ru.practicum.shareit.user.User;

Expand All @@ -15,6 +16,7 @@
import static org.junit.jupiter.api.Assertions.assertEquals;

@DataJpaTest
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
class RequestRepositoryTest {
@Autowired
private EntityManager entityManager;
Expand All @@ -35,7 +37,8 @@ void findAllRequests() {
assertEquals(requestList.size(), 0);
entityManager.persist(user);
entityManager.persist(request);
requestList = requestRepository.findAllRequests(1, PageRequest.of(0, 1)).getContent();
assertEquals(requestList.size(), 1);
List<Request> requestList2 = requestRepository.findAllRequests(1,
PageRequest.of(0, 1)).getContent();
assertEquals(requestList.size(), requestList2.size());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ void getAllRequests() {
Optional<Integer> from = Optional.of(0);
Optional<Integer> size = Optional.of(2);
List<RequestDto> methodRequest = requestService.getAllRequests(1, from, size);
Query query = entityManager.createQuery("FROM Request WHERE requesterId = 1");
Query query = entityManager.createQuery("FROM Request WHERE requesterId != 1");
List<RequestDto> dbRequestDtotListList = query.getResultList();
System.out.println(methodRequest.size());
assertThat(dbRequestDtotListList.size(), equalTo(methodRequest.size()));
Expand Down
Loading

0 comments on commit 2b32710

Please sign in to comment.