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

Created API #133

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
59 changes: 59 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>
<mapstruct.version>1.5.5.Final</mapstruct.version>
<lombok.mapstruck.binding.version>0.2.0</lombok.mapstruck.binding.version>
</properties>
<dependencies>
<dependency>
Expand All @@ -41,6 +43,36 @@
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>

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

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

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

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

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

</dependencies>

<build>
Expand All @@ -66,6 +98,33 @@
<consoleOutput>true</consoleOutput>
<failsOnError>true</failsOnError>
<linkXRef>false</linkXRef>
<sourceDirectories>src/main</sourceDirectories>
</configuration>
</plugin>

<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.mapstruck.binding.version}</version>
</path>
<path>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>${mapstruct.version}</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
</plugins>
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,33 @@
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.CharacterDto;
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;

@Tag(name = "Character management", description = "Endpoints for managing characters")
@RequiredArgsConstructor
@RestController
@RequestMapping("/characters")
public class RickAndMortyController {
private final CharacterService characterService;

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

@GetMapping
@Operation(summary = "Get characters by name",
description = "Returns a list of all characters with the given name")
public List<CharacterDto> getCharactersByName(@RequestParam String name) {
return characterService.getCharactersByName(name);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package mate.academy.rickandmorty.dto.external;

import java.time.LocalDateTime;
import java.util.List;

public record CharacterResponseDataDto(
int id,
String name,
String status,
String species,
String type,
String gender,
OriginResponseDto origin,
OriginResponseDto location,
String image,
List<String> episode,
String url,
LocalDateTime created
) {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package mate.academy.rickandmorty.dto.external;

public record InfoResponseDto(
int count,
int pages,
String next,
String prev
) {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package mate.academy.rickandmorty.dto.external;

public record OriginResponseDto(
String name,
String url
) {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package mate.academy.rickandmorty.dto.external;

import java.util.List;

public record ResultsResponseDataDto(
List<CharacterResponseDataDto> results,
InfoResponseDto infoResponseDto
) {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package mate.academy.rickandmorty.dto.internal;

import lombok.Data;

@Data
public class CharacterDto {
private Long 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,16 @@
package mate.academy.rickandmorty.mapper;

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

@Mapper(config = MapperConfig.class)
public interface CharacterMapper {
CharacterDto toDto(Character character);

@Mapping(target = "externalId", source = "id")
Character toModel(CharacterResponseDataDto responseDataDto);
}
21 changes: 21 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,21 @@
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.Data;

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

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

public interface CharacterRepository extends JpaRepository<Character, Long> {
List<Character> findAllByNameContainingIgnoreCase(String name);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package mate.academy.rickandmorty.service;

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

public interface CharacterService {
CharacterDto getRandomCharacter();

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

import jakarta.annotation.PostConstruct;
import java.util.List;
import lombok.RequiredArgsConstructor;
import mate.academy.rickandmorty.mapper.CharacterMapper;
import mate.academy.rickandmorty.model.Character;
import mate.academy.rickandmorty.repository.CharacterRepository;
import org.springframework.stereotype.Component;

@RequiredArgsConstructor
@Component
public class CharactersInitializer {
private final CharacterRepository characterRepository;
private final RickAndMortyClient rickAndMortyClient;
private final CharacterMapper characterMapper;

@PostConstruct
public void fetchCharactersToDb() {
List<Character> characters = rickAndMortyClient.getCharacters().stream()
.map(characterMapper::toModel)
.toList();
characterRepository.saveAll(characters);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package mate.academy.rickandmorty.service;

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.CharacterResponseDataDto;
import mate.academy.rickandmorty.dto.external.ResultsResponseDataDto;
import org.springframework.stereotype.Component;

@RequiredArgsConstructor
@Component
public class RickAndMortyClient {
private static final String URL = "https://rickandmortyapi.com/api/character";
private final ObjectMapper objectMapper;

public List<CharacterResponseDataDto> getCharacters() {
List<CharacterResponseDataDto> characters = new ArrayList<>();
HttpClient httpClient = HttpClient.newHttpClient();
String page = URL;
while (page != null) {
HttpRequest httpRequest = HttpRequest.newBuilder()
.GET()
.uri(URI.create(page))
.build();
try {
HttpResponse<String> response = httpClient.send(
httpRequest, HttpResponse.BodyHandlers.ofString()
);
ResultsResponseDataDto resultsResponseDataDto = objectMapper
.readValue(response.body(), ResultsResponseDataDto.class);
characters.addAll(resultsResponseDataDto.results());
if (resultsResponseDataDto.infoResponseDto() != null
&& resultsResponseDataDto.infoResponseDto().next() != null) {
page = resultsResponseDataDto.infoResponseDto().next();
} else {
page = null;
}
} catch (IOException | InterruptedException e) {
throw new RuntimeException("Can't send http request", e);
}
}
return characters;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package mate.academy.rickandmorty.service.impl;

import jakarta.persistence.EntityNotFoundException;
import java.util.List;
import java.util.Random;
import lombok.RequiredArgsConstructor;
import mate.academy.rickandmorty.dto.internal.CharacterDto;
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.stereotype.Service;

@Service
@RequiredArgsConstructor
public class CharacterServiceImpl implements CharacterService {
private final CharacterRepository characterRepository;
private final CharacterMapper characterMapper;
private final Random random = new Random();

@Override
public CharacterDto getRandomCharacter() {
long randomId = random.nextLong(characterRepository.count());
Character character = characterRepository.findById(randomId)
.orElseThrow(() -> new EntityNotFoundException(
"Can't get character with id: " + randomId));
return characterMapper.toDto(character);
}

@Override
public List<CharacterDto> getCharactersByName(String name) {
return characterRepository.findAllByNameContainingIgnoreCase(name)
.stream()
.map(characterMapper::toDto)
.toList();
}
}
7 changes: 7 additions & 0 deletions 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?serverTimeZone=UTC
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.show-sql=true
spring.jpa.open-in-view=false
Loading