Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

init structure, add liquibase #9

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 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
82 changes: 82 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
<maven.checkstyle.plugin.configLocation>
https://raw.githubusercontent.com/mate-academy/style-guides/master/java/checkstyle.xml
</maven.checkstyle.plugin.configLocation>
<lombok.mapstruct.binding.version>0.2.0</lombok.mapstruct.binding.version>
<mapstruct.version>1.5.5.Final</mapstruct.version>
</properties>
<dependencies>
<dependency>
Expand All @@ -37,14 +39,71 @@
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

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

<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>

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

<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>${mapstruct.version}</version>
</dependency>

<dependency>
<groupId>org.liquibase</groupId>
<artifactId>liquibase-core</artifactId>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.1.0</version>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</path>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok-mapstruct-binding</artifactId>
<version>${lombok.mapstruct.binding.version}</version>
</path>
<path>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>${mapstruct.version}</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
Expand All @@ -68,6 +127,29 @@
<linkXRef>false</linkXRef>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>3.3.0</version>
<executions>
<execution>
<phase>compile</phase>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
<configuration>
<configLocation>${maven.checkstyle.plugin.configLocation}</configLocation>
<inputEncoding>UTF-8</inputEncoding>
<outputEncoding>UTF-8</outputEncoding>
<consoleOutput>true</consoleOutput>
<failsOnError>true</failsOnError>
<linkXRef>false</linkXRef>
<sourceDirectories>src</sourceDirectories>
</configuration>
</plugin>

</plugins>
</build>

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package mate.academy.rickandmorty.api.util;

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

@Configuration
public class ApiClientConfiguration {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package mate.academy.rickandmorty.api.util;

import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import mate.academy.rickandmorty.repository.PersonageRepository;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
public class PersonageDatabasePopulator {
private final RickAndMortyClient rickAndMortyApiClient;
private final PersonageRepository personageRepository;

@PostConstruct
public void init() {
if (personageRepository.count() != 0) {
personageRepository.deleteAll();
}
personageRepository.saveAll(rickAndMortyApiClient.getAllPersonages());
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package mate.academy.rickandmorty.api.util;

import java.util.ArrayList;
import java.util.List;
import lombok.RequiredArgsConstructor;
import mate.academy.rickandmorty.dto.external.ExternalResponseDto;
import mate.academy.rickandmorty.dto.external.Result;
import mate.academy.rickandmorty.mapper.PersonageMapper;
import mate.academy.rickandmorty.model.Personage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
@RequiredArgsConstructor
public class RickAndMortyClient {
private final PersonageMapper personageMapper;
private final RestTemplate restTemplate;
@Value("${rick-and-morty.api.url}")
private String baseCharacterUrl;

public List<Personage> getAllPersonages() {
List<Result> resultList = new ArrayList<>();
ExternalResponseDto externalResponseDto =
restTemplate.getForEntity(baseCharacterUrl, ExternalResponseDto.class).getBody();
String nextUrl = externalResponseDto.info().next();
while (nextUrl != null) {
resultList.addAll(externalResponseDto.resultList());
externalResponseDto = restTemplate
.getForEntity(nextUrl, ExternalResponseDto.class)
.getBody();
nextUrl = externalResponseDto.info().next();
}
return resultList
.stream()
.map(personageMapper::toPersonage)
.toList();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package mate.academy.rickandmorty.controller;

import io.swagger.v3.oas.annotations.Operation;
import java.util.List;
import lombok.RequiredArgsConstructor;
import mate.academy.rickandmorty.dto.internal.PersonageResponseDto;
import mate.academy.rickandmorty.service.PersonageService;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequiredArgsConstructor
@RequestMapping("/rick-and-morty")
public class RickAndMortyController {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't see any Swagger documentation :)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's add Tag annotation

private final PersonageService personageRepository;

@GetMapping("/random-personage")
@Operation(summary = "Get random personage",
description = "Get random personage from Rick and Morty universe")
public PersonageResponseDto getRandomPersonage() {
return personageRepository.getRandomPersonage();
}

@GetMapping("/search")
@Operation(summary = "Get personages by name",
description = "Get from Rick and Morty universe "
+ "personages witch has name in their name")
public List<PersonageResponseDto> getPersonageByName(
@PageableDefault(page = 0, size = 10, sort = "name") Pageable pageable,
@RequestParam String name
) {
return personageRepository.getPersonageByNameLike(pageable, name);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package mate.academy.rickandmorty.dto.external;

import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;

public record ExternalResponseDto(
Info info,
@JsonProperty("results") List<Result> resultList
) {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package mate.academy.rickandmorty.dto.external;

public record Info(
Long count,
Integer pages,
String next,
String prev
) {
}
11 changes: 11 additions & 0 deletions src/main/java/mate/academy/rickandmorty/dto/external/Result.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package mate.academy.rickandmorty.dto.external;

import com.fasterxml.jackson.annotation.JsonProperty;

public record Result(
@JsonProperty("id") Long externalId,
String name,
String status,
String gender
) {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package mate.academy.rickandmorty.dto.internal;

public record PersonageResponseDto(Long id,
Long externalId,
String name,
String status,
String gender) {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package mate.academy.rickandmorty.excpetion;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

@ControllerAdvice
public class CustomGlobalExceptionHandler extends ResponseEntityExceptionHandler {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

don't you need @ControllerAdvice?

@ExceptionHandler(Exception.class)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

?

Suggested change
@ExceptionHandler(Exception.class)
@ExceptionHandler(EntityNotFoundException.class)

public ResponseEntity<Object> handleEntityNotFound(Exception ex) {
return new ResponseEntity<>(ex.getMessage(), HttpStatus.SERVICE_UNAVAILABLE);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
return new ResponseEntity<>(ex.getMessage(), HttpStatus.SERVICE_UNAVAILABLE);
return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package mate.academy.rickandmorty.mapper;

import mate.academy.rickandmorty.dto.external.Result;
import mate.academy.rickandmorty.dto.internal.PersonageResponseDto;
import mate.academy.rickandmorty.model.Personage;
import org.mapstruct.InjectionStrategy;
import org.mapstruct.Mapper;
import org.mapstruct.NullValueCheckStrategy;

@Mapper(componentModel = "spring",
injectionStrategy = InjectionStrategy.CONSTRUCTOR,
nullValueCheckStrategy = NullValueCheckStrategy.ALWAYS,
implementationPackage = "<PACKAGE_NAME>.impl")
public interface PersonageMapper {
PersonageResponseDto toDto(Personage personage);

Personage toPersonage(Result result);
}
29 changes: 29 additions & 0 deletions src/main/java/mate/academy/rickandmorty/model/Personage.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package mate.academy.rickandmorty.model;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import lombok.Data;

@Entity
@Data
@Table(name = "personages")
public class Personage {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(name = "external_id", nullable = false)
private Long externalId;

@Column(nullable = false)
private String name;

@Column(nullable = false)
private String status;

private String gender;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package mate.academy.rickandmorty.repository;

import java.util.List;
import java.util.Optional;
import mate.academy.rickandmorty.model.Personage;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

@Repository
public interface PersonageRepository extends JpaRepository<Personage, Long> {
List<Personage> findAllByNameContains(Pageable pageable, String name);

@Query("from Personage p order by RAND() limit 1")
Optional<Personage> findRandomPersonage();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package mate.academy.rickandmorty.service;

import java.util.List;
import mate.academy.rickandmorty.dto.internal.PersonageResponseDto;
import org.springframework.data.domain.Pageable;

public interface PersonageService {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

remove empty line

List<PersonageResponseDto> getPersonageByNameLike(Pageable pageable, String name);

PersonageResponseDto getRandomPersonage();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package mate.academy.rickandmorty.service.impl;

import jakarta.persistence.EntityNotFoundException;
import java.util.List;
import lombok.RequiredArgsConstructor;
import mate.academy.rickandmorty.dto.internal.PersonageResponseDto;
import mate.academy.rickandmorty.mapper.PersonageMapper;
import mate.academy.rickandmorty.model.Personage;
import mate.academy.rickandmorty.repository.PersonageRepository;
import mate.academy.rickandmorty.service.PersonageService;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class PersonageServiceImpl implements PersonageService {
private final PersonageRepository personageRepository;
private final PersonageMapper personageMapper;

@Override
public List<PersonageResponseDto> getPersonageByNameLike(Pageable pageable, String name) {
return personageRepository.findAllByNameContains(pageable, name)
.stream()
.map(personageMapper::toDto)
.toList();
}

@Override
public PersonageResponseDto getRandomPersonage() {
Personage randomPersonage = personageRepository.findRandomPersonage()
.orElseThrow(() -> new EntityNotFoundException("Can't get random personage"));
return personageMapper.toDto(randomPersonage);
}
}
Loading