Skip to content

Commit

Permalink
Refactored code and tests.
Browse files Browse the repository at this point in the history
  • Loading branch information
sagaofsilence committed Feb 22, 2024
1 parent 47b67c3 commit 6cd850b
Show file tree
Hide file tree
Showing 4 changed files with 87 additions and 36 deletions.
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
package io.refactoring.http5.client.example.util;

import io.refactoring.http5.client.example.RequestProcessingException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.hc.client5.http.classic.methods.HttpDelete;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.classic.methods.HttpPut;
Expand Down Expand Up @@ -43,8 +45,8 @@ public String getUser(final long userId) throws RequestProcessingException {
httpHost);

// Create a response handler
final BasicHttpClientResponseHandler responseHandler = new BasicHttpClientResponseHandler();
final String responseBody = httpClient.execute(httpHost, httpGetRequest, responseHandler);
final BasicHttpClientResponseHandler handler = new BasicHttpClientResponseHandler();
final String responseBody = httpClient.execute(httpHost, httpGetRequest, handler);

log.info("Got response: {}", responseBody);

Expand All @@ -56,32 +58,38 @@ public String getUser(final long userId) throws RequestProcessingException {
}

/**
* Gets all users.
* Gets paginated users.
*
* @param requestParameters request parameters
* @return response
* @throws RequestProcessingException if failed to execute request
*/
public String getAllUsers(final Map<String, String> requestParameters)
public String getPaginatedUsers(final Map<String, String> requestParameters)
throws RequestProcessingException {
try (final CloseableHttpClient httpClient = HttpClients.createDefault()) {
// Create request
final HttpHost httpHost = HttpHost.create("https://reqres.in");
final HttpGet httpGetRequest = new HttpGet(new URIBuilder("/api/users/").build());
final List<NameValuePair> nameValuePairs =
requestParameters.entrySet().stream()
.map(entry -> new BasicNameValuePair(entry.getKey(), entry.getValue()))
.map(entry -> (NameValuePair) entry)
.toList();
final HttpGet httpGetRequest =
new HttpGet(new URIBuilder("/api/users/").addParameters(nameValuePairs).build());
log.debug(
"Executing {} request: {} on host {}",
httpGetRequest.getMethod(),
httpGetRequest.getUri(),
httpHost);

// Create a response handler
final BasicHttpClientResponseHandler responseHandler = new BasicHttpClientResponseHandler();
final String responseBody = httpClient.execute(httpHost, httpGetRequest, responseHandler);
final BasicHttpClientResponseHandler handler = new BasicHttpClientResponseHandler();
final String responseBody = httpClient.execute(httpHost, httpGetRequest, handler);

log.info("Got response: {}", responseBody);
return responseBody;
} catch (Exception e) {
throw new RequestProcessingException("Failed to get all users.", e);
throw new RequestProcessingException("Failed to get paginated users.", e);
}
}

Expand Down Expand Up @@ -117,7 +125,8 @@ public String createUser(
try (final UrlEncodedFormEntity entity =
new UrlEncodedFormEntity(formParams, StandardCharsets.UTF_8)) {
final HttpHost httpHost = HttpHost.create("https://reqres.in");
final HttpPost httpPostRequest = new HttpPost(new URIBuilder("/api/users/").build());
final URI uri = new URIBuilder("/api/users/").build();
final HttpPost httpPostRequest = new HttpPost(uri);
httpPostRequest.setEntity(entity);
log.debug(
"Executing {} request: {} on host {}",
Expand All @@ -126,8 +135,8 @@ public String createUser(
httpHost);

// Create a response handler
final BasicHttpClientResponseHandler responseHandler = new BasicHttpClientResponseHandler();
final String responseBody = httpClient.execute(httpHost, httpPostRequest, responseHandler);
final BasicHttpClientResponseHandler handler = new BasicHttpClientResponseHandler();
final String responseBody = httpClient.execute(httpHost, httpPostRequest, handler);
log.info("Got response: {}", responseBody);

return responseBody;
Expand Down Expand Up @@ -172,7 +181,8 @@ public String updateUser(
try (final UrlEncodedFormEntity entity =
new UrlEncodedFormEntity(formParams, StandardCharsets.UTF_8)) {
final HttpHost httpHost = HttpHost.create("https://reqres.in");
final HttpPut httpPutRequest = new HttpPut(new URIBuilder("/api/users/" + userId).build());
final URI uri = new URIBuilder("/api/users/" + userId).build();
final HttpPut httpPutRequest = new HttpPut(uri);
httpPutRequest.setEntity(entity);
log.debug(
"Executing {} request: {} on host {}",
Expand All @@ -181,8 +191,8 @@ public String updateUser(
httpHost);

// Create a response handler
final BasicHttpClientResponseHandler responseHandler = new BasicHttpClientResponseHandler();
final String responseBody = httpClient.execute(httpHost, httpPutRequest, responseHandler);
final BasicHttpClientResponseHandler handler = new BasicHttpClientResponseHandler();
final String responseBody = httpClient.execute(httpHost, httpPutRequest, handler);
log.info("Got response: {}", responseBody);

return responseBody;
Expand All @@ -191,4 +201,31 @@ public String updateUser(
throw new RequestProcessingException("Failed to update user.", e);
}
}

/**
* Deletes given user.
*
* @param userId existing user id
* @throws RequestProcessingException if failed to execute request
*/
public void deleteUser(final long userId) throws RequestProcessingException {
try (final CloseableHttpClient httpClient = HttpClients.createDefault()) {
log.info("Delete user with ID: {}", userId);
final HttpHost httpHost = HttpHost.create("https://reqres.in");
final URI uri = new URIBuilder("/api/users/" + userId).build();
final HttpDelete httpDeleteRequest = new HttpDelete(uri);
log.debug(
"Executing {} request: {} on host {}",
httpDeleteRequest.getMethod(),
httpDeleteRequest.getUri(),
httpHost);

// Create a response handler
final BasicHttpClientResponseHandler handler = new BasicHttpClientResponseHandler();
final String responseBody = httpClient.execute(httpHost, httpDeleteRequest, handler);
log.info("Got response: {}", responseBody);
} catch (Exception e) {
throw new RequestProcessingException("Failed to update user.", e);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,8 @@ public User getUser(final long userId) throws RequestProcessingException {
httpHost);

// Create a response handler
final BasicHttpClientResponseHandler responseHandler = new BasicHttpClientResponseHandler();
final String responseBody = httpClient.execute(httpHost, httpGetRequest, responseHandler);
final BasicHttpClientResponseHandler handler = new BasicHttpClientResponseHandler();
final String responseBody = httpClient.execute(httpHost, httpGetRequest, handler);

log.info("Got response: {}", jsonUtils.makePretty(responseBody));

Expand All @@ -62,13 +62,13 @@ public User getUser(final long userId) throws RequestProcessingException {
}

/**
* Gets all users.
* Gets paginated users.
*
* @param requestParameters request parameters
* @return response
* @throws RequestProcessingException if failed to execute request
*/
public String getAllUsers(final Map<String, String> requestParameters)
public String getPaginatedUsers(final Map<String, String> requestParameters)
throws RequestProcessingException {
try (final CloseableHttpClient httpClient = HttpClients.createDefault()) {
// Create request
Expand All @@ -82,25 +82,25 @@ public String getAllUsers(final Map<String, String> requestParameters)
httpHost);

// Create a response handler
final BasicHttpClientResponseHandler responseHandler = new BasicHttpClientResponseHandler();
final String responseBody = httpClient.execute(httpHost, httpGetRequest, responseHandler);
final BasicHttpClientResponseHandler handler = new BasicHttpClientResponseHandler();
final String responseBody = httpClient.execute(httpHost, httpGetRequest, handler);

log.info("Got response: {}", jsonUtils.makePretty(responseBody));
return responseBody;
} catch (Exception e) {
throw new RequestProcessingException("Failed to get all users.", e);
throw new RequestProcessingException("Failed to get paginated users.", e);
}
}

/**
* Gets all users.
* Gets paginated users.
*
* @param requestParameters request parameters
* @return response
* @throws RequestProcessingException if failed to execute request
*/
public UserPage getAllUsersUsingTypedResponseHandler(final Map<String, String> requestParameters)
throws RequestProcessingException {
public UserPage getPaginatedUsersUsingTypedResponseHandler(
final Map<String, String> requestParameters) throws RequestProcessingException {
try (final CloseableHttpClient httpClient = HttpClients.createDefault()) {
// Create request
final HttpHost httpHost = userRequestProcessingUtils.getApiHost();
Expand All @@ -113,13 +113,13 @@ public UserPage getAllUsersUsingTypedResponseHandler(final Map<String, String> r
httpHost);

// Create a response handler
final DataObjectResponseHandler<UserPage> responseHandler =
final DataObjectResponseHandler<UserPage> handler =
new DataObjectResponseHandler<>(UserPage.class);
final UserPage responseBody = httpClient.execute(httpHost, httpGetRequest, responseHandler);
final UserPage responseBody = httpClient.execute(httpHost, httpGetRequest, handler);
log.info("Got response: {}", jsonUtils.toJson(responseBody));
return responseBody;
} catch (Exception e) {
throw new RequestProcessingException("Failed to get all users.", e);
throw new RequestProcessingException("Failed to get paginated users.", e);
}
}

Expand All @@ -145,8 +145,8 @@ public User createUser(@NonNull final User input) throws RequestProcessingExcept
httpHost);

// Create a response handler
final BasicHttpClientResponseHandler responseHandler = new BasicHttpClientResponseHandler();
final String responseBody = httpClient.execute(httpHost, httpPostRequest, responseHandler);
final BasicHttpClientResponseHandler handler = new BasicHttpClientResponseHandler();
final String responseBody = httpClient.execute(httpHost, httpPostRequest, handler);
log.info("Got response: {}", jsonUtils.makePretty(responseBody));

return jsonUtils.fromJson(responseBody, User.class);
Expand Down Expand Up @@ -177,8 +177,8 @@ public User updateUser(@NonNull final User input) throws RequestProcessingExcept
httpHost);

// Create a response handler
final BasicHttpClientResponseHandler responseHandler = new BasicHttpClientResponseHandler();
final String responseBody = httpClient.execute(httpHost, httpPutRequest, responseHandler);
final BasicHttpClientResponseHandler handler = new BasicHttpClientResponseHandler();
final String responseBody = httpClient.execute(httpHost, httpPutRequest, handler);
log.info("Got response: {}", jsonUtils.makePretty(responseBody));

return jsonUtils.fromJson(responseBody, User.class);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,15 @@ public class UserSimpleHttpRequestHelperTests extends BaseClassicExampleTests {
private final UserSimpleHttpRequestHelper userHttpRequestHelper =
new UserSimpleHttpRequestHelper();

/** Execute get all request. */
/** Execute get paginated request. */
@Test
void executeGetAllRequest() {
void executeGetPaginatedRequest() {
try {
// prepare
final Map<String, String> params = Map.of("page", "1");

// execute
final String responseBody = userHttpRequestHelper.getAllUsers(params);
final String responseBody = userHttpRequestHelper.getPaginatedUsers(params);

// verify
assertThat(responseBody).isNotEmpty();
Expand Down Expand Up @@ -90,4 +90,18 @@ void executePutRequest() {
Assertions.fail("Failed to execute HTTP request.", e);
}
}

/** Execute delete request. */
@Test
void executeDeleteRequest() {
try {
// prepare
final int userId = 2;

// execute
userHttpRequestHelper.deleteUser(userId);
} catch (Exception e) {
Assertions.fail("Failed to execute HTTP request.", e);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ void executeGetAllRequest() {
final Map<String, String> params = Map.of("page", "1");

// execute
final String responseBody = userHttpRequestHelper.getAllUsers(params);
final String responseBody = userHttpRequestHelper.getPaginatedUsers(params);

// verify
assertThat(responseBody).isNotEmpty();
Expand Down Expand Up @@ -67,7 +67,7 @@ void executeGetAllRequestUsingTypes() {

// execute
final UserPage responseBody =
userHttpRequestHelper.getAllUsersUsingTypedResponseHandler(params);
userHttpRequestHelper.getPaginatedUsersUsingTypedResponseHandler(params);

// verify
final ThrowingConsumer<UserPage> responseRequirements =
Expand Down

0 comments on commit 6cd850b

Please sign in to comment.