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

First solution of jv-rick-and-morty #118

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
77 changes: 77 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,57 @@
<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.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

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

<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>1.5.5.Final</version>
</dependency>

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

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

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

<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>1.5.5.Final</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 +117,32 @@
<consoleOutput>true</consoleOutput>
<failsOnError>true</failsOnError>
<linkXRef>false</linkXRef>
<sourceDirectories>src</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>0.2.0</version>
</path>
<path>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.5.5.Final</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
</plugins>
Expand Down
3 changes: 1 addition & 2 deletions src/main/java/mate/academy/rickandmorty/Application.java
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
package mate.academy.rickandmorty;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.SpringApplication;

@SpringBootApplication
public class Application {

Choose a reason for hiding this comment

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

Avoid unnecessary changes in your PRs.

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,33 @@
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.internal.CharacterInternalResponseDto;
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;

import java.util.List;

@Tag(name = "Rick and Morty character management", description = "Endpoints for managing Rick and Morty characters")
@RestController
@RequiredArgsConstructor
@RequestMapping("/characters")
public class CharacterController {
private final CharacterService characterService;

@GetMapping("/by-name")
@Operation(summary = "Get a character by name", description = "Get a character by name")
public List<CharacterInternalResponseDto> getCharactersByName(@RequestParam String name) {
return characterService.getCharactersByName(name);
}

@GetMapping("/random")
@Operation(summary = "Get a random character", description = "Get a random character")
public CharacterInternalResponseDto getRandomCharacter() {
return characterService.getRandomCharacter();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package mate.academy.rickandmorty.dto.external;

import java.time.LocalDateTime;
import java.util.ArrayList;
import lombok.Data;

@Data
public class CharacterExternalResponseDto {

Choose a reason for hiding this comment

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

You might use record instead of regular class for DTOs. Additionally, you won't require Lombok - @Data produces lots of boilerplate code.

private Long id;
private String name;
private String status;
private String species;
private String type;
private String gender;
private OriginResponseDto origin;
private OriginResponseDto location;
private String image;
private ArrayList<String> episode;
private String url;
private LocalDateTime created;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package mate.academy.rickandmorty.dto.external;

import java.util.List;

public record CharacterResponseDataDto(List<CharacterExternalResponseDto> results) {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package mate.academy.rickandmorty.dto.external;

import lombok.Data;

@Data
public class OriginResponseDto {
private String name;
private String url;
}
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 CharacterInternalResponseDto {
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,15 @@
package mate.academy.rickandmorty.mapper;

import mate.academy.rickandmorty.config.MapperConfig;
import mate.academy.rickandmorty.dto.external.CharacterExternalResponseDto;
import mate.academy.rickandmorty.dto.internal.CharacterInternalResponseDto;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;

@Mapper(config = MapperConfig.class)
public interface CharacterMapper {
@Mapping(target = "externalId", source = "id")
Character toModel(CharacterExternalResponseDto characterExternalResponseDto);

CharacterInternalResponseDto toDto(Character character);
}
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;

@Entity
@Data
@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,12 @@
package mate.academy.rickandmorty.repository;

import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

@Repository
public interface CharacterRepository extends JpaRepository<Character, Long> {
@Query(value = "SELECT c FROM Character c WHERE c.name LIKE CONCAT('%', :name, '%')")
List<Character> findAllByNameContainingIgnoreCase(String name);
Copy link

Choose a reason for hiding this comment

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

Consider removing the @query annotation for this method as Spring Data JPA's query derivation from method names can automatically generate the required query

}
19 changes: 19 additions & 0 deletions src/main/java/mate/academy/rickandmorty/service/CharacterInit.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package mate.academy.rickandmorty.service;

import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import mate.academy.rickandmorty.dto.external.CharacterResponseDataDto;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
public class CharacterInit {
private final RickAndMortyClient client;
private final CharacterService characterService;

@PostConstruct
public void initCharacters() {
CharacterResponseDataDto characters = client.getCharacters();
characterService.saveAll(characters.results());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package mate.academy.rickandmorty.service;

import java.util.List;
import mate.academy.rickandmorty.dto.external.CharacterExternalResponseDto;
import mate.academy.rickandmorty.dto.internal.CharacterInternalResponseDto;

public interface CharacterService {
CharacterInternalResponseDto getRandomCharacter();

List<CharacterInternalResponseDto> getCharactersByName(String name);

void saveAll(List<CharacterExternalResponseDto> characterExternalResponseDtoList);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
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 lombok.RequiredArgsConstructor;
import mate.academy.rickandmorty.dto.external.CharacterResponseDataDto;
import org.springframework.stereotype.Component;

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

public CharacterResponseDataDto getCharacters() {
HttpClient httpClient = HttpClient.newHttpClient();

HttpRequest request = HttpRequest.newBuilder()
.GET()
.uri(URI.create(BASE_URL))
.build();

try {
HttpResponse<String> response = httpClient.send(
request, HttpResponse.BodyHandlers.ofString());

return objectMapper.readValue(
response.body(), CharacterResponseDataDto.class);

Copy link

Choose a reason for hiding this comment

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

are you sure you receive all 826 characters with this implementation? Remember about pagination. You need some kind of a loop to check if there's a next page
image

} catch (IOException | InterruptedException e) {
throw new RuntimeException(e);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package mate.academy.rickandmorty.service.impl;

import java.util.List;
import java.util.Random;
import lombok.RequiredArgsConstructor;
import mate.academy.rickandmorty.dto.external.CharacterExternalResponseDto;
import mate.academy.rickandmorty.dto.internal.CharacterInternalResponseDto;
import mate.academy.rickandmorty.mapper.CharacterMapper;
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 CharacterMapper characterMapper;
private final CharacterRepository characterRepository;
private final Random random = new Random();

@Override
public CharacterInternalResponseDto getRandomCharacter() {
long randomId = random.nextLong(characterRepository.count());
Character character = characterRepository.findById(randomId)
.orElseThrow(() ->
new RuntimeException("Cannot find a character by id: " + randomId));
Copy link

Choose a reason for hiding this comment

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

it's better to throw more specific exceptions where possible, let's go for EntityNotFound or NoSuchElement exception here

return characterMapper.toDto(character);
}

@Override
public List<CharacterInternalResponseDto> getCharactersByName(String name) {
return characterRepository.findAllByNameContainingIgnoreCase(name).stream()
.map(characterMapper::toDto)
.toList();
}

@Override
public void saveAll(List<CharacterExternalResponseDto> characterExternalResponseDtoList) {
List<Character> characters = characterExternalResponseDtoList.stream()
.map(characterMapper::toModel)
.toList();
characterRepository.saveAll(characters);
}
}
8 changes: 8 additions & 0 deletions src/main/resources/application.properties
Original file line number Diff line number Diff line change
@@ -1 +1,9 @@
spring.datasource.url=jdbc:mysql://localhost:3306/rick_and_morty?serverTimeZone=UTC
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

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