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

task done, to review #19

Closed
wants to merge 7 commits into from
Closed
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
83 changes: 83 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@
<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>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<lombok.mapstruct.binding.version>0.2.0</lombok.mapstruct.binding.version>
</properties>
<dependencies>
<dependency>
Expand All @@ -32,11 +36,58 @@
<scope>test</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-data-jpa</artifactId>
</dependency>

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

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

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

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

<dependency>
<groupId>org.liquibase</groupId>
<artifactId>liquibase-core</artifactId>
<version>${liquibase.version}</version>
</dependency>

<dependency>
<groupId>org.liquibase</groupId>
<artifactId>liquibase-maven-plugin</artifactId>
<version>${liquibase.version}</version>
</dependency>

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

<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
Expand All @@ -63,12 +114,44 @@
</executions>
<configuration>
<configLocation>${maven.checkstyle.plugin.configLocation}</configLocation>
<sourceDirectories>src</sourceDirectories>
<consoleOutput>true</consoleOutput>
<failsOnError>true</failsOnError>
<linkXRef>false</linkXRef>
</configuration>
</plugin>
</plugins>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.11.0</version>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
<encoding>${project.build.sourceEncoding}</encoding>
<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>
</pluginManagement>
</build>

</project>
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,53 @@
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.external.ExternalCharResponseDto;
import mate.academy.rickandmorty.mapper.CharacterMapper;
import mate.academy.rickandmorty.model.Character;
import mate.academy.rickandmorty.service.CharacterService;
import mate.academy.rickandmorty.service.RickAndMortyClient;
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 to manage client character data base")
@RestController
@RequestMapping("/characters")
@RequiredArgsConstructor
public class CharacterController {
private final RickAndMortyClient client;
private final CharacterService service;
private final CharacterMapper mapper;

@Operation(summary = "show random character",
description = "show and save random character from client db")
@GetMapping("/random")
public ExternalCharResponseDto getRandomCharacter() {
return client.getRandomCharacter();
}

@Operation(summary = "saving all characters from client to db",
description = "save all char info from client db to yours,"
+ " only to use once for the first time with empty table")
@GetMapping("/save")
public void save() {
service.save();
}
Copy link

@Ivan95kos Ivan95kos Oct 24, 2023

Choose a reason for hiding this comment

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

Anyone who finds this endpoint may spam external api on your behalf. Please do not leave such obvious vulnerabilities in code
use @PostConstruct in client service instead of endpoint /save

Suggested change
@Operation(summary = "saving all characters from client to db",
description = "save all char info from client db to yours,"
+ " only to use once for the first time with empty table")
@GetMapping("/save")
public void save() {
service.save();
}


@Operation(summary = "show character by search name parameter",
description = "show character by string occurrence in his/her/its name")
Copy link

Choose a reason for hiding this comment

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

Suggested change
description = "show character by string occurrence in his/her/its name")
description = "show character by string occurrence in their name")

@GetMapping
public List<ExternalCharResponseDto> getCharactersBySearchString(
@RequestParam String searchString
) {
List<Character> charactersBySearchString =
service.getCharactersBySearchString(searchString);
return charactersBySearchString.stream()
.map(mapper::toDto)
.toList();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package mate.academy.rickandmorty.dto.external;

public record ExternalCharResponseDto(Long id,
Long externalId,
String name,
String status,
String gender) {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package mate.academy.rickandmorty.dto.internal;

public record InfoDto(Long count,
Long pages) {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package mate.academy.rickandmorty.dto.internal;

import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
import lombok.Data;

@Data
public class InternalCharListDto {
@JsonProperty("results")
private List<InternalCharResponseDto> results;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package mate.academy.rickandmorty.dto.internal;

public record InternalCharResponseDto(Long id,
String name,
String status,
String gender) {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package mate.academy.rickandmorty.mapper;

import mate.academy.rickandmorty.config.MapperConfig;
import mate.academy.rickandmorty.dto.external.ExternalCharResponseDto;
import mate.academy.rickandmorty.dto.internal.InternalCharResponseDto;
import mate.academy.rickandmorty.model.Character;
import org.mapstruct.Mapper;

@Mapper(config = MapperConfig.class)
public interface CharacterMapper {
default Character toEntity(InternalCharResponseDto responseDto) {
Character character = new Character();
character.setExternalId(responseDto.id());
character.setName(responseDto.name());
character.setStatus(responseDto.status());
character.setGender(responseDto.gender());
return character;
}

default ExternalCharResponseDto toDto(Character character) {
return new ExternalCharResponseDto(
character.getId(),
character.getExternalId(),
character.getName(),
character.getStatus(),
character.getGender()
);
}
}
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 com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import lombok.Data;

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

import mate.academy.rickandmorty.model.Character;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

public interface CharacterRepository extends JpaRepository<Character, Long> {
@Query(value = "SELECT * FROM characters c WHERE c.external_id = :id", nativeQuery = true)
Character findByExternalId(Long id);
}
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.model.Character;

public interface CharacterService {
void save();

List<Character> getCharactersBySearchString(String searchString);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
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.Random;
import lombok.RequiredArgsConstructor;
import mate.academy.rickandmorty.dto.external.ExternalCharResponseDto;
import mate.academy.rickandmorty.dto.internal.InternalCharListDto;
import mate.academy.rickandmorty.dto.internal.InternalCharResponseDto;
import mate.academy.rickandmorty.mapper.CharacterMapper;
import mate.academy.rickandmorty.model.Character;
import mate.academy.rickandmorty.repository.CharacterRepository;
import org.springframework.stereotype.Component;
import org.springframework.web.util.UriComponentsBuilder;

@Component
@RequiredArgsConstructor
public class RickAndMortyClient {

Choose a reason for hiding this comment

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

All data from the public API should be fetched once, and only once, when the Application context is created

private static final String GET_CHAR_BASE_URL = "https://rickandmortyapi.com/api/character/%s";
private static final String GET_ALL_BASE_URL = "https://rickandmortyapi.com/api/character";

Choose a reason for hiding this comment

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

save the API in properties instead of constants
you can use

@Value("${rick-and-morty-api}")
private String url;

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

public ExternalCharResponseDto getRandomCharacter() {
Random random = new Random();
int maxCharAmount = 826;
HttpClient httpClient = HttpClient.newHttpClient();
String url = GET_CHAR_BASE_URL.formatted(String.valueOf(random.nextInt(maxCharAmount)));
HttpRequest httpRequest = HttpRequest.newBuilder()
.GET()
.uri(URI.create(url))
.build();
try {
HttpResponse<String> response = httpClient
.send(httpRequest, HttpResponse.BodyHandlers.ofString());
InternalCharResponseDto internalCharResponseDto = objectMapper.readValue(
response.body(), InternalCharResponseDto.class
);
if (!characterRepository.findAll().isEmpty()) {
for (Character c : characterRepository.findAll()) {
if (c.getExternalId().equals(internalCharResponseDto.id())) {
return characterMapper.toDto(c);
}
}
}
Character saved = characterRepository
.save(characterMapper.toEntity(internalCharResponseDto));
return characterMapper.toDto(saved);
} catch (IOException | InterruptedException e) {
throw new RuntimeException(e);
}
}

public InternalCharListDto getAllCharacters(Integer page) {
HttpClient httpClient = HttpClient.newHttpClient();
String url = UriComponentsBuilder
.fromHttpUrl(GET_ALL_BASE_URL)
.queryParam("page", page)
.toUriString();
HttpRequest httpRequest = HttpRequest.newBuilder()
.GET()
.uri(URI.create(url))
.build();
try {
HttpResponse<String> response = httpClient
.send(httpRequest, HttpResponse.BodyHandlers.ofString());
return objectMapper.readValue(
response.body(),
InternalCharListDto.class
);
} catch (IOException | InterruptedException e) {
throw new RuntimeException(e);
}
}
}
Loading