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

hw done #187

Open
wants to merge 7 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
42 changes: 35 additions & 7 deletions pom.xml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?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">
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>org.springframework.boot</groupId>
Expand All @@ -19,28 +19,56 @@
<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>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>

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

<dependency>
<groupId>org.springframework.boot</groupId>
<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>
<version>${lombok.version}</version>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>1.5.5.Final</version>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.5.2.Final</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.1.0</version>
</dependency>
</dependencies>

<build>
Expand All @@ -52,7 +80,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>3.3.0</version>
<version>3.3.1</version>
<executions>
<execution>
<phase>compile</phase>
Expand All @@ -63,12 +91,12 @@
</executions>
<configuration>
<configLocation>${maven.checkstyle.plugin.configLocation}</configLocation>
<excludeGeneratedSources>true</excludeGeneratedSources>
<consoleOutput>true</consoleOutput>
<failsOnError>true</failsOnError>
<linkXRef>false</linkXRef>
</configuration>
</plugin>
</plugins>
</build>

</project>
</project>
63 changes: 63 additions & 0 deletions src/main/java/mate/academy/rickandmorty/ExternalDataFetcher.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package mate.academy.rickandmorty;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
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.CharacterDto;
import mate.academy.rickandmorty.dto.external.CharacterListDto;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
public class ExternalDataFetcher {
@Value("${url}")
private String url;
private final ObjectMapper objectMapper;
private final HttpClient httpClient = HttpClient.newHttpClient();

public List<CharacterDto> fetchAllCharacters() {
List<CharacterDto> allCharacters = new ArrayList<>();
int page = 1;
boolean hasMorePages = true;

while (hasMorePages) {
try {
HttpRequest request = HttpRequest.newBuilder()
.GET()
.uri(new URI(url + "?page=" + page))
.build();
HttpResponse<String> response = httpClient.send(
request,
HttpResponse.BodyHandlers.ofString()
);

String responseBody = response.body();
CharacterListDto characterListDto = parseResponse(responseBody);
allCharacters.addAll(characterListDto.characters());
hasMorePages = characterListDto.pagesInfo().next() != null;
page++;
} catch (IOException | InterruptedException | URISyntaxException e) {
throw new RuntimeException("Can't fetch data from API.", e);
}
}
return allCharacters;
}

public CharacterListDto parseResponse(String responseBody) {
try {
return objectMapper.readValue(responseBody, new TypeReference<>() {});
} catch (JsonProcessingException e) {
throw new RuntimeException("Can't parse response body.", e);
}
}
}
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,41 @@
package mate.academy.rickandmorty.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.util.List;
import lombok.RequiredArgsConstructor;
import mate.academy.rickandmorty.dto.internal.CharacterResponseDto;
import mate.academy.rickandmorty.service.CharacterService;
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
@RequestMapping("characters")
@RequiredArgsConstructor
@Tag(
name = "Characters",
description = "API to get info about characters"
)
public class CharacterController {
private final CharacterService characterService;

@GetMapping("/random")
@Operation(
summary = "Get a random character",
description = "Use this method to get random character from \"Rick and Morty\""
)
public CharacterResponseDto getRandom() {
return characterService.getRandomCharacter();
}

@GetMapping
@Operation(
summary = "Get characters by string",
description = "Use this method to find characters, whose name contains entered string"
)
public List<CharacterResponseDto> search(@RequestParam String name) {
return characterService.search(name);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package mate.academy.rickandmorty.dto.external;

public record CharacterDto(
Long id,
String status,
String gender
) {
}
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 CharacterListDto(
@JsonProperty("results") List<CharacterDto> characters,
@JsonProperty("info") PaginationDto pagesInfo
) {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package mate.academy.rickandmorty.dto.external;

import com.fasterxml.jackson.annotation.JsonProperty;

public record PaginationDto(@JsonProperty("next") String next) {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package mate.academy.rickandmorty.dto.internal;

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

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

@Mapper(config = MapperConfig.class)
public interface CharacterMapper {
@Mapping(source = "id", target = "externalId")
@Mapping(target = "id", ignore = true)
Character toModel(CharacterDto characterDto);

CharacterResponseDto toDto(Character character);
}
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 lombok.Getter;
import lombok.Setter;

@Entity(name = "characters")
@Getter
@Setter
public class Character {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(unique = true)
private String externalId;

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.repository;

import java.util.List;
import mate.academy.rickandmorty.model.Character;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface CharacterRepository extends JpaRepository<Character, Long> {
List<Character> findCharacterByNameLikeIgnoreCase(String name);
}
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.CharacterResponseDto;
import org.springframework.stereotype.Service;

@Service
public interface CharacterService {
CharacterResponseDto getRandomCharacter();

List<CharacterResponseDto> search(String name);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package mate.academy.rickandmorty.service;

import jakarta.annotation.PostConstruct;
import jakarta.persistence.EntityNotFoundException;
import java.util.List;
import lombok.RequiredArgsConstructor;
import mate.academy.rickandmorty.ExternalDataFetcher;
import mate.academy.rickandmorty.dto.external.CharacterDto;
import mate.academy.rickandmorty.dto.internal.CharacterResponseDto;
import mate.academy.rickandmorty.mapper.CharacterMapper;
import mate.academy.rickandmorty.model.Character;
import mate.academy.rickandmorty.repository.CharacterRepository;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class CharacterServiceImpl implements CharacterService {
private final CharacterRepository characterRepository;
private final CharacterMapper characterMapper;
private final ExternalDataFetcher dataFetcher;

@Override
public CharacterResponseDto getRandomCharacter() {
long count = characterRepository.count();
long randomId = (long) (Math.random() * count);
Character character = characterRepository.findById(randomId)
.orElseThrow(() ->
new EntityNotFoundException("Can't find character by id: " + randomId));
return characterMapper.toDto(character);
}

@Override
public List<CharacterResponseDto> search(String name) {
return characterRepository.findCharacterByNameLikeIgnoreCase("%" + name + "%").stream()
.map(characterMapper::toDto)
.toList();
}

@PostConstruct
public void init() {
List<CharacterDto> characterDtos = dataFetcher.fetchAllCharacters();
List<Character> characters = characterDtos.stream()
.map(characterMapper::toModel)
.toList();
characterRepository.saveAll(characters);
}
}
2 changes: 2 additions & 0 deletions src/test/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,5 @@ spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

url=https://rickandmortyapi.com/api/character
Loading