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

Solution #200

Open
wants to merge 2 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
24 changes: 24 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,36 @@
<artifactId>spring-boot-starter</artifactId>
</dependency>

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

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

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

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

<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.28</version>
<scope>provided</scope>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
Expand Down
29 changes: 29 additions & 0 deletions src/main/java/mate/academy/rickandmorty/config/AppConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package mate.academy.rickandmorty.config;

import java.util.Random;
import mate.academy.rickandmorty.service.CharacterService;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class AppConfig {

@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}

@Bean
public Random random() {
return new Random();
}

@Bean
public CommandLineRunner commandLineRunner(CharacterService characterService) {
return args -> {
characterService.fetchCharacters();
};
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
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.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
@RequiredArgsConstructor
@RequestMapping(value = "/api/characters")
@Tag(name = "Character API", description = "Operations related to characters from Rick and Morty")
public class CharacterController {
private final CharacterService characterService;

@GetMapping("/random")
@Operation(summary = "Get a random character",
description = "Returns a random character from the database.")
public CharacterResponseDto getRandomCharacter() {
return characterService.getRandomCharacter();
}

@GetMapping
@Operation(summary = "Search characters by name",
description = "Returns a list of characters whose name contains the specified word.")
public List<CharacterResponseDto> searchCharactersByName(@RequestParam String word) {
return characterService.searchCharactersByName(word);
}
}
14 changes: 14 additions & 0 deletions src/main/java/mate/academy/rickandmorty/dto/CharacterListDto.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package mate.academy.rickandmorty.dto;

import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
import lombok.Getter;
import lombok.Setter;
import mate.academy.rickandmorty.model.CharacterApiResponse;

@Getter
@Setter
public class CharacterListDto {
@JsonProperty("results")
private List<CharacterApiResponse> results;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package mate.academy.rickandmorty.dto;

public record CharacterResponseDto(
Long id,
int externalId,
String name,
String status,
String gender
) {
}
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.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import jakarta.validation.constraints.NotNull;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
@Entity
@Table(name = "characters")
public class Character {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private int externalId;
@NotNull
private String name;
private String status;
private String gender;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package mate.academy.rickandmorty.model;

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class CharacterApiResponse {
@JsonProperty("id")
private int id;
@JsonProperty("name")
private String name;
@JsonProperty("status")
private String status;
@JsonProperty("gender")
private String gender;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package mate.academy.rickandmorty.repository;

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> {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package mate.academy.rickandmorty.service;

import java.util.List;
import mate.academy.rickandmorty.dto.CharacterResponseDto;
import org.springframework.stereotype.Service;

@Service
public interface CharacterService {
void fetchCharacters();

CharacterResponseDto getRandomCharacter();

List<CharacterResponseDto> searchCharactersByName(String word);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
package mate.academy.rickandmorty.service.impl;

import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import mate.academy.rickandmorty.dto.CharacterListDto;
import mate.academy.rickandmorty.dto.CharacterResponseDto;
import mate.academy.rickandmorty.model.Character;
import mate.academy.rickandmorty.repository.CharacterRepository;
import mate.academy.rickandmorty.service.CharacterService;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

@Service
@RequiredArgsConstructor
public class CharacterServiceImpl implements CharacterService {
private final RestTemplate restTemplate;
private final CharacterRepository characterRepository;
private final Random random;

@Override
public void fetchCharacters() {
String url = "https://rickandmortyapi.com/api/character";
int page = 1;

while (true) {
String pageUrl = url + "?page=" + page;
CharacterListDto response;

try {
response = restTemplate.getForObject(pageUrl, CharacterListDto.class);
} catch (HttpClientErrorException e) {
if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
break;
}
throw e;
}

if (response == null || response.getResults() == null
|| response.getResults().isEmpty()) {
break;
}

List<Character> characters = response.getResults()
.stream()
.map(result -> {
Character character = new Character();
character.setExternalId(result.getId());

if (result.getName() != null) {
character.setName(result.getName());
} else {
throw new IllegalArgumentException("Field name is missing");
}

character.setGender(result.getGender());
character.setStatus(result.getStatus());
return character;
}).collect(Collectors.toList());

characterRepository.saveAll(characters);

page++;
}
}

@Override
public CharacterResponseDto getRandomCharacter() {
int randomId = random.nextInt(1, (int) characterRepository.count());
Character character = characterRepository
.findById(Long.valueOf(randomId))
.orElseThrow(() -> new RuntimeException("Character not found"));
return toDto(character);
}

@Override
public List<CharacterResponseDto> searchCharactersByName(String word) {
return characterRepository.findAll().stream()
.filter(ch -> ch.getName().toLowerCase().contains(word.toLowerCase()))
.map(this::toDto)
.collect(Collectors.toList());
}

public CharacterResponseDto toDto(Character character) {
return new CharacterResponseDto(
character.getId(),
character.getExternalId(),
character.getName(),
character.getStatus(),
character.getGender()
);
}
}
6 changes: 6 additions & 0 deletions src/main/resources/application.properties
Original file line number Diff line number Diff line change
@@ -1 +1,7 @@
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.h2.console.enabled=true

1 change: 1 addition & 0 deletions src/test/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true
Loading