From 3b5caf1109c2ec543b67b134417969eabe750a64 Mon Sep 17 00:00:00 2001 From: Norbert Bartels Date: Sun, 27 Dec 2020 21:00:18 +0100 Subject: [PATCH] Issue #1109 - refactoring webrequestor execute methods --- .../com/restfb/DefaultFacebookClient.java | 27 ++- .../java/com/restfb/DefaultWebRequestor.java | 75 ++++----- src/main/java/com/restfb/WebRequestor.java | 154 +++++++++++++----- src/main/java/com/restfb/util/ObjectUtil.java | 6 + .../com/restfb/ClasspathWebRequestor.java | 27 +-- src/test/java/com/restfb/ConnectionTest.java | 28 +--- .../com/restfb/DefaultWebRequestorTest.java | 24 +-- .../java/com/restfb/FakeWebRequestor.java | 39 ++--- .../java/com/restfb/JsonMapperToJavaTest.java | 7 +- .../integration/EtagWebRequestorITCase.java | 9 +- .../java/com/restfb/types/InsightTest.java | 23 ++- 11 files changed, 216 insertions(+), 203 deletions(-) diff --git a/src/main/java/com/restfb/DefaultFacebookClient.java b/src/main/java/com/restfb/DefaultFacebookClient.java index 9efdc8413..3644986ae 100644 --- a/src/main/java/com/restfb/DefaultFacebookClient.java +++ b/src/main/java/com/restfb/DefaultFacebookClient.java @@ -23,6 +23,7 @@ import static com.restfb.logging.RestFBLogger.CLIENT_LOGGER; import static com.restfb.util.EncodingUtils.decodeBase64; +import static com.restfb.util.ObjectUtil.requireNotEmpty; import static com.restfb.util.ObjectUtil.verifyParameterPresence; import static com.restfb.util.StringUtils.*; import static com.restfb.util.UrlUtils.urlEncode; @@ -271,10 +272,12 @@ public Connection fetchConnection(String connection, Class connectionT public Connection fetchConnectionPage(final String connectionPageUrl, Class connectionType) { String connectionJson; if (!isBlank(accessToken) && !isBlank(appSecret)) { - connectionJson = makeRequestAndProcessResponse(() -> webRequestor.executeGet(String.format("%s&%s=%s", - connectionPageUrl, urlEncode(APP_SECRET_PROOF_PARAM_NAME), obtainAppSecretProof(accessToken, appSecret)))); + WebRequestor.Request request = new WebRequestor.Request(String.format("%s&%s=%s", connectionPageUrl, + urlEncode(APP_SECRET_PROOF_PARAM_NAME), obtainAppSecretProof(accessToken, appSecret)), null); + connectionJson = makeRequestAndProcessResponse(() -> webRequestor.executeGet(request)); } else { - connectionJson = makeRequestAndProcessResponse(() -> webRequestor.executeGet(connectionPageUrl, getHeaderAccessToken())); + connectionJson = makeRequestAndProcessResponse( + () -> webRequestor.executeGet(new WebRequestor.Request(connectionPageUrl, getHeaderAccessToken()))); } return new Connection<>(this, connectionJson, connectionType); @@ -303,10 +306,7 @@ public FacebookClient createClientWithAccessToken(String accessToken) { public T fetchObjects(List ids, Class objectType, Parameter... parameters) { verifyParameterPresence("ids", ids); verifyParameterPresence("connectionType", objectType); - - if (ids.isEmpty()) { - throw new IllegalArgumentException("The list of IDs cannot be empty."); - } + requireNotEmpty(ids, "The list of IDs cannot be empty."); if (Stream.of(parameters).anyMatch(p -> IDS_PARAM_NAME.equals(p.name))) { throw new IllegalArgumentException("You cannot specify the '" + IDS_PARAM_NAME + "' URL parameter yourself - " @@ -405,10 +405,7 @@ public List executeBatch(List batchRequests) { @Override public List executeBatch(List batchRequests, List binaryAttachments) { verifyParameterPresence("binaryAttachments", binaryAttachments); - - if (batchRequests == null || batchRequests.isEmpty()) { - throw new IllegalArgumentException("You must specify at least one batch request."); - } + requireNotEmpty(batchRequests, "You must specify at least one batch request."); return jsonMapper.toJavaList( makeRequest("", true, false, binaryAttachments, Parameter.with("batch", jsonMapper.toJson(batchRequests, true))), @@ -740,15 +737,17 @@ protected String makeRequest(String endpoint, final boolean executeAsPost, final final String parameterString = toParameterString(parameters); return makeRequestAndProcessResponse(() -> { + WebRequestor.Request request = new WebRequestor.Request(fullEndpoint, getHeaderAccessToken(), parameterString); if (executeAsDelete && !isHttpDeleteFallback()) { - return webRequestor.executeDelete(fullEndpoint + "?" + parameterString, getHeaderAccessToken()); + return webRequestor.executeDelete(request); } if (executeAsPost) { - return webRequestor.executePost(fullEndpoint, parameterString, binaryAttachments, getHeaderAccessToken()); + request.setBinaryAttachments(binaryAttachments); + return webRequestor.executePost(request); } - return webRequestor.executeGet(fullEndpoint + "?" + parameterString, getHeaderAccessToken()); + return webRequestor.executeGet(request); }); } diff --git a/src/main/java/com/restfb/DefaultWebRequestor.java b/src/main/java/com/restfb/DefaultWebRequestor.java index 3563045cb..a6e858ab9 100644 --- a/src/main/java/com/restfb/DefaultWebRequestor.java +++ b/src/main/java/com/restfb/DefaultWebRequestor.java @@ -80,29 +80,19 @@ protected enum HttpMethod { } @Override - public Response executeGet(String url, String headerAccessToken) throws IOException { - return execute(url, HttpMethod.GET, headerAccessToken); + public Response executeGet(Request request) throws IOException { + return execute(HttpMethod.GET, request); } @Override - public Response executeGet(String url) throws IOException { - return execute(url, HttpMethod.GET, null); - } + public Response executePost(Request request) throws IOException { - @Override - public Response executePost(String url, String parameters, String headerAccessToken) throws IOException { - return executePost(url, parameters, null, headerAccessToken); - } - - @Override - public Response executePost(String url, String parameters, List binaryAttachments, String headerAccessToken) - throws IOException { - - binaryAttachments = Optional.ofNullable(binaryAttachments).orElse(new ArrayList<>()); + List binaryAttachments = request.getBinaryAttachments(); if (HTTP_LOGGER.isDebugEnabled()) { - HTTP_LOGGER.debug("Executing a POST to " + url + " with parameters " - + (!binaryAttachments.isEmpty() ? "" : "(sent in request body): ") + UrlUtils.urlDecode(parameters) + HTTP_LOGGER.debug("Executing a POST to " + request.getUrl() + " with parameters " + + (!binaryAttachments.isEmpty() ? "" : "(sent in request body): ") + + UrlUtils.urlDecode(request.getParameters()) + (!binaryAttachments.isEmpty() ? " and " + binaryAttachments.size() + " binary attachment[s]." : "")); } @@ -110,7 +100,8 @@ public Response executePost(String url, String parameters, List * This implementation is a no-op. * @@ -291,7 +282,8 @@ protected String createFormFieldName(BinaryAttachment binaryAttachment) { } String name = binaryAttachment.getFilename(); - return Optional.ofNullable(name).filter(f -> f.contains(".")).map(f -> f.substring(0, f.lastIndexOf('.'))).orElse(name); + return Optional.ofNullable(name).filter(f -> f.contains(".")).map(f -> f.substring(0, f.lastIndexOf('.'))) + .orElse(name); } /** @@ -326,8 +318,8 @@ public Map> getCurrentHeaders() { } @Override - public Response executeDelete(String url, String headerAccessToken) throws IOException { - return execute(url, HttpMethod.DELETE, headerAccessToken); + public Response executeDelete(Request request) throws IOException { + return execute(HttpMethod.DELETE, request); } @Override @@ -335,18 +327,19 @@ public DebugHeaderInfo getDebugHeaderInfo() { return debugHeaderInfo; } - private Response execute(String url, HttpMethod httpMethod, String headerAccessToken) throws IOException { - HTTP_LOGGER.debug("Making a {} request to {}", httpMethod.name(), url); + private Response execute(HttpMethod httpMethod, Request request) throws IOException { + HTTP_LOGGER.debug("Making a {} request to {} with parameters {}", httpMethod.name(), request.getUrl(), + request.getParameters()); HttpURLConnection httpUrlConnection = null; try { - httpUrlConnection = openConnection(new URL(url)); + httpUrlConnection = openConnection(new URL(request.getFullUrl())); httpUrlConnection.setReadTimeout(DEFAULT_READ_TIMEOUT_IN_MS); httpUrlConnection.setUseCaches(false); httpUrlConnection.setRequestMethod(httpMethod.name()); - initHeaderAccessToken(httpUrlConnection, headerAccessToken); + initHeaderAccessToken(httpUrlConnection, request); // Allow subclasses to customize the connection if they'd like to - set // their own headers, timeouts, etc. @@ -374,7 +367,8 @@ protected void fillHeaderAndDebugInfo(HttpURLConnection httpUrlConnection) { HTTP_LOGGER.debug("Facebook used the API {} to answer your request", usedApiVersion); Version usedVersion = Version.getVersionFromString(usedApiVersion); - DebugHeaderInfo.DebugHeaderInfoFactory factory = DebugHeaderInfo.DebugHeaderInfoFactory.create().setVersion(usedVersion); + DebugHeaderInfo.DebugHeaderInfoFactory factory = + DebugHeaderInfo.DebugHeaderInfoFactory.create().setVersion(usedVersion); Arrays.stream(FbHeaderField.values()).forEach(f -> f.getPutHeader().accept(httpUrlConnection, factory)); debugHeaderInfo = factory.build(); @@ -395,14 +389,13 @@ protected Response fetchResponse(HttpURLConnection httpUrlConnection) throws IOE } private enum FbHeaderField { - X_FB_TRACE_ID((c, f) -> f.setTraceId(getHeaderOrEmpty(c,"x-fb-trace-id"))), // - X_FB_REV((c, f) -> f.setRev(getHeaderOrEmpty(c,"x-fb-rev"))), - X_FB_DEBUG((c, f) -> f.setDebug(getHeaderOrEmpty(c,"x-fb-debug"))), - X_APP_USAGE((c, f) -> f.setAppUsage(getHeaderOrEmpty(c,"x-app-usage"))), - X_PAGE_USAGE((c, f) -> f.setPageUsage(getHeaderOrEmpty(c,"x-page-usage"))), - X_AD_ACCOUNT_USAGE((c, f) -> f.setAdAccountUsage(getHeaderOrEmpty(c,"x-ad-account-usage"))), - X_BUSINESS_USE_CASE_USAGE((c, f) -> f.setBusinessUseCaseUsage(getHeaderOrEmpty(c,"x-business-use-case-usage"))); - + X_FB_TRACE_ID((c, f) -> f.setTraceId(getHeaderOrEmpty(c, "x-fb-trace-id"))), // + X_FB_REV((c, f) -> f.setRev(getHeaderOrEmpty(c, "x-fb-rev"))), // + X_FB_DEBUG((c, f) -> f.setDebug(getHeaderOrEmpty(c, "x-fb-debug"))), // + X_APP_USAGE((c, f) -> f.setAppUsage(getHeaderOrEmpty(c, "x-app-usage"))), // + X_PAGE_USAGE((c, f) -> f.setPageUsage(getHeaderOrEmpty(c, "x-page-usage"))), // + X_AD_ACCOUNT_USAGE((c, f) -> f.setAdAccountUsage(getHeaderOrEmpty(c, "x-ad-account-usage"))), // + X_BUSINESS_USE_CASE_USAGE((c, f) -> f.setBusinessUseCaseUsage(getHeaderOrEmpty(c, "x-business-use-case-usage"))); private final BiConsumer putHeader; diff --git a/src/main/java/com/restfb/WebRequestor.java b/src/main/java/com/restfb/WebRequestor.java index 18d1b118d..bcfd59035 100644 --- a/src/main/java/com/restfb/WebRequestor.java +++ b/src/main/java/com/restfb/WebRequestor.java @@ -26,7 +26,11 @@ import static java.lang.String.format; import java.io.IOException; +import java.util.ArrayList; import java.util.List; +import java.util.Optional; + +import com.restfb.util.StringUtils; /** * Specifies how a class that sends {@code HTTP} requests to the Facebook API endpoint must operate. @@ -94,75 +98,137 @@ public String toString() { } /** - * Given a Facebook API endpoint URL, execute a {@code GET} against it. - * - * @param url - * The URL to make a {@code GET} request for, including URL parameters. - * @param headerAccessToken - * access token used in the header. May be {@code null}, if access token is already part of the query string - * @return HTTP response data. - * @throws IOException - * If an error occurs while performing the {@code GET} operation. - * @since 1.5 + * encapsulates the HTTP Request configuration */ - Response executeGet(String url, String headerAccessToken) throws IOException; + class Request { + + private final String url; + + private final Optional headerAccessToken; + + private String parameters; + + private List binaryAttachments; + + /** + * Simple http request with url and a header access token + * + * @param url + * the endpoint the request ist directed to + * @param headerAccessToken + * the HTTP header access token (may be {@code null}) + */ + public Request(String url, String headerAccessToken) { + this(url, headerAccessToken, null); + } + + /** + * Simple http request with url and a header access token + * + * @param url + * the endpoint the request ist directed to + * @param headerAccessToken + * the HTTP header access token (may be {@code null}) + * @param parameters + * the query parameter string + */ + public Request(String url, String headerAccessToken, String parameters) { + this(url, headerAccessToken, parameters, null); + } + + /** + * Simple http request with url and a header access token + * + * @param url + * the endpoint the request ist directed to + * @param headerAccessToken + * the HTTP header access token (may be {@code null}) + * @param parameters + * the query parameter string + * @param attachments + * list of binary attachments + */ + public Request(String url, String headerAccessToken, String parameters, List attachments) { + this.url = url; + this.headerAccessToken = Optional.ofNullable(headerAccessToken); + this.parameters = parameters; + setBinaryAttachments(attachments); + } + + public String getUrl() { + return url; + } + + public String getHeaderAccessToken() { + return headerAccessToken.orElse(null); + } + + public boolean hasHeaderAccessToken() { + return headerAccessToken.isPresent(); + } + + public String getParameters() { + return parameters; + } + + public List getBinaryAttachments() { + return Optional.ofNullable(binaryAttachments).orElse(new ArrayList<>()); + } + + public void setBinaryAttachments(List binaryAttachments) { + this.binaryAttachments = Optional.ofNullable(binaryAttachments).orElse(new ArrayList<>()); + } + + public String getFullUrl() { + if (!StringUtils.isBlank(parameters)) { + if (url != null && url.contains("?")) { + return url + "&" + parameters; + } + return url + "?" + parameters; + } + return url; + } + + @Override + public String toString() { + return format("Request to url %s with parameters %s. Header access token: %b", getUrl(), getParameters(), + hasHeaderAccessToken()); + } + } /** * Given a Facebook API endpoint URL, execute a {@code GET} against it. - * - * @param url - * The URL to make a {@code GET} request for, including URL parameters. + * + * @param request + * The request data for the {@code GET} request * @return HTTP response data. * @throws IOException * If an error occurs while performing the {@code GET} operation. * @since 1.5 */ - Response executeGet(String url) throws IOException; - - /** - * Given a Facebook API endpoint URL and parameter string, execute a {@code POST} to the endpoint URL. - * - * @param url - * The URL to {@code POST} to. - * @param parameters - * The parameters to be {@code POST}ed. - * @param headerAccessToken - * access token used in the header. May be {@code null}, if access token is already part of the query string - * @return HTTP response data. - * @throws IOException - * If an error occurs while performing the {@code POST}. - */ - Response executePost(String url, String parameters, String headerAccessToken) throws IOException; + Response executeGet(Request request) throws IOException; /** * Given a Facebook API endpoint URL and parameter string, execute a {@code POST} to the endpoint URL. * - * @param url - * The URL to {@code POST} to. - * @param parameters - * The parameters to be {@code POST}ed. - * @param binaryAttachments - * Optional binary attachments to be included in the {@code POST} body (e.g. photos and videos). - * @param headerAccessToken - * access token used in the header. May be {@code null}, if access token is already part of the query string + * @param request + * The request data used for the {@code POST} request. * @return HTTP response data. * @throws IOException * If an error occurs while performing the {@code POST}. */ - Response executePost(String url, String parameters, List binaryAttachments, String headerAccessToken) throws IOException; + Response executePost(Request request) throws IOException; /** * Given a Facebook API endpoint URL and parameter string, execute a {@code DELETE} to the endpoint URL. * - * @param url - * The URL to submit the {@code DELETE} to. - * @param headerAccessToken - * access token used in the header. May be {@code null}, if access token is already part of the query string + * @param request + * The request data used for the {@code DELETE} request. * @return HTTP response data. * @throws IOException * If an error occurs while performing the {@code DELETE}. */ - Response executeDelete(String url, String headerAccessToken) throws IOException; + Response executeDelete(Request request) throws IOException; /** * Provides access to the facebook header information. diff --git a/src/main/java/com/restfb/util/ObjectUtil.java b/src/main/java/com/restfb/util/ObjectUtil.java index c12f0f144..a1dfdb99c 100644 --- a/src/main/java/com/restfb/util/ObjectUtil.java +++ b/src/main/java/com/restfb/util/ObjectUtil.java @@ -51,6 +51,12 @@ public static String requireNotEmpty(String obj, String errorText) { return obj; } + public static void requireNotEmpty(Collection collection, String errorText) { + if (collection == null || collection.isEmpty()) { + throw new IllegalArgumentException(errorText); + } + } + /** * Ensures that {@code obj} isn't {@code null}. * diff --git a/src/test/java/com/restfb/ClasspathWebRequestor.java b/src/test/java/com/restfb/ClasspathWebRequestor.java index 5786471b9..0d727e040 100644 --- a/src/test/java/com/restfb/ClasspathWebRequestor.java +++ b/src/test/java/com/restfb/ClasspathWebRequestor.java @@ -25,7 +25,6 @@ import static java.net.HttpURLConnection.HTTP_OK; import java.io.IOException; -import java.util.List; /** * {@link WebRequestor} implementation that loads a file from the classpath instead of hitting the web. Useful for @@ -54,39 +53,23 @@ public ClasspathWebRequestor(String pathToJson) throws IOException { } /** - * @see com.restfb.WebRequestor#executePost(java.lang.String, java.lang.String, java.lang.String) + * @see com.restfb.WebRequestor#executeGet(com.restfb.WebRequestor.Request) */ @Override - public Response executePost(String url, String parameters, String headerAccessToken) { + public Response executeGet(Request request) { return response; } /** - * @see com.restfb.WebRequestor#executeGet(java.lang.String) + * @see com.restfb.WebRequestor#executePost(com.restfb.WebRequestor.Request) */ @Override - public Response executeGet(String url) { - return response; - } - - /** - * @see com.restfb.WebRequestor#executeGet(java.lang.String) - */ - @Override - public Response executeGet(String url, String headerAccessToken) { - return response; - } - - /** - * @see com.restfb.WebRequestor#executePost(String, String, List, String) - */ - @Override - public Response executePost(String url, String parameters, List binaryAttachments, String headerAccessToken) throws IOException { + public Response executePost(Request request) { return response; } @Override - public Response executeDelete(String url, String headerAccessToken) { + public Response executeDelete(Request request) { return response; } diff --git a/src/test/java/com/restfb/ConnectionTest.java b/src/test/java/com/restfb/ConnectionTest.java index 337b4626f..4da1af5d4 100644 --- a/src/test/java/com/restfb/ConnectionTest.java +++ b/src/test/java/com/restfb/ConnectionTest.java @@ -182,17 +182,12 @@ void checkIteration_withSameCursor() { void checkIteration_withSameCursorAndClient() { FakeWebRequestor fakeWebRequestor = new FakeWebRequestor() { @Override - public Response executeGet(String url, String headerAccessToken) { - if (url.equals("https://graph.facebook.com/v3.2/me/adaccounts?access_token=token&format=json")) { + public Response executeGet(Request request) { + if (request.getFullUrl().equals("https://graph.facebook.com/v3.2/me/adaccounts?access_token=token&format=json")) { return new Response(HTTP_OK, jsonFromClasspath("connection-same-cursor")); } - return new Response(HTTP_OK, url); - } - - @Override - public Response executeGet(String url) throws IOException { - return executeGet(url, null); + return new Response(HTTP_OK, request.getUrl()); } }; DefaultFacebookClient facebookClient = @@ -221,7 +216,9 @@ private Connection createCursorConnection(boolean cursorOnly) { private Connection create3PageConnection() { FakeWebRequestor fakeWebRequestor = new FakeWebRequestor() { @Override - public Response executeGet(String url, String headerAccessToken) { + public Response executeGet(Request request) { + + String url = request.getFullUrl(); if (url.equals("https://graph.facebook.com/v3.1/page1?access_token=token&format=json")) { return new Response(HTTP_OK, jsonFromClasspath("connection-p1")); @@ -237,11 +234,6 @@ public Response executeGet(String url, String headerAccessToken) { return new Response(HTTP_OK, url); } - - @Override - public Response executeGet(String url) throws IOException { - return executeGet(url, null); - } }; DefaultFacebookClient facebookClient = new DefaultFacebookClient("token", fakeWebRequestor, new DefaultJsonMapper(), Version.VERSION_3_1); @@ -251,7 +243,9 @@ public Response executeGet(String url) throws IOException { private Connection create3PageConnectionWithCursorOnly() { FakeWebRequestor fakeWebRequestor = new FakeWebRequestor() { @Override - public Response executeGet(String url, String headerAccessToken) { + public Response executeGet(Request request) { + + String url = request.getFullUrl(); if (url.equals("https://graph.facebook.com/v2.12/page1?access_token=token&format=json")) { return new Response(HTTP_OK, jsonFromClasspath("connection-p1-cursor-only")); @@ -269,10 +263,6 @@ public Response executeGet(String url, String headerAccessToken) { } - @Override - public Response executeGet(String url) throws IOException { - return executeGet(url, null); - } }; DefaultFacebookClient facebookClient = new DefaultFacebookClient("token", fakeWebRequestor, new DefaultJsonMapper(), Version.VERSION_3_1); diff --git a/src/test/java/com/restfb/DefaultWebRequestorTest.java b/src/test/java/com/restfb/DefaultWebRequestorTest.java index a5f616836..0f7a56825 100644 --- a/src/test/java/com/restfb/DefaultWebRequestorTest.java +++ b/src/test/java/com/restfb/DefaultWebRequestorTest.java @@ -65,7 +65,7 @@ void checkGet_withAccessToken() throws IOException { when(mockUrlConnection.getResponseCode()).thenReturn(200); InputStream stream = new ByteArrayInputStream(resultString.getBytes(StandardCharsets.UTF_8)); when(mockUrlConnection.getInputStream()).thenReturn(stream); - WebRequestor.Response response = requestor.executeGet("http://www.example.org", "accesstoken"); + WebRequestor.Response response = requestor.executeGet(new WebRequestor.Request("http://www.example.org", "accesstoken")); verify(mockUrlConnection).setRequestProperty("Authorization", "Bearer accesstoken"); } @@ -76,7 +76,7 @@ void checkGet() throws IOException { when(mockUrlConnection.getResponseCode()).thenReturn(200); InputStream stream = new ByteArrayInputStream(resultString.getBytes(StandardCharsets.UTF_8)); when(mockUrlConnection.getInputStream()).thenReturn(stream); - WebRequestor.Response response = requestor.executeGet("http://www.example.org"); + WebRequestor.Response response = requestor.executeGet(new WebRequestor.Request("http://www.example.org", null)); // check the result assertThat(response.getStatusCode()).isEqualTo(200); @@ -88,8 +88,8 @@ void checkGet() throws IOException { verify(mockUrlConnection).setRequestMethod(DefaultWebRequestor.HttpMethod.GET.name()); verify(mockUrlConnection, never()).setRequestProperty(eq("Authorization"), anyString()); verify(mockUrlConnection).connect(); - verify(requestor).executeGet(anyString()); - verify(requestor, never()).executePost(anyString(), anyString(), isNull()); + verify(requestor).executeGet(any(WebRequestor.Request.class)); + verify(requestor, never()).executePost(any(WebRequestor.Request.class)); verify(requestor).customizeConnection(mockUrlConnection); verify(requestor).fillHeaderAndDebugInfo(mockUrlConnection); verify(requestor).fetchResponse(mockUrlConnection); @@ -102,7 +102,7 @@ void checkPost_withAccessToken() throws IOException { when(mockUrlConnection.getResponseCode()).thenReturn(200); InputStream stream = new ByteArrayInputStream(resultString.getBytes(StandardCharsets.UTF_8)); when(mockUrlConnection.getInputStream()).thenReturn(stream); - WebRequestor.Response response = requestor.executePost(exampleUrl, "", "accesstoken"); + WebRequestor.Response response = requestor.executePost(new WebRequestor.Request(exampleUrl, "accesstoken", "")); verify(mockUrlConnection).setRequestProperty("Authorization", "Bearer accesstoken"); } @@ -114,7 +114,8 @@ void checkPost_NoBinary() throws IOException { when(mockUrlConnection.getResponseCode()).thenReturn(200); InputStream stream = new ByteArrayInputStream(resultString.getBytes(StandardCharsets.UTF_8)); when(mockUrlConnection.getInputStream()).thenReturn(stream); - WebRequestor.Response response = requestor.executePost(exampleUrl, "", null); + WebRequestor.Request request = new WebRequestor.Request(exampleUrl, null, ""); + WebRequestor.Response response = requestor.executePost(request); // check the result assertThat(response.getStatusCode()).isEqualTo(200); @@ -127,8 +128,8 @@ void checkPost_NoBinary() throws IOException { verify(mockUrlConnection).setRequestMethod(DefaultWebRequestor.HttpMethod.POST.name()); verify(mockUrlConnection, never()).setRequestProperty(eq("Authorization"), anyString()); verify(mockUrlConnection).connect(); - verify(requestor).executePost(same(exampleUrl), anyString(), isNull()); - verify(requestor, never()).executeGet(anyString()); + verify(requestor).executePost(eq(request)); + verify(requestor, never()).executeGet(any(WebRequestor.Request.class)); verify(requestor).customizeConnection(mockUrlConnection); verify(requestor).fillHeaderAndDebugInfo(mockUrlConnection); verify(requestor).fetchResponse(mockUrlConnection); @@ -146,7 +147,8 @@ void checkPost_WithBinary() throws IOException { when(mockUrlConnection.getResponseCode()).thenReturn(200); InputStream stream = new ByteArrayInputStream(resultString.getBytes(StandardCharsets.UTF_8)); when(mockUrlConnection.getInputStream()).thenReturn(stream); - WebRequestor.Response response = requestor.executePost(exampleUrl, "", Collections.singletonList(mockAttachment), null); + WebRequestor.Request request = new WebRequestor.Request(exampleUrl, null, "", Collections.singletonList(mockAttachment)); + WebRequestor.Response response = requestor.executePost(request); // check the result assertThat(response.getStatusCode()).isEqualTo(200); @@ -160,8 +162,8 @@ void checkPost_WithBinary() throws IOException { verify(mockUrlConnection, never()).setRequestProperty(eq("Authorization"), anyString()); verify(mockUrlConnection).setRequestMethod(DefaultWebRequestor.HttpMethod.POST.name()); verify(mockUrlConnection).connect(); - verify(requestor).executePost(same(exampleUrl), anyString(), anyList(), isNull()); - verify(requestor, never()).executeGet(anyString()); + verify(requestor).executePost(eq(request)); + verify(requestor, never()).executeGet(any(WebRequestor.Request.class)); verify(requestor).customizeConnection(mockUrlConnection); verify(requestor).fillHeaderAndDebugInfo(mockUrlConnection); verify(requestor).fetchResponse(mockUrlConnection); diff --git a/src/test/java/com/restfb/FakeWebRequestor.java b/src/test/java/com/restfb/FakeWebRequestor.java index 23d65f78f..e80fdc765 100644 --- a/src/test/java/com/restfb/FakeWebRequestor.java +++ b/src/test/java/com/restfb/FakeWebRequestor.java @@ -23,9 +23,6 @@ import static java.net.HttpURLConnection.HTTP_OK; -import java.io.IOException; -import java.util.List; - import com.restfb.DefaultWebRequestor.HttpMethod; /** @@ -52,43 +49,27 @@ public FakeWebRequestor() { } @Override - public Response executeGet(String url) throws IOException { - this.savedUrl = url; - this.method = HttpMethod.GET; - return createInternalResponse(); - } - - @Override - public Response executeGet(String url, String headerAccessToken) throws IOException { - this.savedUrl = url; + public Response executeGet(Request request) { + this.savedUrl = request.getFullUrl(); this.method = HttpMethod.GET; - this.accessToken = headerAccessToken; - return createInternalResponse(); - } - - @Override - public Response executePost(String url, String parameters, String headerAccessToken) { - this.savedUrl = url; - this.method = HttpMethod.POST; - this.parameters = parameters; - this.accessToken = headerAccessToken; + this.accessToken = request.getHeaderAccessToken(); return createInternalResponse(); } @Override - public Response executePost(String url, String parameters, List binaryAttachments, String headerAccessToken) { - this.savedUrl = url; + public Response executePost(Request request) { + this.savedUrl = request.getUrl(); this.method = HttpMethod.POST; - this.parameters = parameters; - this.accessToken = headerAccessToken; + this.parameters = request.getParameters(); + this.accessToken = request.getHeaderAccessToken(); return createInternalResponse(); } @Override - public Response executeDelete(String url, String headerAccessToken) { - this.savedUrl = url; + public Response executeDelete(Request request) { + this.savedUrl = request.getFullUrl(); this.method = HttpMethod.DELETE; - this.accessToken = headerAccessToken; + this.accessToken = request.getHeaderAccessToken(); return createInternalResponse(); } diff --git a/src/test/java/com/restfb/JsonMapperToJavaTest.java b/src/test/java/com/restfb/JsonMapperToJavaTest.java index 045342ca8..399f34baf 100644 --- a/src/test/java/com/restfb/JsonMapperToJavaTest.java +++ b/src/test/java/com/restfb/JsonMapperToJavaTest.java @@ -223,14 +223,9 @@ void unicodeGet() { User user2 = new DefaultFacebookClient("blub", new DefaultWebRequestor() { @Override - public Response executeGet(final String url, String headerAccessToken) { + public Response executeGet(Request request) { return new Response(HttpURLConnection.HTTP_OK, "{\"id\":\"b4TUmsLXoK\",\"name\":\"ⲉ鯨ɯ摓㻦恛҉祐\\f፲\"}"); } - - @Override - public Response executeGet(String url) throws IOException { - return executeGet(url, null); - } }, new DefaultJsonMapper(), Version.LATEST).fetchObject("me", User.class); assertThat(user2).isNotNull(); } diff --git a/src/test/java/com/restfb/integration/EtagWebRequestorITCase.java b/src/test/java/com/restfb/integration/EtagWebRequestorITCase.java index 620d31753..4772bf80c 100644 --- a/src/test/java/com/restfb/integration/EtagWebRequestorITCase.java +++ b/src/test/java/com/restfb/integration/EtagWebRequestorITCase.java @@ -27,6 +27,7 @@ import java.io.IOException; import java.net.HttpURLConnection; +import com.restfb.WebRequestor; import org.junit.jupiter.api.Test; import com.restfb.ETagWebRequestor; @@ -40,10 +41,10 @@ void fetchMeWithCache() throws IOException { String requestUrl = "https://graph.facebook.com/v2.5/me?format=json&access_token="; requestUrl += getTestSettings().getUserAccessToken(); ETagWebRequestor webRequest = new ETagWebRequestor(); - Response resp1 = webRequest.executeGet(requestUrl); + Response resp1 = webRequest.executeGet(new WebRequestor.Request(requestUrl, null)); assertNotNull(resp1); assertEquals(HttpURLConnection.HTTP_OK, (int) resp1.getStatusCode()); - Response resp2 = webRequest.executeGet(requestUrl); + Response resp2 = webRequest.executeGet(new WebRequestor.Request(requestUrl, null)); assertNotNull(resp2); assertEquals(HttpURLConnection.HTTP_NOT_MODIFIED, (int) resp2.getStatusCode()); assertEquals(resp1.getBody(), resp2.getBody()); @@ -55,10 +56,10 @@ void fetchMeWithoutCache() throws IOException { requestUrl += getTestSettings().getUserAccessToken(); ETagWebRequestor webRequest = new ETagWebRequestor(); webRequest.setUseCache(false); - Response resp1 = webRequest.executeGet(requestUrl); + Response resp1 = webRequest.executeGet(new WebRequestor.Request(requestUrl, null)); assertNotNull(resp1); assertEquals(HttpURLConnection.HTTP_OK, (int) resp1.getStatusCode()); - Response resp2 = webRequest.executeGet(requestUrl); + Response resp2 = webRequest.executeGet(new WebRequestor.Request(requestUrl, null)); assertNotNull(resp2); assertEquals(HttpURLConnection.HTTP_OK, (int) resp2.getStatusCode()); assertEquals(resp1.getBody(), resp2.getBody()); diff --git a/src/test/java/com/restfb/types/InsightTest.java b/src/test/java/com/restfb/types/InsightTest.java index d8d0bdba5..fd35a7e61 100644 --- a/src/test/java/com/restfb/types/InsightTest.java +++ b/src/test/java/com/restfb/types/InsightTest.java @@ -31,13 +31,11 @@ import java.util.Map; import java.util.TreeMap; -import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import com.restfb.*; import com.restfb.json.JsonObject; - class InsightTest extends AbstractJsonMapperTests { @Test @@ -63,12 +61,12 @@ void checkV3_3_insight_1() { @Test void checkV3_3_connection() { TreeMap vals = new TreeMap<>(); - Connection conn = create3PageInsightConnection(); + Connection conn = create3PageInsightConnection(); for (List insightList : conn) { for (Insight insight : insightList) { assertNotNull(insight); JsonObject object = insight.getValues().get(0).get("value").asObject(); - for (String name: object.names()) { + for (String name : object.names()) { vals.put(name, object.get(name).asInt()); } } @@ -94,30 +92,29 @@ void checkIssue1082() { private Connection create3PageInsightConnection() { FakeWebRequestor fakeWebRequestor = new FakeWebRequestor() { @Override - public Response executeGet(String url, String headerAccessToken) throws IOException { + public Response executeGet(Request request) { + + String url = request.getFullUrl(); if (url.equals("https://graph.facebook.com/v3.3/page1?access_token=token&format=json")) { return new Response(HTTP_OK, jsonFromClasspath("v3_3/insight/page-1")); } - if (url.equals("https://graph.facebook.com/v3.3//insights?access_token=&pretty=0&metric=page_fans_city&since=1560236400&until=1560409200")) { + if (url.equals( + "https://graph.facebook.com/v3.3//insights?access_token=&pretty=0&metric=page_fans_city&since=1560236400&until=1560409200")) { return new Response(HTTP_OK, jsonFromClasspath("v3_3/insight/page-2")); } - if (url.equals("https://graph.facebook.com/v3.3//insights?access_token=&pretty=0&since=1560409200&until=1560582000&metric=page_fans_city")) { + if (url.equals( + "https://graph.facebook.com/v3.3//insights?access_token=&pretty=0&since=1560409200&until=1560582000&metric=page_fans_city")) { return new Response(HTTP_OK, jsonFromClasspath("v3_3/insight/page-3")); } return new Response(HTTP_OK, url); } - - @Override - public Response executeGet(String url) throws IOException { - return executeGet(url, null); - } }; DefaultFacebookClient facebookClient = - new DefaultFacebookClient("token", fakeWebRequestor, new DefaultJsonMapper(), Version.VERSION_3_3); + new DefaultFacebookClient("token", fakeWebRequestor, new DefaultJsonMapper(), Version.VERSION_3_3); return facebookClient.fetchConnection("/page1", Insight.class); } }