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

Fix slow issue as the client and ObjectMapper where created at each f… #53

Open
wants to merge 1 commit into
base: master
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
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ public void fetchAndStoreQuotes(int numberOfQuotes) throws IOException {
Quote quote = null;
try {
quote = client.fetchQuote();
} catch (URISyntaxException | InterruptedException e) {
} catch (InterruptedException e) {
e.printStackTrace();
}
if (quote != null) {
Expand Down
31 changes: 20 additions & 11 deletions LabJavaIO/src/main/java/ch/heigvd/res/labio/quotes/QuoteClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,31 +21,40 @@
* @author Daniel Palumbo
*/
public class QuoteClient {
ObjectMapper objectMapper = new ObjectMapper();

HttpRequest httpRequest;
HttpClient httpClient;

/*
* This has changed in the 2016 version of the lab. We were using the "itheardquotes" API, which is now down. We have
* replaced it with another API that generates random jokes.
*/
static String WEB_SERVICE_ENDPOINT = "http://api.icndb.com/jokes/random?firstName=Olivier&lastName=Liechti&escape=javascript";

public QuoteClient() {
try {
httpRequest = HttpRequest.newBuilder()
.GET()
.uri(new URI(WEB_SERVICE_ENDPOINT))
.header("Accept", "application/json")
.build();
} catch (Exception e) {
throw new Error();
}

httpClient = HttpClient.newBuilder().build();
}

/**
* Use this method to invoke the iheartquotes.com web service and receive
* an instance of a Quote.
*
* @return an instance of Quote, with values provided by the web service
*/
public Quote fetchQuote() throws URISyntaxException, IOException, InterruptedException {
// Use JAVA 11 http client and request feature
HttpRequest request = HttpRequest.newBuilder()
.GET()
.uri(new URI(WEB_SERVICE_ENDPOINT))
.header("Accept", "application/json")
.build();

HttpClient client = HttpClient.newBuilder().build();

public Quote fetchQuote() throws IOException, InterruptedException {
// Make the call to the API and map the response body to a Quote object
return new ObjectMapper().readValue(client.send(request, HttpResponse.BodyHandlers.ofString()).body(), Quote.class);
return objectMapper.readValue(httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString()).body(), Quote.class);
}

}