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 Attempt #201

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
72 changes: 57 additions & 15 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.1.4</version>
<version>3.3.4</version>
<relativePath/>
</parent>
<groupId>mate.academy</groupId>
Expand All @@ -19,6 +19,9 @@
<maven.checkstyle.plugin.configLocation>
https://raw.githubusercontent.com/mate-academy/style-guides/master/java/checkstyle.xml
</maven.checkstyle.plugin.configLocation>
<lombok.version>1.18.34</lombok.version>
<lombok.mapstruct.binding.version>0.2.0</lombok.mapstruct.binding.version>
<mapstruct.version>1.5.5.Final</mapstruct.version>
</properties>
<dependencies>
<dependency>
Expand All @@ -37,35 +40,74 @@
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

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

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

<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</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>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>3.3.0</version>
<executions>
<execution>
<phase>compile</phase>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<configLocation>${maven.checkstyle.plugin.configLocation}</configLocation>
<consoleOutput>true</consoleOutput>
<failsOnError>true</failsOnError>
<linkXRef>false</linkXRef>
<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.mapstruct.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,27 @@
package mate.academy.rickandmorty.controller;

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(value = "/character")
Copy link

Choose a reason for hiding this comment

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

For API design consistency, it would be better to use a plural form '/characters' instead of '/character'.

public class CharacterController {
private final CharacterService characterService;

@GetMapping
Copy link

Choose a reason for hiding this comment

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

The method 'getRandomCharacter' does not have any explicit path. Consider adding an explicit path like '/random' to make it clear this endpoint is for getting a random character.

public CharacterDto getRandomCharacter() {
return characterService.getRandomCharacter();
}

@GetMapping("/{name}")
public List<CharacterDto> getCharactersByName(@PathVariable String name) {
return characterService.findCharacterByName(name);
}
}
9 changes: 9 additions & 0 deletions src/main/java/mate/academy/rickandmorty/dto/ApiPageInfo.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package mate.academy.rickandmorty.dto;

public record ApiPageInfo(
int pages,
int count,
String next,
String prev
) {
}
9 changes: 9 additions & 0 deletions src/main/java/mate/academy/rickandmorty/dto/ApiResponse.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package mate.academy.rickandmorty.dto;

import java.util.List;

public record ApiResponse(
ApiPageInfo info,
List<CharacterDto> results
) {
}
8 changes: 8 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,8 @@
package mate.academy.rickandmorty.dto;

public record CharacterDto(
Long id,
String name,
String status,
String gender
) {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
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;
import org.mapstruct.Mapping;
import java.util.List;

@Mapper(config = MapperConfig.class)
public interface CharacterMapper {

@Mapping(source = "id", target = "externalId")
Character toModel(CharacterDto characterDto);

@Mapping(source = "id", target = "externalId")
List<Character> toModelList(List<CharacterDto> characterDtoList);

CharacterDto toDto(Character character);

List<CharacterDto> toDtoList(List<Character> characterList);
}
26 changes: 26 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,26 @@
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.NoArgsConstructor;
import lombok.Setter;

@Entity
@Getter
@Setter
@NoArgsConstructor
@Table(name = "results")

public class Character {
Copy link

Choose a reason for hiding this comment

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

The class 'Character' might conflict with 'java.lang.Character'. Consider renaming your class to something more specific like 'RickAndMortyCharacter'.

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

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

public interface CharacterRepository extends JpaRepository<Character, Long>, JpaSpecificationExecutor<Character> {

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

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.PostConstruct;
import jakarta.persistence.EntityNotFoundException;
import lombok.RequiredArgsConstructor;
import mate.academy.rickandmorty.dto.ApiResponse;
import mate.academy.rickandmorty.dto.CharacterDto;
import mate.academy.rickandmorty.mapper.CharacterMapper;
import mate.academy.rickandmorty.model.Character;
import mate.academy.rickandmorty.repository.CharacterRepository;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
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;

@Service
@RequiredArgsConstructor
public class CharacterInitializer {
@Value("${api.url}")
private String apiUrl;
Copy link

Choose a reason for hiding this comment

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

The 'apiUrl' field should be final. Since we are injecting value from the property file, it should not be changed during runtime.

private final CharacterRepository characterRepository;
private final ObjectMapper objectMapper;
private final CharacterMapper characterMapper;

@PostConstruct
public void init() {
if(characterRepository.count() == 0) {
initCharactersFromExternalApi(apiUrl);
}
}
private void initCharactersFromExternalApi(String apiUrl) {
HttpClient client = HttpClient.newHttpClient();
List<CharacterDto> characterDtoList = new ArrayList<>();
try {
while (apiUrl != null) {
HttpRequest getRequest = HttpRequest.newBuilder()
.GET()
.uri(URI.create(apiUrl))
.build();
HttpResponse<String> response = client.send(getRequest,
HttpResponse.BodyHandlers.ofString());
ApiResponse apiResponse = objectMapper.readValue(
response.body(),
ApiResponse.class
);
characterDtoList.addAll(apiResponse.results());
apiUrl = apiResponse.info().next();
}
List<Character> characters = characterMapper.toModelList(characterDtoList);
characterRepository.saveAll(characters);
} catch (IOException | InterruptedException e) {
throw new EntityNotFoundException("Can't access results from external API", e);
Copy link

Choose a reason for hiding this comment

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

EntityNotFoundException is not the appropriate exception to throw when there is an error connecting to the external API. Consider creating a custom exception to handle this scenario.

}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package mate.academy.rickandmorty.service;

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

public interface CharacterService {
CharacterDto getRandomCharacter();
List<CharacterDto> findCharacterByName(String name);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package mate.academy.rickandmorty.service;

import jakarta.persistence.EntityNotFoundException;
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.repository.CharacterRepository;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

@Service
@RequiredArgsConstructor
public class CharacterServiceImpl implements CharacterService {

private final CharacterRepository characterRepository;
private final CharacterMapper characterMapper;

@Override
public CharacterDto getRandomCharacter() {
long count = characterRepository.count();
if(count == 0) {
throw new EntityNotFoundException("No character found");
}
long randomNumber = ThreadLocalRandom.current().nextLong(count);
return characterRepository.findById(randomNumber)
.map(characterMapper::toDto)
.orElseThrow(() -> new EntityNotFoundException("Character not found for ID: " + randomNumber));
}

@Override
public List<CharacterDto> findCharacterByName(String name) {
List<Character> character = characterRepository.findByNameContainingIgnoreCase(name);
return characterMapper.toDtoList(character);
}
}
9 changes: 9 additions & 0 deletions src/main/resources/application.properties
Original file line number Diff line number Diff line change
@@ -1 +1,10 @@
spring.datasource.url=jdbc:mysql://localhost:3306/rick-and-morty?createDatabaseIfNotExist=true
spring.datasource.username=root
spring.datasource.password=Styczen10!
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

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

api.url=https://rickandmortyapi.com/api/character
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

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