Skip to content

Commit

Permalink
☀️ add object to json util and avoid nullable responses from generic …
Browse files Browse the repository at this point in the history
…handler
  • Loading branch information
sergiomartins8 committed Oct 16, 2020
1 parent 28bf5bf commit 64141bd
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 15 deletions.
45 changes: 31 additions & 14 deletions src/test/java/io/company/utils/api/ClientApi.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,17 @@

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;
import org.apache.http.client.HttpResponseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

import static java.util.Objects.requireNonNull;

/**
Expand All @@ -37,19 +39,34 @@ public abstract class ClientApi {
* @param <T> class type
* @return concrete object
*/
@SneakyThrows
public static <T> T responseHandler(Request request, Class<T> clazz) {
try (Response response = OK_HTTP_CLIENT.newCall(request).execute()) {
if (!response.isSuccessful()) {
LOGGER.error("Failed request with response: {}", response);
return null;
}
JsonNode node = OBJECT_MAPPER.readTree(requireNonNull(response.body()).string());
return OBJECT_MAPPER.treeToValue(node, clazz);
} catch (IOException e) {
LOGGER.error(e.getMessage());
} finally {
OK_HTTP_CLIENT.connectionPool().evictAll();
Response response = OK_HTTP_CLIENT.newCall(request).execute();

if (!response.isSuccessful()) {
LOGGER.error("Failed for request: {}", request);
LOGGER.error("Failed with request body: {}", bodyToString(requireNonNull(request.body())));
LOGGER.error("Failed request with response body: {}", requireNonNull(response.body()).string());
throw new HttpResponseException(response.code(), "Response was unsuccessful");
}
return null;

JsonNode node = OBJECT_MAPPER.readTree(requireNonNull(response.body()).string());
response.close();
OK_HTTP_CLIENT.connectionPool().evictAll();

return OBJECT_MAPPER.treeToValue(node, clazz);
}

/**
* Converts a request body into a string.
*
* @param request request body to be converted
* @return request body as a string
*/
@SneakyThrows
private static String bodyToString(RequestBody request) {
final Buffer buffer = new Buffer();
request.writeTo(buffer);
return buffer.readUtf8();
}
}
28 changes: 28 additions & 0 deletions src/test/java/io/company/utils/logging/AsJson.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package io.company.utils.logging;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;

/**
* Allows whoever implements {@link AsJson} interface to be printed as a json string.
* <br>
* Pretty useful for logging model/POJO classes.
* <br>
* Example:
* <p>
* public class UserModel implements AsJson {}
* </p>
* <p>
* public void printObjectAsJson() {
* UserModel userModel = new UserModel();
* System.out.println(userModel.toJson());
* }
* </p>
*/
public interface AsJson {
@SneakyThrows
default String toJson() {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(this);
}
}
2 changes: 1 addition & 1 deletion src/test/java/io/company/utils/logging/Loggable.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import org.slf4j.LoggerFactory;

/**
* Allows whoever implements {@link Loggable} to use a default logger implementation.
* Allows whoever implements {@link Loggable} interface to use a default logger implementation.
*/
public interface Loggable {
default Logger logger() {
Expand Down

0 comments on commit 64141bd

Please sign in to comment.