detailView methods findAll and findId with a test for findAll
This commit is contained in:
parent
79fa5d5f8b
commit
d0b35deb0f
2 changed files with 88 additions and 0 deletions
58
client/src/main/java/client/DetailView.java
Normal file
58
client/src/main/java/client/DetailView.java
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
package client;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import commons.Recipe;
|
||||
|
||||
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.List;
|
||||
|
||||
public class DetailView {
|
||||
private final String BASE_URL = "http://localhost:8080/api";
|
||||
private final HttpClient client;
|
||||
private final ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
public DetailView() {
|
||||
client = HttpClient.newHttpClient();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Gets all the recipes from the backend
|
||||
* @return a JSON string with all the recipes
|
||||
|
||||
*/
|
||||
public List<Recipe> findAll() throws IOException, InterruptedException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(URI.create(BASE_URL+ "/recipes"))
|
||||
.GET()
|
||||
.build();
|
||||
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
List<Recipe> recipes = objectMapper.readValue(response.body(), new TypeReference<List<Recipe>>() {
|
||||
}); // JSON string-> List<Recipe> (Jackson)
|
||||
return recipes;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Gets a single recipe based on its id
|
||||
* @param id every recipe has it's unique id
|
||||
* @return a singe recipe with the given id
|
||||
*/
|
||||
public Recipe findId(int id) throws IOException, InterruptedException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(URI.create(BASE_URL+"/" + id))
|
||||
.GET()
|
||||
.build();
|
||||
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
Recipe recipe = objectMapper.readValue(response.body(),Recipe.class);
|
||||
return recipe;
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue