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

result #204

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
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
62 changes: 62 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,19 @@
<description>jv-rick-and-morty</description>
<properties>
<java.version>17</java.version>
<mapstruct.version>1.6.2</mapstruct.version>
<maven.checkstyle.plugin.version>3.1.1</maven.checkstyle.plugin.version>
<maven.checkstyle.plugin.configLocation>
https://raw.githubusercontent.com/mate-academy/style-guides/master/java/checkstyle.xml
</maven.checkstyle.plugin.configLocation>
</properties>
<dependencies>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>

Choose a reason for hiding this comment

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

Suggested change

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
Expand All @@ -32,6 +39,16 @@
<scope>test</scope>
</dependency>

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

Choose a reason for hiding this comment

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

Suggested change

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

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
Expand All @@ -41,6 +58,48 @@
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>

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

<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>${mapstruct.version}</version>
<scope>provided</scope>
</dependency>

<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok-mapstruct-binding</artifactId>
<version>0.2.0</version>
</dependency>

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

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

<dependency>
<groupId>org.liquibase</groupId>
<artifactId>liquibase-core</artifactId>
<version>${liquibase.version}</version>
</dependency>

<dependency>
<groupId>org.liquibase</groupId>
<artifactId>liquibase-maven-plugin</artifactId>
<version>${liquibase.version}</version>
</dependency>
</dependencies>

<build>
Expand All @@ -66,6 +125,9 @@
<consoleOutput>true</consoleOutput>
<failsOnError>true</failsOnError>
<linkXRef>false</linkXRef>
<sourceDirectories>
<sourceDirectory>src/main/java</sourceDirectory>
</sourceDirectories>
</configuration>
</plugin>
</plugins>
Expand Down
1 change: 0 additions & 1 deletion src/main/java/mate/academy/rickandmorty/Application.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@

@SpringBootApplication
public class Application {

public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
Expand Down
13 changes: 13 additions & 0 deletions src/main/java/mate/academy/rickandmorty/config/MapperConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package mate.academy.rickandmorty.config;

import org.mapstruct.InjectionStrategy;
import org.mapstruct.NullValueCheckStrategy;

@org.mapstruct.MapperConfig(
componentModel = "spring",
injectionStrategy = InjectionStrategy.CONSTRUCTOR,
nullValueCheckStrategy = NullValueCheckStrategy.ALWAYS,
implementationPackage = "<PACKAGE_NAME>.impl"
)
public class MapperConfig {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package mate.academy.rickandmorty.config;

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() {
return new RestTemplate();
}
}

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

import lombok.RequiredArgsConstructor;
import mate.academy.rickandmorty.dto.CharacterDto;
import mate.academy.rickandmorty.service.CharacterService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequiredArgsConstructor
@RequestMapping("/characters")
public class CharacterController {
private final CharacterService characterService;

@GetMapping("/random")
public CharacterDto getRandomCharacter() {
return characterService.getRandomCharacter();
}

@GetMapping("/{id}")
public CharacterDto getCharacterById(@PathVariable Long id) {
return characterService.getCharacterById(id);
}
}
12 changes: 12 additions & 0 deletions src/main/java/mate/academy/rickandmorty/dto/CharacterDto.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package mate.academy.rickandmorty.dto;

import lombok.Data;

@Data
public class CharacterDto {
private Long id;
private String internalId;
private String name;
private String status;
private String gender;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package mate.academy.rickandmorty.dto;

import lombok.Data;

@Data
public class CharacterExternalDto {
private Long id;
private String name;
private String status;
private String gender;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package mate.academy.rickandmorty.dto;

import java.util.List;
import java.util.Map;
import lombok.Data;

@Data
public class CharacterResponseDto {
private Map<String, Object> info;
private List<CharacterExternalDto> results;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package mate.academy.rickandmorty.mapper;

import mate.academy.rickandmorty.config.MapperConfig;
import mate.academy.rickandmorty.dto.CharacterDto;
import mate.academy.rickandmorty.dto.CharacterExternalDto;
import mate.academy.rickandmorty.model.Character;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;

@Mapper(config = MapperConfig.class)
public interface CharacterMapper {
String DEFAULT_ID = "default-id";

CharacterDto toDto(Character character);

@Mapping(target = "internalId", expression = "java(generateInternalId(characterResponseDto))")
Character toEntity(CharacterExternalDto characterResponseDto);

default String generateInternalId(CharacterExternalDto dto) {
return dto.getId() != null ? String.valueOf(dto.getId()) : DEFAULT_ID;
}
}
25 changes: 25 additions & 0 deletions src/main/java/mate/academy/rickandmorty/model/Character.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
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.Getter;
import lombok.Setter;

@Entity
@Getter
@Setter
@Table(name = "characters")
public class Character {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, unique = true)
private String internalId;

Choose a reason for hiding this comment

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

Suggested change
private String internalId;
@Column(nullable = false, unique = true)
private String internalId;

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

import mate.academy.rickandmorty.model.Character;
import org.springframework.data.jpa.repository.JpaRepository;

public interface CharacterRepository extends JpaRepository<Character, Long> {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package mate.academy.rickandmorty.service;

import java.util.List;
import mate.academy.rickandmorty.dto.CharacterDto;
import mate.academy.rickandmorty.dto.CharacterExternalDto;

public interface CharacterService {
CharacterDto getRandomCharacter();

CharacterDto getCharacterById(Long id);

List<CharacterExternalDto> fetchAllCharacters();

void saveAllCharactersToDb();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
package mate.academy.rickandmorty.service.impl;

import jakarta.persistence.EntityNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import mate.academy.rickandmorty.dto.CharacterDto;
import mate.academy.rickandmorty.dto.CharacterExternalDto;
import mate.academy.rickandmorty.dto.CharacterResponseDto;
import mate.academy.rickandmorty.mapper.CharacterMapper;
import mate.academy.rickandmorty.model.Character;
import mate.academy.rickandmorty.repository.CharacterRepository;
import mate.academy.rickandmorty.service.CharacterService;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
@RequiredArgsConstructor
public class CharacterServiceImpl implements CharacterService {
private static final String URL = "https://rickandmortyapi.com/api/character?page=";
private static final Long CHARACTER_MAX = 826L;
private static final String URL_NEXT_KEY = "next";
private static final Random RANDOM = new Random();
private final CharacterMapper characterMapper;
private final CharacterRepository characterRepository;
private final RestTemplate restTemplate;

@Override
public CharacterDto getRandomCharacter() {
return getCharacterById(RANDOM.nextLong(CHARACTER_MAX) + 1);
}

@Override
public CharacterDto getCharacterById(Long id) {
return characterMapper.toDto(characterRepository.findById(id).orElseThrow(()
-> new EntityNotFoundException("Can't find character by id " + id)));
}

@Override
public List<CharacterExternalDto> fetchAllCharacters() {
List<CharacterExternalDto> allCharacters = new ArrayList<>();
int page = 1;
CharacterResponseDto response;
do {
ResponseEntity<CharacterResponseDto> apiResponse = restTemplate.getForEntity(
URL + page, CharacterResponseDto.class
);
response = apiResponse.getBody();

if (response != null && response.getResults() != null) {
allCharacters.addAll(response.getResults());
}

String nextPageUrl = (String) response.getInfo().get(URL_NEXT_KEY);
page++;
} while (response != null && response.getInfo().get(URL_NEXT_KEY) != null);
return allCharacters;
}

@EventListener(ApplicationReadyEvent.class)
@Override
public void saveAllCharactersToDb() {
List<CharacterExternalDto> characters = fetchAllCharacters();
List<Character> characterEntities = characters.stream()
.map(characterMapper::toEntity)
.collect(Collectors.toList());
characterRepository.saveAll(characterEntities);
}
}
9 changes: 8 additions & 1 deletion src/main/resources/application.properties
Original file line number Diff line number Diff line change
@@ -1 +1,8 @@

spring.datasource.url=jdbc:mysql://localhost:3306/rick_and_morty
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect
spring.datasource.username=
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=validate
spring.jpa.show-sql=true
spring.jpa.open-in-view=false
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
databaseChangeLog:
- changeSet:
id: create-characters-table
author: SD
changes:
- createTable:
tableName: characters
columns:
- column:
name: id
type: BIGINT
autoIncrement: true
constraints:
primaryKey: true
nullable: false
- column:
name: internal_id
type: varchar(255)
constraints:
unique: true
nullable: false
- column:
name: name
type: varchar(255)
- column:
name: status
type: varchar(255)
- column:
name: gender
type: varchar(255)
3 changes: 3 additions & 0 deletions src/main/resources/db/changelog/db.changelog-master.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
databaseChangeLog:
- include:
file: db/changelog/changes/01-create-characters-table.yaml
Loading