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 2 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
78 changes: 78 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,67 @@
<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>
<version>${liquibase.version}</version>

Choose a reason for hiding this comment

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

there is no need to specify the version - it is taken from spring-boot-starter-parent

</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 +123,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
21 changes: 21 additions & 0 deletions src/main/java/mate/academy/rickandmorty/api/util/DbLoader.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
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 DbLoader {

Choose a reason for hiding this comment

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

Suggested change
public class DbLoader {
public class PersonageDatabasePopulator {

private final RickAndMortyApiClient rickAndMortyApiClient;
private final PersonageRepository personageRepository;

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

Choose a reason for hiding this comment

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

just wondering - do you need to keep only up-to-date personages?

if yes - then you might need to clear your db first and only then load the latest info from API:

if (personageRepository.count() != 0) {
  personageRepository.deleteAll();
}
personageRepository.saveAll(rickAndMortyApiClient.getAllPersonages());

Copy link
Author

Choose a reason for hiding this comment

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

I did it because in our task description was it: All data from the public API should be fetched once, and only once, when the Application context is created. But I uncorrected understood it, i thought that i had to do it only once

Choose a reason for hiding this comment

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

@teract10s no, you're right - you have to do that API call only once

I'm asking about DB state. imagine that you ran you application 2 times:

  1. DB is empty - call the API to save the personages
  2. DB is not empty - call the API to save the personages - a lot of duplicates as a result

}

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

import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
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.stereotype.Component;

@Component
@RequiredArgsConstructor
public class RickAndMortyApiClient {

Choose a reason for hiding this comment

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

minor

may be simplified to RickAndMortyClient

private static final String BASE_CHARACTER_URL = "https://rickandmortyapi.com/api/character";

Choose a reason for hiding this comment

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

this property should be stored in application properties and referenced via @Value

private final ObjectMapper objectMapper;
private final PersonageMapper personageMapper;

public List<Personage> getAllPersonages() {
List<Result> resultList = new ArrayList<>();
ExternalResponseDto externalResponseDto = getExternalResponseDto(BASE_CHARACTER_URL);

Choose a reason for hiding this comment

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

there is no need to pass the url as a parameter - you can simply access it inside of that method

while (externalResponseDto.getInfo().getNext() != null) {
resultList.addAll(externalResponseDto.getResultList());
externalResponseDto = getExternalResponseDto(externalResponseDto.getInfo().getNext());
}
return resultList
.stream()
.map(personageMapper::fromExternalResultToPersonage)
.toList();
}

private ExternalResponseDto getExternalResponseDto(String url) {
HttpClient httpClient = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.GET()
.uri(URI.create(url))
.build();
try {
HttpResponse<String> response = httpClient.send(
request, HttpResponse.BodyHandlers.ofString());
return objectMapper.readValue(response.body(), ExternalResponseDto.class);

Choose a reason for hiding this comment

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

JDK HttpClient if fine but....

you could define a RestTemplate bean and then use its method getForObject here

this way your code will be less verbose and more readable

} catch (IOException | InterruptedException e) {
throw new RuntimeException("Can't send request to url: " + url);

Choose a reason for hiding this comment

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

too generic :)

consider creating your custom exception (P.S. don't forget to handle that)

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

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.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")
public PersonageResponseDto getRandomPersonage() {
return personageRepository.getRandomPersonage();
}

@GetMapping("/search")
public List<PersonageResponseDto> getPersonageByName(
Pageable pageable, @RequestParam String name

Choose a reason for hiding this comment

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

you may make use of @PageableDefault here in case client did not provide pagination parameters

) {
return personageRepository.getPersonageByNameLike(pageable, name);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package mate.academy.rickandmorty.dto.external;

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

@Data
public class ExternalResponseDto {

Choose a reason for hiding this comment

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

why not record?

private Info info;
@JsonProperty("results")
private List<Result> resultList;
}
11 changes: 11 additions & 0 deletions src/main/java/mate/academy/rickandmorty/dto/external/Info.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package mate.academy.rickandmorty.dto.external;

import lombok.Data;

@Data
public class Info {

Choose a reason for hiding this comment

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

why not record?

private Long count;
private Integer pages;
private String next;
private String prev;
}
13 changes: 13 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,13 @@
package mate.academy.rickandmorty.dto.external;

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;

@Data
public class Result {

Choose a reason for hiding this comment

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

why not record

@JsonProperty("id")
private Long externalId;
private String name;
private String status;
private 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,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 fromExternalResultToPersonage(Result result);

Choose a reason for hiding this comment

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

toPersonage

}
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,16 @@
package mate.academy.rickandmorty.repository;

import java.util.List;
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")
Personage findRandomPersonage();

Choose a reason for hiding this comment

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

does it make sense to use Optional in case something went wrong and retrieval failed?

I'm not suggesting, I'm just wondering :)

Copy link
Author

Choose a reason for hiding this comment

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

I thought that here we with 100% will get some entity

}
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,32 @@
package mate.academy.rickandmorty.service.impl;

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();
return personageMapper.toDto(randomPersonage);
}
}
8 changes: 8 additions & 0 deletions src/main/resources/application.properties
Original file line number Diff line number Diff line change
@@ -1 +1,9 @@
spring.datasource.url=jdbc:mysql://localhost:3306/rick_and_morty
spring.datasource.username=root
spring.datasource.password=1234
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver

spring.jpa.hibernate.ddl-auto=validate
spring.jpa.show-sql=true

spring.jpa.open-in-view=false
Loading