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 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
47 changes: 47 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,52 @@
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>

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

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

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

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

<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>1.5.2.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.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.17.2</version>
</dependency>
</dependencies>

<build>
Expand All @@ -66,6 +112,7 @@
<consoleOutput>true</consoleOutput>
<failsOnError>true</failsOnError>
<linkXRef>false</linkXRef>
<sourceDirectories>main</sourceDirectories>
</configuration>
</plugin>
</plugins>
Expand Down
78 changes: 78 additions & 0 deletions src/main/java/mate/academy/rickandmorty/ExternalDataFetcher.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
package mate.academy.rickandmorty;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.PostConstruct;
import jakarta.persistence.EntityNotFoundException;
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.model.Character;
import mate.academy.rickandmorty.repo.CharacterRepo;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
public class ExternalDataFetcher {
private static final String HOME_URL = "https://rickandmortyapi.com/api/character";
private final ObjectMapper objectMapper;
private final CharacterRepo characterRepo;

@PostConstruct
public void init() {
if (characterRepo.count() == 0) {
run();
}
}

public void run() {
HttpClient httpClient = HttpClient.newHttpClient();
String pageUrl = HOME_URL;

try {
while (!pageUrl.isEmpty()) {
HttpRequest httpRequest = HttpRequest.newBuilder()
.GET()
.uri(URI.create(pageUrl))
.build();
HttpResponse<String> response = httpClient.send(
httpRequest, HttpResponse.BodyHandlers.ofString()
);

JsonNode node = objectMapper.readTree(response.body());
BelitskyiAlexandr marked this conversation as resolved.
Show resolved Hide resolved
List<Character> characters = new ArrayList<>();
JsonNode results = node.get("results");
if (results != null) {
for (JsonNode result : results) {
characters.add(parseCharacter(result));
}
characterRepo.saveAll(characters);
}

JsonNode infoNode = node.get("info");
if (infoNode != null) {
pageUrl = infoNode.get("next").asText();
} else {
pageUrl = "";
}
}
} catch (IOException | InterruptedException e) {
throw new EntityNotFoundException("Cannot get data from Pick and Morty API", e);
}
}

private Character parseCharacter(JsonNode node) {
Character character = new Character();
character.setExternalId(node.get("id").asText());
character.setName(node.get("name").asText());
character.setGender(node.get("gender").asText());
character.setStatus(node.get("status").asText());

return character;
}
}
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,42 @@
package mate.academy.rickandmorty.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
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;

import java.util.List;

@RequiredArgsConstructor
@RestController
@RequestMapping("/characters")
@Tag(
name = "Characters",
description = "API to get info about characters"
)
public class CharacterController {
private final CharacterService characterService;

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

@Operation(
summary = "Get characters by string",
description = "Use this method to find characters, whose name contains entered string"
)
@GetMapping("search/{name}")
public List<CharacterDto> getCharactersByPartOfString(@PathVariable String partOfName) {
BelitskyiAlexandr marked this conversation as resolved.
Show resolved Hide resolved
return characterService.getCharactersByString(partOfName);
}
}
5 changes: 5 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,5 @@
package mate.academy.rickandmorty.dto;

public record CharacterDto (Long id, String externalId, String name,
BelitskyiAlexandr marked this conversation as resolved.
Show resolved Hide resolved
String status, String gender) {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package mate.academy.rickandmorty.mapper;

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

@Mapper(config = MapperConfig.class)
public interface CharacterMapper {
CharacterDto toDto(Character character);
}
23 changes: 23 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,23 @@
package mate.academy.rickandmorty.model;

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;

@Getter
@Setter
@Table(name = "characters")
@Entity
public class Character {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
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,9 @@
package mate.academy.rickandmorty.repo;

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

public interface CharacterRepo extends JpaRepository<Character, Long> {
List<Character> findByNameContaining(String name);
BelitskyiAlexandr marked this conversation as resolved.
Show resolved Hide resolved
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package mate.academy.rickandmorty.service;

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

public interface CharacterService {
CharacterDto getRandomCharacter();

List<CharacterDto> getCharactersByString(String namePart);


BelitskyiAlexandr marked this conversation as resolved.
Show resolved Hide resolved
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package mate.academy.rickandmorty.service;

import jakarta.persistence.EntityNotFoundException;
import java.util.List;
import java.util.Optional;
import java.util.Random;
import lombok.RequiredArgsConstructor;
import mate.academy.rickandmorty.dto.CharacterDto;
import mate.academy.rickandmorty.mapper.CharacterMapper;
import mate.academy.rickandmorty.model.Character;
import mate.academy.rickandmorty.repo.CharacterRepo;
import org.springframework.stereotype.Service;

@RequiredArgsConstructor
@Service
public class CharacterServiceImpl implements CharacterService{
private static final int NUMBER_OF_CHARACTERS = 826;
BelitskyiAlexandr marked this conversation as resolved.
Show resolved Hide resolved
BelitskyiAlexandr marked this conversation as resolved.
Show resolved Hide resolved
private final CharacterRepo characterRepo;
private final CharacterMapper characterMapper;
private final Random random = new Random();

@Override
public CharacterDto getRandomCharacter() {
Long id = random.nextLong(NUMBER_OF_CHARACTERS);
Optional<Character> character = characterRepo.findById(id);
return characterMapper.toDto(character.orElseThrow(() ->
new EntityNotFoundException("Character not found by id:" + id)));
}

@Override
public List<CharacterDto> getCharactersByString(String namePart) {
return characterRepo.findByNameContaining(namePart).stream()
.map(characterMapper::toDto)
.toList();
}
}
5 changes: 5 additions & 0 deletions src/main/resources/application.properties
Original file line number Diff line number Diff line change
@@ -1 +1,6 @@
spring.datasource.url=jdbc:mysql://localhost:3306/rick_and_morty?enabledTLSProtocols=TLSv1.2
spring.datasource.username=root
spring.datasource.password=rootroot
spring.jpa.hibernate.ddl-auto=update

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
9 changes: 4 additions & 5 deletions src/test/resources/application.properties
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.datasource.url=jdbc:mysql://localhost:3306/rick_and_morty
spring.datasource.username=root
BelitskyiAlexandr marked this conversation as resolved.
Show resolved Hide resolved
spring.datasource.password=rootroot
spring.jpa.hibernate.ddl-auto=update
Loading