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, Rick and Morty #181

Open
wants to merge 4 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
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
"id": 1,
"externalId": "1",
"name": "Rick Sanchez",
"status": "Alive",
"status": "Alive",
"gender": "Male"
}
```
Expand All @@ -29,7 +29,7 @@

1. You must use [public API](https://rickandmortyapi.com/documentation/#rest) (you should use REST API).
2. All data from the public API should be fetched once, and only once, when the Application context is created

### Tech Requirements

- Use MySQL DB in your app.
Expand Down
47 changes: 47 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,11 @@
<scope>test</scope>
</dependency>

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

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
Expand All @@ -41,6 +46,47 @@
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>

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

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

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

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

<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.5.2.Final</version>
<scope>provided</scope>
</dependency>

<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.17.2</version>
</dependency>
</dependencies>

<build>
Expand All @@ -66,6 +112,7 @@
<consoleOutput>true</consoleOutput>
<failsOnError>true</failsOnError>
<linkXRef>false</linkXRef>
<sourceDirectories>main</sourceDirectories>
</configuration>
</plugin>
</plugins>
Expand Down
1 change: 0 additions & 1 deletion src/main/java/mate/academy/rickandmorty/Application.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@

@SpringBootApplication
public class Application {

public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
Expand Down
14 changes: 14 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,14 @@
package mate.academy.rickandmorty.config;

import org.mapstruct.InjectionStrategy;
import org.mapstruct.NullValueCheckStrategy;

@org.mapstruct.MapperConfig(
componentModel = "spring",
injectionStrategy = InjectionStrategy.CONSTRUCTOR,
nullValueCheckStrategy = NullValueCheckStrategy.ALWAYS,
implementationName = "<CLASS_NAME>Impl"
)
public class MapperConfig {

}
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.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;

@RequiredArgsConstructor
@RestController
@RequestMapping("/characters")
@Tag(name = "Characters", description = "Operations related to characters")
public class CharacterController {
private final CharacterService characterService;

@GetMapping("/random")
@Operation(summary = "Get a random character",
description = "Retrieve a random character from \"Rick and Morty\"")
public CharacterDto getRandomCharacter() {
return characterService.getRandomCharacter();
}

@GetMapping("/search/{name}")
@Operation(summary = "Get characters by name",
description = "Retrieve a list of characters name fragment")
public List<CharacterDto> getBookByName(@PathVariable String name) {
return characterService.searchCharacters(name);
}
}
4 changes: 4 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,4 @@
package mate.academy.rickandmorty.dto;

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

import jakarta.validation.constraints.NotBlank;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;

@Setter
@Getter
@AllArgsConstructor
public class CreateCharacterRequestDto {
@NotBlank
private String externalId;
@NotBlank
private String name;
@NotBlank
private String status;
@NotBlank
private String gender;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
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;

@Mapper(config = MapperConfig.class)
public interface CharacterMapper {
CharacterDto toDto(Character character);
}
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 jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import lombok.Getter;
import lombok.Setter;

@Entity
@Getter
@Setter
@Table(name = "characters")
public class Character {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String 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 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> {
List<Character> findByNameContaining(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.CharacterDto;

public interface CharacterService {
CharacterDto getRandomCharacter();

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

import java.util.List;
import java.util.Random;
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;

@Service
@RequiredArgsConstructor
public class CharacterServiceImpl implements CharacterService {

Choose a reason for hiding this comment

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

Didn't find service where you use
You must use public API (you should use REST API).

private final CharacterRepository characterRepository;
private final CharacterMapper characterMapper;
private static final Random random = new Random();
Copy link

Choose a reason for hiding this comment

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

Suggested change
private static final Random random = new Random();
private final Random random = new Random();


@Override
public CharacterDto getRandomCharacter() {
List<Character> characters = characterRepository.findAll();
return characterMapper
.toDto(characters.get(random.nextInt(characters.size())));
}

@Override
public List<CharacterDto> searchCharacters(String name) {
return characterRepository.findByNameContaining(name).stream()
.map(characterMapper::toDto)
.toList();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package mate.academy.rickandmorty.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import mate.academy.rickandmorty.model.Character;
import mate.academy.rickandmorty.repository.CharacterRepository;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
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;

@Component
@AllArgsConstructor
public class DataInitializer implements CommandLineRunner {
private static final String URL = "https://rickandmortyapi.com/api/character";
private final CharacterRepository characterRepository;
private final ObjectMapper objectMapper;

@Override
public void run(String... args) throws IOException, InterruptedException {
HttpClient httpClient = HttpClient.newHttpClient();
String nextPageUrl = URL;

while (nextPageUrl != null) {
HttpRequest httpRequest = HttpRequest.newBuilder()
.GET()
.uri(URI.create(nextPageUrl))
.build();
HttpResponse<String> response = httpClient
.send(httpRequest, HttpResponse.BodyHandlers.ofString());

JsonNode rootNode = objectMapper.readTree(response.body());
List<Character> characters = new ArrayList<>();
JsonNode results = rootNode.get("results");

for (JsonNode result : results) {
Character character = new Character();
character.setExternalId(result.get("id").asText());
character.setName(result.get("name").asText());
character.setGender(result.get("gender").asText());
character.setStatus(result.get("status").asText());

characters.add(character);
}
characterRepository.saveAll(characters);
nextPageUrl = rootNode.get("info").get("next").asText(null);
}
}
}
4 changes: 4 additions & 0 deletions src/main/resources/application.properties
Original file line number Diff line number Diff line change
@@ -1 +1,5 @@
spring.datasource.url=jdbc:mysql://localhost:3306/rick_and_morty
spring.datasource.username=root
spring.datasource.password=root12345
spring.jpa.hibernate.ddl-auto=update

2 changes: 0 additions & 2 deletions src/test/java/mate/academy/rickandmorty/ApplicationTests.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,7 @@

@SpringBootTest
class ApplicationTests {

@Test
void contextLoads() {
}

}
Loading