diff --git a/AGENTS.md b/AGENTS.md index bb3bceb..5d7bfa9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -14,8 +14,8 @@ Guidance for AI coding agents working in this repository. - `ZBValidateOptions`, `ZBBulkFileJobOptions`, `ZBValidateBatchOptions`, `ZBValidateRequestOptions`: the option objects, each with a package-private `fill` that both builds the request and rejects an invalid combination before anything is sent. - `zero-bounce-sdk/src/main/java/com/zerobounce/ZeroBounceWarmup.java`: a separate client for the Warmup API, a different product with its own host and its own team-scoped key. Not part of `ZeroBounceSDK`. - `zero-bounce-sdk/src/main/java/com/zerobounce/HttpMessages.java`: turns HTTP failures, HTML pages, and empty or non-JSON bodies into a short `ErrorResponse`. -- `zero-bounce-sdk/src/main/java/com/zerobounce/SdkHttp.java`: per-client HTTP seam. Production leaves `transport` null. -- `zero-bounce-sdk/src/test/java/com/zerobounce/OfflineApiTest.java`, `OfflineWarmupTest.java`: the offline suites. `FakeApi` (and a mocked `HttpURLConnection`) answer every call and record the url, method, headers and body, so the assertions are on what actually went on the wire. +- `zero-bounce-sdk/src/main/java/com/zerobounce/SdkHttp.java`: shared Apache HttpClient 5 exchange and timeout configuration, plus the per-client fake transport seam. Production leaves `transport` null. Response handlers consume and close responses. One shared client per timeout value (at most eight, admitted under a lock) pools connections for every instance and is never closed by SDK users; each runs HttpClient's idle-connection evictor, one daemon thread, and honours the JVM proxy and TLS system properties. Redirects and automatic retries are disabled. A test that mocks `HttpClients` must open the mock with `HttpClientTestSupport.mockClients()`, which drops the shared clients on both sides of the mock. +- `zero-bounce-sdk/src/test/java/com/zerobounce/OfflineApiTest.java`, `OfflineWarmupTest.java`: the offline suites. `FakeApi` and replacement `exchangeHttp` methods record the URL, method, headers and body. `LoopbackServer` routes real HttpClient 5 builders to a local server for transport and multipart tests. - `live/LiveApi.java`: the opt-in live suite. It sits outside the Maven module's source root, so `mvn test` and CI never compile or run it. - `zero-bounce-sdk/pom.xml`: SDK build. The version is `` inside ``. - `pom.xml`: the JavaFX sample. Its `` is `1.0-SNAPSHOT` and is not the SDK version. @@ -81,7 +81,7 @@ Keys come from the environment only. Never write one into a file, a commit, a lo - **Errors carry the HTTP status.** `ErrorResponse.getStatusCode()` is set on every path, so callers can tell a Cloudflare 403 from an API 400/404 and a Warmup 429. A failure that never reached the API leaves it 0. - **`ErrorResponse.parseError` already handles `detail`.** It collects every value of the error JSON, so the Inbox Placement Tester's Django-style `{"detail": ...}` surfaces without a special case. A test pins that. - **Offline tests only, in the Maven module.** Never call the live API from a test under `src/test`. The live suite is the separate, opt-in `live/LiveApi.java`. Tests replace `transport`: it is package-visible, so assign a `FakeApi` (or another `SdkHttp.Transport`) on that instance. -- There is no runtime version constant and no User-Agent. Do not add one that can drift from ``. +- There is no runtime version constant, and the SDK sets no User-Agent of its own: requests carry HttpClient's default (`Apache-HttpClient/…`). Do not disable it, and do not add one that can drift from ``. - Match the surrounding style. Do not reformat unrelated code. ## Changelog diff --git a/CHANGELOG.md b/CHANGELOG.md index 05a41ab..b8fb5c3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,10 +7,24 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Changed + +- All HTTP requests in `ZeroBounceSDK` and `ZeroBounceWarmup`, including multipart uploads and file downloads, now use Apache HttpClient 5.6.5 and HttpCore 5.4.4. Redirects and automatic retries are disabled; timeouts, response bytes and callback behavior are preserved. +- Requests reuse connections: one shared client per timeout value serves every `ZeroBounceSDK` and `ZeroBounceWarmup` instance, so repeated calls skip a new TCP and TLS handshake. Up to eight timeout values get a shared client; a call with any other timeout gets a client of its own, closed after the call. Nothing needs closing. Each shared client runs one daemon thread, HttpClient's idle-connection evictor, which closes connections that have been idle for 5 seconds or are past the server's `Keep-Alive` timeout. A pooled connection idle for more than a second is checked before it is reused. +- Every request honours the JVM's proxy and TLS settings (`https.proxyHost`, the default `ProxySelector`, `javax.net.ssl.*`), as the calls sent through `HttpURLConnection` did. +- Requests send HttpClient's own `User-Agent` (`Apache-HttpClient/5.6.5 (Java/…)`). The calls sent through `HttpURLConnection` sent `Java/…`. +- **Behaviour change:** `validateBatch` and the other calls that POST a JSON body label it `Content-Type: application/json; charset=UTF-8`. Up to 3.0.1 `HttpURLConnection` labelled it `application/x-www-form-urlencoded`, its default. +- The text fields of multipart uploads (`sendFile`, `scoringSendFile`, the bulk email finder, domain search and list evaluator uploads) are sent as UTF-8 `text/plain` without a `Content-Transfer-Encoding` header. Up to 3.0.1 they were ISO-8859-1. +- HttpClient 5 logs through SLF4J (`slf4j-api` 1.7.36). An application with no SLF4J binding sees SLF4J's one-time "no binding" notice on stderr at its first request. At DEBUG, HttpClient's loggers write the API key, the Warmup key and the SMTP password: the request line carries `api_key`, `org.apache.hc.client5.http.headers` writes `Authorization` and `API-Key`, and `org.apache.hc.client5.http.wire` writes request bodies. Keep `org.apache.hc` at INFO or above in production; logback with no configuration file logs at DEBUG. Up to 3.0.1 the multipart uploads, `getFile` and `scoringGetFile` logged the same through HttpClient 4 and commons-logging, and `HttpURLConnection` logged the request line and headers to `java.util.logging` at FINE. + ### Deprecated - `ZeroBounceWarmup.EmailContent.setIndustry` (not an API field; not sent), `EmailContent.setWebsite` (use `setCompanyWebsite`), `ManagedSending.setDailyLimit` (the API does not apply a daily limit; not sent) and `ManagedSending.setTimezoneOffset(Integer)` (use `setTimezoneOffset(double)`; an int literal already calls it). They still compile and work as described under Fixed. +### Removed + +- The SDK no longer depends on Apache HttpClient 4 (`org.apache.httpcomponents:httpclient`), HttpCore 4, HttpMime or Commons Codec, so they are no longer on an application's classpath through it. An application that uses `org.apache.http` classes itself must declare those dependencies. + ### Fixed - **Behaviour change:** a 2xx whose body is blank (only spaces, tabs or line breaks) is not an empty success: on every `ZeroBounceWarmup` JSON call and on `deleteInboxPlacementTest` it reaches the error callback with status 200, "Empty response from ZeroBounce (HTTP 200)". Only a 204, or a 200 with nothing in it, is the documented empty success (null). Up to 3.0.1 `ZeroBounceWarmup` took a blank body for that empty success. diff --git a/README.md b/README.md index e3e8faa..23ded23 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,7 @@ - Keep API keys on a trusted server. Do not embed them in mobile apps or browser JavaScript that untrusted users can inspect. - Custom API base URLs (when supported) must use `https://`. Do not pass end-user-controlled hosts into those settings. - Request URLs include `api_key` as a query parameter (ZeroBounce API contract). Do not log full request URLs or enable payload debug logging in production. +- Requests are sent by Apache HttpClient 5, which logs through SLF4J. At DEBUG it logs the request line (with `api_key`), every request header (including `Authorization` and `API-Key`) and the raw request bytes (form fields such as the SMTP password, and uploaded files). Keep `org.apache.hc` at INFO or above in production; see [Controlling SDK logging](#controlling-sdk-logging) for a configuration. Logback with no configuration file logs everything at DEBUG. [![Maven Central](https://img.shields.io/maven-central/v/com.zerobounce.java/zerobouncesdk?label=Latest%20release)](https://mvnrepository.com/artifact/com.zerobounce.java/zerobouncesdk) @@ -101,9 +102,36 @@ ZeroBounceSDK.getInstance().initialize("", ""); ### Controlling SDK logging -The SDK is silent by default so it never emits Personally Identifiable Information (PII) unless you -explicitly opt in. To integrate the SDK with your application's logging framework, register a -`ZBLogger` implementation before issuing any API calls. The helper class `ZBLoggers` adapts +Two loggers can write during a request: + +- **The SDK's own logger** stays off until you register a `ZBLogger`. What it writes has the API key + redacted. +- **Apache HttpClient**, which sends the requests, logs through your SLF4J backend. At DEBUG it writes + the API key, the Warmup key, the SMTP password and uploaded files. + +Keep `org.apache.hc` at INFO or above in production. Logback with no configuration file logs +everything at DEBUG, so if you use Logback without a `logback.xml`, start from this one: + +```xml + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + +``` + +To send the SDK's own logging to your application's logging framework, register a `ZBLogger` +implementation before issuing any API calls. The helper class `ZBLoggers` adapts `java.util.logging` (JUL) out of the box: ```java diff --git a/zero-bounce-sdk/pom.xml b/zero-bounce-sdk/pom.xml index 821fc36..3ffca4b 100644 --- a/zero-bounce-sdk/pom.xml +++ b/zero-bounce-sdk/pom.xml @@ -43,6 +43,8 @@ UTF-8 UTF-8 5.23.0 + + 5.4.4 @@ -54,39 +56,27 @@ provided - - - commons-codec - commons-codec - 1.22.1 - - com.google.code.gson gson 2.14.0 - + - org.apache.httpcomponents - httpclient - 4.5.14 + org.apache.httpcomponents.client5 + httpclient5 + 5.6.5 - - org.apache.httpcomponents - httpcore - 4.4.16 + org.apache.httpcomponents.core5 + httpcore5 + ${httpcore5.version} - - - org.apache.httpcomponents - httpmime - 4.5.14 + org.apache.httpcomponents.core5 + httpcore5-h2 + ${httpcore5.version} diff --git a/zero-bounce-sdk/src/main/java/com/zerobounce/Priority3Api.java b/zero-bounce-sdk/src/main/java/com/zerobounce/Priority3Api.java index d0f6b62..e20b2e7 100644 --- a/zero-bounce-sdk/src/main/java/com/zerobounce/Priority3Api.java +++ b/zero-bounce-sdk/src/main/java/com/zerobounce/Priority3Api.java @@ -1,16 +1,13 @@ package com.zerobounce; import com.google.gson.reflect.TypeToken; -import org.apache.http.HttpEntity; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.mime.MultipartEntityBuilder; -import org.apache.http.entity.mime.content.FileBody; -import org.apache.http.entity.mime.content.InputStreamBody; -import org.apache.http.entity.mime.content.StringBody; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; +import org.apache.hc.core5.http.HttpEntity; +import org.apache.hc.client5.http.classic.methods.HttpPost; +import org.apache.hc.core5.http.ContentType; +import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder; +import org.apache.hc.client5.http.entity.mime.FileBody; +import org.apache.hc.client5.http.entity.mime.InputStreamBody; +import org.apache.hc.client5.http.entity.mime.StringBody; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -198,16 +195,10 @@ void bulkRootGetFile( contentType = result.contentType; body = result.body; } else { - java.net.HttpURLConnection con = (java.net.HttpURLConnection) sdk.createUrlFrom(url).openConnection(); - con.setInstanceFollowRedirects(false); - con.setConnectTimeout(sdk.priority3TimeoutMillis()); - con.setReadTimeout(sdk.priority3TimeoutMillis()); - status = con.getResponseCode(); - contentType = con.getContentType(); - InputStream stream = SdkHttp.checkedBody(con, status > 299 ? con.getErrorStream() : con.getInputStream()); - // A failed response with no body has no error stream at all. - body = stream == null ? new byte[0] : stream.readAllBytes(); - con.disconnect(); + SdkHttp.Result result = sdk.exchangeHttp("GET", url, null, null, null); + status = result.status; + contentType = result.contentType; + body = result.body; } } catch (Exception e) { errorCallback.onError(ErrorResponse.parseError(sdk.redactedFailure(e))); @@ -290,10 +281,9 @@ private void sendBulkRootMultipart( if (deliverMultipartTransport(url, fields, file.getName(), successCallback, errorCallback)) { return; } - MultipartResponse response; - try (CloseableHttpClient httpClient = HttpClients.createDefault()) { + SdkHttp.Result response; + try { HttpPost uploadFile = new HttpPost(url); - uploadFile.setConfig(sdk.apacheRequestConfig()); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); for (Map.Entry entry : fields.entrySet()) { builder.addPart(entry.getKey(), new StringBody(entry.getValue(), ContentType.TEXT_PLAIN)); @@ -301,12 +291,12 @@ private void sendBulkRootMultipart( builder.addPart("api_key", new StringBody(sdk.priority3ApiKey(), ContentType.TEXT_PLAIN)); builder.addPart("file", new FileBody(file)); uploadFile.setEntity(builder.build()); - response = readMultipartResponse(httpClient.execute(uploadFile)); + response = SdkHttp.execute(uploadFile, sdk.priority3TimeoutMillis()); } catch (Exception e) { errorCallback.onError(ErrorResponse.parseError(sdk.redactedFailure(e))); return; } - sdk.deliverSendFileResponse(response.status, response.contentType, response.body, + sdk.deliverSendFileResponse(response.status, response.contentType, new String(response.body, StandardCharsets.UTF_8), successCallback, errorCallback); } @@ -322,10 +312,9 @@ private void sendBulkRootMultipartStream( if (deliverMultipartTransport(url, fields, fileName, successCallback, errorCallback)) { return; } - MultipartResponse response; - try (CloseableHttpClient httpClient = HttpClients.createDefault()) { + SdkHttp.Result response; + try { HttpPost uploadFile = new HttpPost(url); - uploadFile.setConfig(sdk.apacheRequestConfig()); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); for (Map.Entry entry : fields.entrySet()) { builder.addPart(entry.getKey(), new StringBody(entry.getValue(), ContentType.TEXT_PLAIN)); @@ -333,12 +322,12 @@ private void sendBulkRootMultipartStream( builder.addPart("api_key", new StringBody(sdk.priority3ApiKey(), ContentType.TEXT_PLAIN)); builder.addPart("file", new InputStreamBody(inputStream, ContentType.DEFAULT_BINARY, fileName)); uploadFile.setEntity(builder.build()); - response = readMultipartResponse(httpClient.execute(uploadFile)); + response = SdkHttp.execute(uploadFile, sdk.priority3TimeoutMillis()); } catch (Exception e) { errorCallback.onError(ErrorResponse.parseError(sdk.redactedFailure(e))); return; } - sdk.deliverSendFileResponse(response.status, response.contentType, response.body, + sdk.deliverSendFileResponse(response.status, response.contentType, new String(response.body, StandardCharsets.UTF_8), successCallback, errorCallback); } @@ -396,24 +385,4 @@ private boolean deliverMultipartTransport( return true; } - /** What an upload answered. */ - private static final class MultipartResponse { - final int status; - final String contentType; - final String body; - - MultipartResponse(int status, String contentType, String body) { - this.status = status; - this.contentType = contentType; - this.body = body; - } - } - - private static MultipartResponse readMultipartResponse(CloseableHttpResponse response) throws IOException { - HttpEntity responseEntity = response.getEntity(); - int status = response.getStatusLine().getStatusCode(); - org.apache.http.Header type = response.getFirstHeader("Content-Type"); - return new MultipartResponse(status, type != null ? type.getValue() : "", - SdkHttp.readText(responseEntity.getContent())); - } } diff --git a/zero-bounce-sdk/src/main/java/com/zerobounce/SdkHttp.java b/zero-bounce-sdk/src/main/java/com/zerobounce/SdkHttp.java index 12e4861..0b7722c 100644 --- a/zero-bounce-sdk/src/main/java/com/zerobounce/SdkHttp.java +++ b/zero-bounce-sdk/src/main/java/com/zerobounce/SdkHttp.java @@ -1,16 +1,30 @@ package com.zerobounce; -import java.io.FilterInputStream; +import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase; +import org.apache.hc.client5.http.config.ConnectionConfig; +import org.apache.hc.client5.http.config.RequestConfig; +import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; +import org.apache.hc.client5.http.impl.classic.HttpClientBuilder; +import org.apache.hc.client5.http.impl.classic.HttpClients; +import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder; +import org.apache.hc.core5.http.ContentType; +import org.apache.hc.core5.http.Header; +import org.apache.hc.core5.http.HttpEntity; +import org.apache.hc.core5.http.io.HttpClientResponseHandler; +import org.apache.hc.core5.http.io.entity.ByteArrayEntity; +import org.apache.hc.core5.http.io.entity.EntityUtils; +import org.apache.hc.core5.util.TimeValue; +import org.apache.hc.core5.util.Timeout; + import java.io.IOException; -import java.io.InputStream; -import java.net.HttpURLConnection; +import java.net.URI; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; -/** - * One outbound call. {@link Transport} replaces the network for a single {@link ZeroBounceSDK}. - */ +/** One outbound call, with a per-client replacement transport for offline tests. */ final class SdkHttp { final String method; @@ -18,7 +32,6 @@ final class SdkHttp { final String contentType; final byte[] body; final Map fields; - /** The real clients disable redirects. The offline suite asserts this stays false. */ final boolean followRedirects; SdkHttp(String method, String url, String contentType, byte[] body, Map fields) { @@ -33,66 +46,141 @@ final class SdkHttp { } /** - * The body of an {@link HttpURLConnection} response, checked against its - * {@code Content-Length}. HttpURLConnection ends the stream quietly when the - * connection closes mid-body, so a body cut short would otherwise read as a - * complete one. Reaching the end with fewer bytes than declared throws the - * same message as Apache HttpClient ("Premature end of Content-Length - * delimited message body"), so the caller reports a transport failure with - * status 0 and saves nothing. - * - * @return the stream to read, or null when the response has no body stream + * Clients shared by every {@link ZeroBounceSDK} and {@link ZeroBounceWarmup}, + * one per timeout, so calls reuse connections as HttpURLConnection did instead + * of paying a new TCP and TLS handshake each time. SDK users never close them. + * Reads are lock-free; a new timeout is admitted under the map's lock. */ - static InputStream checkedBody(HttpURLConnection con, InputStream stream) { - if (stream == null) { - return null; + private static final ConcurrentMap SHARED = new ConcurrentHashMap<>(); + /** Past this many distinct timeouts, a call gets a client of its own, closed after it. */ + private static final int MAX_SHARED_CLIENTS = 8; + /** An idle pooled connection is closed by the shared client's evictor once idle this long. */ + private static final TimeValue MAX_IDLE = TimeValue.ofSeconds(5); + + static ConnectionConfig connectionConfig(int timeoutMillis) { + Timeout timeout = Timeout.ofMilliseconds(timeoutMillis); + return ConnectionConfig.custom() + .setConnectTimeout(timeout) + .setSocketTimeout(timeout) + // Automatic retries are off, so a pooled connection the server has + // since closed would fail the call: one idle for over a second is + // checked before it is reused. + .setValidateAfterInactivity(TimeValue.ofSeconds(1)) + .build(); + } + + static RequestConfig requestConfig(int timeoutMillis) { + Timeout timeout = Timeout.ofMilliseconds(timeoutMillis); + return RequestConfig.custom() + .setRedirectsEnabled(false) + .setConnectionRequestTimeout(timeout) + .setResponseTimeout(timeout) + // How long an idle connection may be reused when the server does not say. + .setConnectionKeepAlive(MAX_IDLE) + .build(); + } + + /** + * @param shared whether the client outlives the call. A shared client also + * runs HttpClient's idle-connection evictor, one daemon thread + * that closes connections idle for {@link #MAX_IDLE} or past their + * keep-alive. The pool itself never closes an idle connection until + * it is next used, so without it a burst of concurrent calls would + * leave that many sockets open indefinitely. + */ + static CloseableHttpClient newClient(int timeoutMillis, boolean shared) { + HttpClientBuilder builder = HttpClients.custom() + .setConnectionManager(PoolingHttpClientConnectionManagerBuilder.create() + .setDefaultConnectionConfig(connectionConfig(timeoutMillis)) + // No limit on concurrent calls, as before: HttpURLConnection had + // none and each Apache 4 call built a client of its own. A shared + // pool's default of 5 per host would make the sixth concurrent + // call wait. + .setMaxConnPerRoute(Integer.MAX_VALUE) + .setMaxConnTotal(Integer.MAX_VALUE) + .useSystemProperties() + .build()) + // The JVM's proxy and TLS settings (https.proxyHost, ProxySelector, + // javax.net.ssl.*), which HttpURLConnection honoured. The default + // User-Agent is kept: HttpURLConnection sent one too, and some + // Cloudflare rules block a request without one. + .useSystemProperties() + .disableRedirectHandling() + .disableAutomaticRetries() + .disableCookieManagement(); + if (shared) { + builder.evictExpiredConnections().evictIdleConnections(MAX_IDLE); } - long declared = con.getContentLengthLong(); - if (declared < 0) { - return stream; + return builder.build(); + } + + /** + * The shared client for {@code timeoutMillis}, or null once + * {@link #MAX_SHARED_CLIENTS} other timeouts have one. The size check and the + * insert happen under one lock, so concurrent callers cannot pass the limit. + */ + static CloseableHttpClient sharedClient(int timeoutMillis) { + CloseableHttpClient client = SHARED.get(timeoutMillis); + if (client != null) { + return client; } - return new FilterInputStream(stream) { - private long received; - - @Override - public int read() throws IOException { - int b = super.read(); - if (b < 0) { - checkComplete(); - } else { - received++; - } - return b; + synchronized (SHARED) { + client = SHARED.get(timeoutMillis); + if (client == null && SHARED.size() < MAX_SHARED_CLIENTS) { + client = newClient(timeoutMillis, true); + SHARED.put(timeoutMillis, client); } + return client; + } + } - @Override - public int read(byte[] buffer, int offset, int length) throws IOException { - int n = super.read(buffer, offset, length); - if (n < 0) { - checkComplete(); - } else { - received += n; + /** + * Closes and forgets the shared clients, so the next call builds new ones. + * The offline suites call it whenever they replace {@code HttpClients.custom()}. + */ + static void closeSharedClients() { + synchronized (SHARED) { + for (CloseableHttpClient client : SHARED.values()) { + try { + client.close(); + } catch (IOException ignored) { + // nothing left to release } - return n; } + SHARED.clear(); + } + } - private void checkComplete() throws IOException { - if (received < declared) { - throw new IOException("Premature end of Content-Length delimited message body (expected: " - + declared + "; received: " + received + ")"); - } + private static final HttpClientResponseHandler READ = response -> { + HttpEntity entity = response.getEntity(); + Header type = response.getFirstHeader("Content-Type"); + return new Result(response.getCode(), type == null ? "" : type.getValue(), + entity == null ? new byte[0] : EntityUtils.toByteArray(entity)); + }; + + static Result exchange(String method, URI uri, String contentType, byte[] body, + Map headers, int timeoutMillis) throws IOException { + HttpUriRequestBase request = new HttpUriRequestBase(method, uri); + request.setHeader("Accept", "application/json"); + if (headers != null) { + for (Map.Entry header : headers.entrySet()) { + request.setHeader(header.getKey(), header.getValue()); } - }; + } + if (body != null) { + request.setEntity(new ByteArrayEntity(body, contentType == null ? null : ContentType.parse(contentType))); + } + return execute(request, timeoutMillis); } - /** - * A response body exactly as it arrived, decoded as UTF-8, line breaks - * and all. Reading it line by line and joining the lines dropped every - * line break, which turned a CSV download into a single line. - */ - static String readText(InputStream stream) throws IOException { - try (InputStream in = stream) { - return new String(in.readAllBytes(), java.nio.charset.StandardCharsets.UTF_8); + static Result execute(HttpUriRequestBase request, int timeoutMillis) throws IOException { + request.setConfig(requestConfig(timeoutMillis)); + CloseableHttpClient shared = sharedClient(timeoutMillis); + if (shared != null) { + return shared.execute(request, READ); + } + try (CloseableHttpClient client = newClient(timeoutMillis, false)) { + return client.execute(request, READ); } } diff --git a/zero-bounce-sdk/src/main/java/com/zerobounce/ZeroBounceSDK.java b/zero-bounce-sdk/src/main/java/com/zerobounce/ZeroBounceSDK.java index 04b348e..bbb46ee 100644 --- a/zero-bounce-sdk/src/main/java/com/zerobounce/ZeroBounceSDK.java +++ b/zero-bounce-sdk/src/main/java/com/zerobounce/ZeroBounceSDK.java @@ -8,26 +8,20 @@ import com.google.gson.JsonPrimitive; import com.google.gson.JsonParser; import com.google.gson.reflect.TypeToken; -import org.apache.http.Header; -import org.apache.http.HttpEntity; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.utils.URIBuilder; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.mime.MultipartEntityBuilder; -import org.apache.http.entity.mime.content.FileBody; -import org.apache.http.entity.mime.content.InputStreamBody; -import org.apache.http.entity.mime.content.StringBody; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.util.EntityUtils; +import org.apache.hc.core5.http.HttpEntity; +import org.apache.hc.client5.http.classic.methods.HttpGet; +import org.apache.hc.client5.http.classic.methods.HttpPost; +import org.apache.hc.core5.net.URIBuilder; +import org.apache.hc.core5.http.ContentType; +import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder; +import org.apache.hc.client5.http.entity.mime.FileBody; +import org.apache.hc.client5.http.entity.mime.InputStreamBody; +import org.apache.hc.client5.http.entity.mime.StringBody; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.*; import java.lang.reflect.Type; -import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; @@ -448,14 +442,6 @@ private static List secretForms(String secret) { }; } - org.apache.http.client.config.RequestConfig apacheRequestConfig() { - return org.apache.http.client.config.RequestConfig.custom() - .setRedirectsEnabled(false) - .setConnectTimeout(timeoutInMillis) - .setConnectionRequestTimeout(timeoutInMillis) - .setSocketTimeout(timeoutInMillis) - .build(); - } String redactedFailure(@NotNull Throwable exception) { String message = exception.getMessage(); @@ -1002,9 +988,8 @@ private void _sendFile( int status; String rsp; String responseType = null; - try (CloseableHttpClient httpClient = HttpClients.createDefault()) { + try { HttpPost uploadFile = new HttpPost(urlPath); - uploadFile.setConfig(apacheRequestConfig()); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); // The same fields the offline transport sees, from one builder. addTextParts(builder, sendFileMultipartFields(scoring, emailAddressColumnIndex, options, file.getName())); @@ -1013,15 +998,10 @@ private void _sendFile( HttpEntity multipart = builder.build(); uploadFile.setEntity(multipart); - CloseableHttpResponse response = httpClient.execute(uploadFile); - HttpEntity responseEntity = response.getEntity(); - status = response.getStatusLine().getStatusCode(); - Header typeHeader = response.getFirstHeader("Content-Type"); - responseType = typeHeader != null ? typeHeader.getValue() : ""; - - logDebug("ZeroBounceSDK::sendFile status: " + status); - - rsp = SdkHttp.readText(responseEntity.getContent()); + SdkHttp.Result response = SdkHttp.execute(uploadFile, timeoutInMillis); + status = response.status; + responseType = response.contentType; + rsp = new String(response.body, StandardCharsets.UTF_8); logPayload("ZeroBounceSDK::sendFile rsp=" + rsp); } catch (Exception e) { @@ -1061,9 +1041,8 @@ private void _sendFileStream( int status; String rsp; String responseType = null; - try (CloseableHttpClient httpClient = HttpClients.createDefault()) { + try { HttpPost uploadFile = new HttpPost(urlPath); - uploadFile.setConfig(apacheRequestConfig()); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); // The same fields the offline transport sees, from one builder. addTextParts(builder, sendFileMultipartFields(scoring, emailAddressColumnIndex, options, fileName)); @@ -1072,15 +1051,10 @@ private void _sendFileStream( HttpEntity multipart = builder.build(); uploadFile.setEntity(multipart); - CloseableHttpResponse response = httpClient.execute(uploadFile); - HttpEntity responseEntity = response.getEntity(); - status = response.getStatusLine().getStatusCode(); - Header typeHeader = response.getFirstHeader("Content-Type"); - responseType = typeHeader != null ? typeHeader.getValue() : ""; - - logDebug("ZeroBounceSDK::sendFile status: " + status); - - rsp = SdkHttp.readText(responseEntity.getContent()); + SdkHttp.Result response = SdkHttp.execute(uploadFile, timeoutInMillis); + status = response.status; + responseType = response.contentType; + rsp = new String(response.body, StandardCharsets.UTF_8); logPayload("ZeroBounceSDK::sendFile rsp=" + rsp); } catch (Exception e) { @@ -1276,17 +1250,10 @@ private void _getFile( contentTypeRaw = result.contentType; bodyBytes = result.body; } else { - try (CloseableHttpClient client = HttpClients.createDefault()) { - HttpGet downloadFile = new HttpGet(uri); - downloadFile.setConfig(apacheRequestConfig()); - try (CloseableHttpResponse response = client.execute(downloadFile)) { - statusCode = response.getStatusLine().getStatusCode(); - HttpEntity entity = response.getEntity(); - Header ctHeader = response.getFirstHeader("Content-Type"); - contentTypeRaw = ctHeader != null ? ctHeader.getValue() : ""; - bodyBytes = entity != null ? EntityUtils.toByteArray(entity) : new byte[0]; - } - } + SdkHttp.Result result = SdkHttp.execute(new HttpGet(uri), timeoutInMillis); + statusCode = result.status; + contentTypeRaw = result.contentType; + bodyBytes = result.body; } } catch (Exception e) { logError("ZeroBounceSDK::getFile failed", e); @@ -2565,31 +2532,11 @@ private void sendRequest( responseType = result.contentType; rsp = new String(result.body, StandardCharsets.UTF_8); } else { - URL url = createUrlFrom(urlString); - HttpURLConnection con = (HttpURLConnection) url.openConnection(); - con.setInstanceFollowRedirects(false); - con.setRequestProperty("Accept", "application/json"); - // Timeouts must be set before connect(); the POST branch connects explicitly below. - con.setConnectTimeout(timeoutInMillis); - con.setReadTimeout(timeoutInMillis); - - if (body == null) { - con.setRequestMethod("GET"); - } else { - con.setRequestMethod("POST"); - con.setDoOutput(true); - con.setFixedLengthStreamingMode(payload.length); - con.connect(); - try (OutputStream os = con.getOutputStream()) { - os.write(payload); - } - } - - logDebug("ZeroBounceSDK::sendRequest executing " + httpMethod + " " + urlPath); - status = con.getResponseCode(); - logDebug("ZeroBounceSDK::sendRequest status: " + status); - responseType = con.getContentType(); - rsp = readResponse(con, status); + SdkHttp.Result result = exchangeHttp(httpMethod, urlString, + payload == null ? null : "application/json; charset=UTF-8", payload, null); + status = result.status; + responseType = result.contentType; + rsp = new String(result.body, StandardCharsets.UTF_8); } } catch (Exception e) { logError("ZeroBounceSDK::sendRequest failed", e); @@ -2644,24 +2591,11 @@ private void sendFormPostRequest( responseType = result.contentType; rsp = new String(result.body, StandardCharsets.UTF_8); } else { - URL url = createUrlFrom(urlPath); - HttpURLConnection con = (HttpURLConnection) url.openConnection(); - con.setInstanceFollowRedirects(false); - con.setRequestProperty("Accept", "application/json"); - con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); - con.setConnectTimeout(timeoutInMillis); - con.setReadTimeout(timeoutInMillis); - con.setRequestMethod("POST"); - con.setDoOutput(true); - con.setFixedLengthStreamingMode(out.length); - con.connect(); - try (OutputStream os = con.getOutputStream()) { - os.write(out); - } - - status = con.getResponseCode(); - responseType = con.getContentType(); - rsp = readResponse(con, status); + SdkHttp.Result result = exchangeHttp("POST", urlPath, + "application/x-www-form-urlencoded", out, null); + status = result.status; + responseType = result.contentType; + rsp = new String(result.body, StandardCharsets.UTF_8); } } catch (Exception e) { logError("ZeroBounceSDK::sendFormPostRequest failed", e); @@ -2756,36 +2690,10 @@ private void sendRequestWithMethod( responseType = result.contentType; rsp = new String(result.body, StandardCharsets.UTF_8); } else { - URL url = createUrlFrom(urlString); - HttpURLConnection con = (HttpURLConnection) url.openConnection(); - con.setInstanceFollowRedirects(false); - con.setRequestProperty("Accept", "application/json"); - if (extraHeaders != null) { - for (Map.Entry header : extraHeaders.entrySet()) { - con.setRequestProperty(header.getKey(), header.getValue()); - } - } - con.setConnectTimeout(timeoutInMillis); - con.setReadTimeout(timeoutInMillis); - con.setRequestMethod(method); - if (contentType != null) { - con.setRequestProperty("Content-Type", contentType); - } - - if (out != null) { - con.setDoOutput(true); - con.setFixedLengthStreamingMode(out.length); - con.connect(); - try (OutputStream os = con.getOutputStream()) { - os.write(out); - } - } - - logDebug("ZeroBounceSDK::sendRequestWithMethod executing " + method + " " + urlPath); - - status = con.getResponseCode(); - responseType = con.getContentType(); - rsp = readResponse(con, status); + SdkHttp.Result result = exchangeHttp(method, urlString, contentType, out, extraHeaders); + status = result.status; + responseType = result.contentType; + rsp = new String(result.body, StandardCharsets.UTF_8); } } catch (Exception e) { logError("ZeroBounceSDK::sendRequestWithMethod failed", e); @@ -2830,20 +2738,11 @@ private void sendRequestWithMethod( deliverJson(status, responseType, rsp, typeToken, successCallback, errorCallback); } - /** - * The body of a response. A failed response with no body has no error - * stream at all, so that reads as an empty body rather than a - * NullPointerException that would lose the status. - */ - private static String readResponse(@NotNull HttpURLConnection con, int status) throws IOException { - InputStream stream = SdkHttp.checkedBody(con, status > 299 ? con.getErrorStream() : con.getInputStream()); - if (stream == null) { - con.disconnect(); - return ""; - } - String content = SdkHttp.readText(stream); - con.disconnect(); - return content; + /** One HttpClient 5 exchange; callbacks and decoding remain with the caller. */ + SdkHttp.Result exchangeHttp(String method, String url, String contentType, byte[] body, + Map headers) throws IOException { + return SdkHttp.exchange(method, URI.create(createUrlFrom(url).toExternalForm()), + contentType, body, headers, timeoutInMillis); } /** diff --git a/zero-bounce-sdk/src/main/java/com/zerobounce/ZeroBounceWarmup.java b/zero-bounce-sdk/src/main/java/com/zerobounce/ZeroBounceWarmup.java index 0a71da9..986e812 100644 --- a/zero-bounce-sdk/src/main/java/com/zerobounce/ZeroBounceWarmup.java +++ b/zero-bounce-sdk/src/main/java/com/zerobounce/ZeroBounceWarmup.java @@ -8,8 +8,7 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.io.OutputStream; -import java.net.HttpURLConnection; +import java.io.IOException; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; @@ -136,6 +135,13 @@ URL createUrlFrom(String url) throws MalformedURLException { return URI.create(url).toURL(); } + /** One HttpClient 5 exchange, separate from callback delivery. */ + SdkHttp.Result exchangeHttp(String method, String url, String contentType, byte[] body, + Map headers) throws IOException { + return SdkHttp.exchange(method, URI.create(createUrlFrom(url).toExternalForm()), + contentType, body, headers, timeoutInMillis); + } + private boolean notReady(@NotNull ZeroBounceSDK.OnErrorCallback errorCallback) { if (setupProblem == null) { return false; @@ -162,37 +168,13 @@ private static class Result { // caller's error callback must reach the caller, not be reported again. Result result = new Result(); try { - HttpURLConnection con = (HttpURLConnection) createUrlFrom(url).openConnection(); - con.setRequestMethod(method); - con.setRequestProperty("Accept", "application/json"); - con.setRequestProperty("API-Key", apiKey); - con.setConnectTimeout(timeoutInMillis); - con.setReadTimeout(timeoutInMillis); - con.setInstanceFollowRedirects(false); - - if (jsonBody != null) { - byte[] out = jsonBody.getBytes(StandardCharsets.UTF_8); - con.setRequestProperty("Content-Type", "application/json"); - con.setDoOutput(true); - con.setFixedLengthStreamingMode(out.length); - con.connect(); - try (OutputStream os = con.getOutputStream()) { - os.write(out); - } - } - - result.status = con.getResponseCode(); - String contentType = con.getHeaderField("Content-Type"); - result.contentType = contentType != null ? contentType : ""; - - // A failed response with no body has no error stream at all; read - // it as an empty body so the status is kept. - java.io.InputStream stream = SdkHttp.checkedBody( - con, result.status > 299 ? con.getErrorStream() : con.getInputStream()); - // The body as it arrived: a CSV download keeps its line breaks. - String content = stream == null ? "" : SdkHttp.readText(stream); - con.disconnect(); - result.body = content; + SdkHttp.Result response = exchangeHttp(method, url, + jsonBody == null ? null : "application/json", + jsonBody == null ? null : jsonBody.getBytes(StandardCharsets.UTF_8), + Map.of("API-Key", apiKey)); + result.status = response.status; + result.contentType = response.contentType; + result.body = new String(response.body, StandardCharsets.UTF_8); } catch (Exception e) { // Rebuilt rather than wrapped: the original holds the URL and headers. errorCallback.onError(ErrorResponse.parseError(redact(e.getMessage(), secrets))); diff --git a/zero-bounce-sdk/src/test/java/com/zerobounce/HttpClientTestSupport.java b/zero-bounce-sdk/src/test/java/com/zerobounce/HttpClientTestSupport.java new file mode 100644 index 0000000..a020d18 --- /dev/null +++ b/zero-bounce-sdk/src/test/java/com/zerobounce/HttpClientTestSupport.java @@ -0,0 +1,46 @@ +package com.zerobounce; + +import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; +import org.apache.hc.client5.http.impl.classic.HttpClientBuilder; +import org.apache.hc.client5.http.impl.classic.HttpClients; +import org.mockito.MockedStatic; +import org.mockito.Mockito; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Proxy; + +import static org.mockito.Mockito.RETURNS_SELF; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** Only the HTTP client factory is replaced; SDK response handling still runs. */ +final class HttpClientTestSupport { + static HttpClientBuilder builder(CloseableHttpClient client) { + HttpClientBuilder builder = mock(HttpClientBuilder.class, RETURNS_SELF); + when(builder.build()).thenReturn(client); + return builder; + } + + /** + * {@code Mockito.mockStatic(HttpClients.class)}, dropping the SDK's shared + * clients when it opens and when it closes. Otherwise a client built before + * the mock would bypass it, and one built from the mock would outlive it. + */ + @SuppressWarnings("unchecked") + static MockedStatic mockClients() { + SdkHttp.closeSharedClients(); + MockedStatic mocked = Mockito.mockStatic(HttpClients.class); + return (MockedStatic) Proxy.newProxyInstance(MockedStatic.class.getClassLoader(), + new Class[]{MockedStatic.class}, (proxy, method, args) -> { + try { + return method.invoke(mocked, args); + } catch (InvocationTargetException e) { + throw e.getCause(); + } finally { + if (method.getName().startsWith("close")) { + SdkHttp.closeSharedClients(); + } + } + }); + } +} diff --git a/zero-bounce-sdk/src/test/java/com/zerobounce/LoopbackServer.java b/zero-bounce-sdk/src/test/java/com/zerobounce/LoopbackServer.java index 96fe378..fa2d63e 100644 --- a/zero-bounce-sdk/src/test/java/com/zerobounce/LoopbackServer.java +++ b/zero-bounce-sdk/src/test/java/com/zerobounce/LoopbackServer.java @@ -1,12 +1,12 @@ package com.zerobounce; -import org.apache.http.HttpHost; -import org.apache.http.HttpRequestInterceptor; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.protocol.HttpClientContext; -import org.apache.http.conn.routing.HttpRoute; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.client.HttpClients; +import org.apache.hc.core5.http.HttpHost; +import org.apache.hc.core5.http.HttpRequestInterceptor; +import org.apache.hc.client5.http.config.RequestConfig; +import org.apache.hc.client5.http.protocol.HttpClientContext; +import org.apache.hc.client5.http.HttpRoute; +import org.apache.hc.client5.http.impl.classic.HttpClientBuilder; +import org.apache.hc.client5.http.impl.classic.HttpClients; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -15,14 +15,10 @@ import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.Field; -import java.net.HttpURLConnection; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.URI; -import java.net.URL; -import java.net.URLConnection; -import java.net.URLStreamHandler; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; @@ -39,10 +35,8 @@ /** * A real HTTP/1.1 server on a loopback socket, answering every connection with * raw bytes the test chooses: a body cut short of its {@code Content-Length}, a - * redirect, or nothing at all. The SDK's real clients talk to it: the - * {@code HttpURLConnection} paths through {@link #sdk()} and {@link #warmup()}, - * whose URLs are re-pointed here, and the Apache HttpClient paths through - * {@link #apacheClients()}. Nothing reaches the network. + * redirect, or nothing at all. The SDK's real HttpClient 5 exchanges are routed + * here by {@link #apacheClients()}. Nothing reaches the live API. */ final class LoopbackServer implements AutoCloseable { @@ -70,8 +64,6 @@ interface Responder { private final List requests = Collections.synchronizedList(new ArrayList<>()); private final CountDownLatch closed = new CountDownLatch(1); - /** Every HttpURLConnection the clients from {@link #sdk()} and {@link #warmup()} opened. */ - final List connections = Collections.synchronizedList(new ArrayList<>()); /** The request config of every request the clients from {@link #apacheClients()} sent. */ final List apacheConfigs = Collections.synchronizedList(new ArrayList<>()); @@ -95,7 +87,6 @@ List requests() { void clear() { requests.clear(); - connections.clear(); apacheConfigs.clear(); } @@ -276,25 +267,13 @@ String local(String url) { return "http://127.0.0.1:" + port() + uri.getRawPath() + (uri.getRawQuery() == null ? "" : "?" + uri.getRawQuery()); } - /** A URL on this server whose connection is recorded in {@link #connections}. */ - private URL recordingUrl(String url) throws IOException { - return URL.of(URI.create(local(url)), new URLStreamHandler() { - @Override - protected URLConnection openConnection(URL u) throws IOException { - HttpURLConnection connection = (HttpURLConnection) URI.create(u.toExternalForm()).toURL().openConnection(); - connections.add(connection); - return connection; - } - }); - } - /** - * A {@link ZeroBounceSDK} whose HttpURLConnection requests come here. Its + * A {@link ZeroBounceSDK} whose ordinary requests come here. Its * Apache HttpClient requests need {@link #apacheClients()} as well. */ ZeroBounceSDK sdk() throws Exception { ZeroBounceSDK sdk = spy(new ZeroBounceSDK()); - doAnswer(invocation -> recordingUrl(invocation.getArgument(0))).when(sdk).createUrlFrom(anyString()); + doAnswer(invocation -> URI.create(local(invocation.getArgument(0))).toURL()).when(sdk).createUrlFrom(anyString()); // The spy copied the original's Priority3Api, which still calls the // original's createUrlFrom. Field field = ZeroBounceSDK.class.getDeclaredField("priority3Api"); @@ -305,23 +284,22 @@ ZeroBounceSDK sdk() throws Exception { ZeroBounceWarmup warmup() throws Exception { ZeroBounceWarmup warmup = spy(new ZeroBounceWarmup()); - doAnswer(invocation -> recordingUrl(invocation.getArgument(0))).when(warmup).createUrlFrom(anyString()); + doAnswer(invocation -> URI.create(local(invocation.getArgument(0))).toURL()).when(warmup).createUrlFrom(anyString()); return warmup; } /** - * Until closed, every {@code HttpClients.createDefault()} on this thread - * returns a real client routed to this server (or to the loopback host and + * Until closed, every {@code HttpClients.custom()} on this thread + * returns a real builder routed to this server (or to the loopback host and * port a redirect names), which records each request's config. */ MockedStatic apacheClients() { - MockedStatic clients = Mockito.mockStatic(HttpClients.class); - clients.when(HttpClients::createDefault).thenAnswer(invocation -> HttpClientBuilder.create() - .setRoutePlanner((target, request, context) -> new HttpRoute(new HttpHost("127.0.0.1", - "127.0.0.1".equals(target.getHostName()) ? target.getPort() : port(), "http"))) - .addInterceptorLast((HttpRequestInterceptor) (request, context) -> - apacheConfigs.add(HttpClientContext.adapt(context).getRequestConfig())) - .build()); + MockedStatic clients = HttpClientTestSupport.mockClients(); + clients.when(HttpClients::custom).thenAnswer(invocation -> HttpClientBuilder.create() + .setRoutePlanner((target, context) -> new HttpRoute(new HttpHost("http", "127.0.0.1", + "127.0.0.1".equals(target.getHostName()) ? target.getPort() : port()))) + .addRequestInterceptorLast((HttpRequestInterceptor) (request, entity, context) -> + apacheConfigs.add(HttpClientContext.cast(context).getRequestConfig()))); return clients; } } diff --git a/zero-bounce-sdk/src/test/java/com/zerobounce/OfflineApiTest.java b/zero-bounce-sdk/src/test/java/com/zerobounce/OfflineApiTest.java index d3d58c7..2a2376c 100644 --- a/zero-bounce-sdk/src/test/java/com/zerobounce/OfflineApiTest.java +++ b/zero-bounce-sdk/src/test/java/com/zerobounce/OfflineApiTest.java @@ -2,14 +2,13 @@ import com.google.gson.JsonObject; import com.google.gson.JsonParser; -import org.apache.http.HttpEntity; -import org.apache.http.StatusLine; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpRequestBase; -import org.apache.http.client.methods.HttpUriRequest; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; +import org.apache.hc.core5.http.HttpEntity; +import org.apache.hc.core5.http.io.HttpClientResponseHandler; +import org.apache.hc.client5.http.config.RequestConfig; +import org.apache.hc.core5.http.ClassicHttpResponse; +import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase; +import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; +import org.apache.hc.client5.http.impl.classic.HttpClients; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.mockito.ArgumentCaptor; @@ -19,8 +18,6 @@ import java.io.ByteArrayInputStream; import java.io.File; import java.io.InputStream; -import java.net.HttpURLConnection; -import java.net.URL; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; @@ -804,17 +801,15 @@ void separateClientsDoNotMixKeys() throws Exception { } @Test - void urlConnectionDoesNotFollowRedirects() throws Exception { - ZeroBounceSDK sdk = spy(new ZeroBounceSDK()); - sdk.initialize("key"); - URL url = mock(URL.class); - HttpURLConnection connection = mock(HttpURLConnection.class); - when(url.openConnection()).thenReturn(connection); - when(connection.getResponseCode()).thenReturn(200); - when(connection.getInputStream()).thenReturn(new ByteArrayInputStream("{\"Credits\":\"1\"}".getBytes(StandardCharsets.UTF_8))); - doReturn(url).when(sdk).createUrlFrom(anyString()); - sdk.getCredits(response -> assertEquals("1", response.getCredits()), error -> fail(error.getErrors().toString())); - verify(connection).setInstanceFollowRedirects(false); + void jsonCallsDoNotFollowRedirects() throws Exception { + try (LoopbackServer server = new LoopbackServer(LoopbackServer.redirect(302, "https://elsewhere.invalid/")); + MockedStatic ignored = server.apacheClients()) { + ZeroBounceSDK sdk = server.sdk(); + sdk.initialize("key"); + sdk.getCredits(response -> fail("redirect accepted"), error -> assertEquals(302, error.getStatusCode())); + assertEquals(1, server.requests().size()); + assertFalse(server.apacheConfigs.get(0).isRedirectsEnabled()); + } } @Test @@ -822,23 +817,23 @@ void apacheDownloadDoesNotFollowRedirects() throws Exception { ZeroBounceSDK sdk = new ZeroBounceSDK(); sdk.initialize("key"); CloseableHttpClient client = mock(CloseableHttpClient.class); - CloseableHttpResponse response = mock(CloseableHttpResponse.class); + ClassicHttpResponse response = mock(ClassicHttpResponse.class); HttpEntity entity = mock(HttpEntity.class); - StatusLine status = mock(StatusLine.class); - ArgumentCaptor captor = ArgumentCaptor.forClass(HttpUriRequest.class); - when(client.execute(captor.capture())).thenReturn(response); + ArgumentCaptor captor = ArgumentCaptor.forClass(HttpUriRequestBase.class); + when(client.execute(captor.capture(), org.mockito.ArgumentMatchers.>any())) + .thenAnswer(invocation -> invocation.>getArgument(1) + .handleResponse(response)); when(response.getEntity()).thenReturn(entity); - when(response.getStatusLine()).thenReturn(status); - when(status.getStatusCode()).thenReturn(200); + when(response.getCode()).thenReturn(200); when(response.getFirstHeader("Content-Type")).thenReturn(null); when(entity.getContent()).thenReturn(new ByteArrayInputStream("email\n".getBytes(StandardCharsets.UTF_8))); - try (MockedStatic clients = Mockito.mockStatic(HttpClients.class)) { - clients.when(HttpClients::createDefault).thenReturn(client); + try (MockedStatic clients = HttpClientTestSupport.mockClients()) { + clients.when(HttpClients::custom).thenAnswer(invocation -> HttpClientTestSupport.builder(client)); Path out = tempDir.resolve("apache.csv"); sdk.getFile("fid", out.toString(), responseBody -> { }, error -> fail(error.getErrors().toString())); } - RequestConfig config = ((HttpRequestBase) captor.getValue()).getConfig(); + RequestConfig config = captor.getValue().getConfig(); assertNotNull(config); assertFalse(config.isRedirectsEnabled()); } @@ -959,12 +954,9 @@ void methodPathEmpty500WithNoErrorStreamKeepsItsStatus() throws Exception { // an empty error list and status 0. ZeroBounceSDK sdk = spy(new ZeroBounceSDK()); sdk.initialize(METHOD_PATH_KEY); - URL url = mock(URL.class); - HttpURLConnection connection = mock(HttpURLConnection.class); - when(url.openConnection()).thenReturn(connection); - when(connection.getResponseCode()).thenReturn(500); - when(connection.getErrorStream()).thenReturn(null); - doReturn(url).when(sdk).createUrlFrom(anyString()); + doReturn(new SdkHttp.Result(500, "", new byte[0])).when(sdk) + .exchangeHttp(anyString(), anyString(), org.mockito.ArgumentMatchers.nullable(String.class), + org.mockito.ArgumentMatchers.nullable(byte[].class), org.mockito.ArgumentMatchers.nullable(Map.class)); for (Map.Entry entry : Map.of( "validate", (Call) (ok, err) -> sdk.validate("a@example.com", "", ok, err), "getCredits", (Call) (ok, err) -> sdk.getCredits(ok, err) diff --git a/zero-bounce-sdk/src/test/java/com/zerobounce/OfflineParityTest.java b/zero-bounce-sdk/src/test/java/com/zerobounce/OfflineParityTest.java index 66237a9..d2a7d5f 100644 --- a/zero-bounce-sdk/src/test/java/com/zerobounce/OfflineParityTest.java +++ b/zero-bounce-sdk/src/test/java/com/zerobounce/OfflineParityTest.java @@ -7,11 +7,7 @@ import org.mockito.Spy; import org.mockito.junit.jupiter.MockitoExtension; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; -import java.net.HttpURLConnection; -import java.net.URL; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; import java.util.ArrayList; @@ -28,7 +24,7 @@ * options, real-time AI scoring, the filters, the list evaluator, the S3 and * SFTP/FTP bulk jobs and the Inbox Placement Tester. *

- * Every request is answered by a mocked {@link HttpURLConnection}; nothing here + * Every request is answered by a replacement HTTP exchange; nothing here * reaches the live API. The assertions are on what actually went on the wire. */ @ExtendWith(MockitoExtension.class) @@ -38,7 +34,7 @@ * It is a second offline suite beside {@link OfflineApiTest} rather than part * of it: the two were written against different seams — {@code OfflineApiTest} * swaps in a {@code FakeApi} transport, while this one mocks - * {@code HttpURLConnection} directly — and both sets of assertions are worth + * the HTTP exchange directly — and both sets of assertions are worth * keeping. The parity cases live here, the transport-level cases there. */ public class OfflineParityTest { @@ -107,48 +103,21 @@ public void setUp() { * Returns the recorded calls, in order. */ private List mockAll(int status, @NotNull String responseJson) throws IOException { - ByteArrayOutputStream sentBody = new ByteArrayOutputStream(); - - URL url = mock(URL.class, withSettings().useConstructor("https://api.zerobounce.net/v2/validate")); - HttpURLConnection con = mock(HttpURLConnection.class); - lenient().when(url.openConnection()).thenReturn(con); - lenient().when(con.getResponseCode()).thenReturn(status); - lenient().when(con.getOutputStream()).thenReturn(sentBody); - lenient().when(con.getInputStream()) - .thenAnswer(i -> new ByteArrayInputStream(responseJson.getBytes(StandardCharsets.UTF_8))); - lenient().when(con.getErrorStream()) - .thenAnswer(i -> new ByteArrayInputStream(responseJson.getBytes(StandardCharsets.UTF_8))); - lenient().doAnswer(invocation -> { Recorded record = new Recorded(); - record.url = invocation.getArgument(0); + record.method = invocation.getArgument(0); + record.url = invocation.getArgument(1); + record.headers.put("Accept", "application/json"); + String type = invocation.getArgument(2); + if (type != null) record.headers.put("Content-Type", type); + byte[] body = invocation.getArgument(3); + record.body = body == null ? "" : new String(body, StandardCharsets.UTF_8); + Map headers = invocation.getArgument(4); + if (headers != null) record.headers.putAll(headers); recorded.add(record); - sentBody.reset(); - return url; - }).when(zeroBounceSDK).createUrlFrom(anyString()); - - lenient().doAnswer(invocation -> { - if (!recorded.isEmpty()) { - recorded.get(recorded.size() - 1).method = invocation.getArgument(0); - } - return null; - }).when(con).setRequestMethod(anyString()); - - lenient().doAnswer(invocation -> { - if (!recorded.isEmpty()) { - recorded.get(recorded.size() - 1).headers - .put(invocation.getArgument(0), invocation.getArgument(1)); - } - return null; - }).when(con).setRequestProperty(anyString(), anyString()); - - // The body is written after setRequestMethod, so read it back lazily. - lenient().doAnswer(invocation -> { - if (!recorded.isEmpty()) { - recorded.get(recorded.size() - 1).body = sentBody.toString(StandardCharsets.UTF_8); - } - return null; - }).when(con).disconnect(); + return new SdkHttp.Result(status, "application/json", responseJson.getBytes(StandardCharsets.UTF_8)); + }).when(zeroBounceSDK).exchangeHttp(anyString(), anyString(), nullable(String.class), + nullable(byte[].class), nullable(Map.class)); return recorded; } diff --git a/zero-bounce-sdk/src/test/java/com/zerobounce/OfflineRedactionFuzzTest.java b/zero-bounce-sdk/src/test/java/com/zerobounce/OfflineRedactionFuzzTest.java index 4bf3227..25ec993 100644 --- a/zero-bounce-sdk/src/test/java/com/zerobounce/OfflineRedactionFuzzTest.java +++ b/zero-bounce-sdk/src/test/java/com/zerobounce/OfflineRedactionFuzzTest.java @@ -1,6 +1,6 @@ package com.zerobounce; -import org.apache.http.impl.client.HttpClients; +import org.apache.hc.client5.http.impl.classic.HttpClients; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.mockito.MockedStatic; diff --git a/zero-bounce-sdk/src/test/java/com/zerobounce/OfflineRedactionSweepTest.java b/zero-bounce-sdk/src/test/java/com/zerobounce/OfflineRedactionSweepTest.java index 89fafae..e6c909d 100644 --- a/zero-bounce-sdk/src/test/java/com/zerobounce/OfflineRedactionSweepTest.java +++ b/zero-bounce-sdk/src/test/java/com/zerobounce/OfflineRedactionSweepTest.java @@ -1,6 +1,6 @@ package com.zerobounce; -import org.apache.http.impl.client.HttpClients; +import org.apache.hc.client5.http.impl.classic.HttpClients; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.mockito.MockedStatic; diff --git a/zero-bounce-sdk/src/test/java/com/zerobounce/OfflineSendFileMultipartTest.java b/zero-bounce-sdk/src/test/java/com/zerobounce/OfflineSendFileMultipartTest.java index 6ea2f69..c8d039b 100644 --- a/zero-bounce-sdk/src/test/java/com/zerobounce/OfflineSendFileMultipartTest.java +++ b/zero-bounce-sdk/src/test/java/com/zerobounce/OfflineSendFileMultipartTest.java @@ -1,6 +1,6 @@ package com.zerobounce; -import org.apache.http.impl.client.HttpClients; +import org.apache.hc.client5.http.impl.classic.HttpClients; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.mockito.MockedStatic; diff --git a/zero-bounce-sdk/src/test/java/com/zerobounce/OfflineStrictJsonCorpusTest.java b/zero-bounce-sdk/src/test/java/com/zerobounce/OfflineStrictJsonCorpusTest.java index 7c68eb1..4b3ca50 100644 --- a/zero-bounce-sdk/src/test/java/com/zerobounce/OfflineStrictJsonCorpusTest.java +++ b/zero-bounce-sdk/src/test/java/com/zerobounce/OfflineStrictJsonCorpusTest.java @@ -1,7 +1,7 @@ package com.zerobounce; import com.google.gson.JsonParser; -import org.apache.http.impl.client.HttpClients; +import org.apache.hc.client5.http.impl.classic.HttpClients; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.mockito.MockedStatic; diff --git a/zero-bounce-sdk/src/test/java/com/zerobounce/OfflineTransportTest.java b/zero-bounce-sdk/src/test/java/com/zerobounce/OfflineTransportTest.java index 3df35da..1ce8e1d 100644 --- a/zero-bounce-sdk/src/test/java/com/zerobounce/OfflineTransportTest.java +++ b/zero-bounce-sdk/src/test/java/com/zerobounce/OfflineTransportTest.java @@ -1,7 +1,7 @@ package com.zerobounce; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.impl.client.HttpClients; +import org.apache.hc.client5.http.config.RequestConfig; +import org.apache.hc.client5.http.impl.classic.HttpClients; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.mockito.MockedStatic; @@ -11,7 +11,7 @@ import java.io.FilterOutputStream; import java.io.IOException; import java.lang.reflect.Method; -import java.net.HttpURLConnection; +import java.net.URI; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; @@ -19,10 +19,19 @@ import java.util.ArrayList; import java.util.List; import java.util.Locale; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -90,10 +99,7 @@ void theSweepCoversEveryPublicRequestMethod() { /** * A 200 that declares 1000 bytes and closes after 33 is a transport failure * (status 0) on every path, like Apache's "Premature end of Content-Length - * delimited message body", and a download leaves no file. From JDK 25, - * HttpURLConnection detects the short body itself and throws "Premature EOF" - * before the SDK's own check sees the end of the stream; either message is a - * transport failure. + * delimited message body", and a download leaves no file. */ @Test void everyRequestPathTreatsABodyCutShortAsATransportFailure() throws Exception { @@ -145,10 +151,8 @@ void everyRequestPathRefusesARedirect() throws Exception { || outcome.errors.get(0).getStatusCode() != status) { failures.add(status + " " + outcome); } - // A POST in fixed-length streaming mode cannot follow a - // redirect either way, so the setting is checked as well. - for (HttpURLConnection connection : List.copyOf(server.connections)) { - if (connection.getInstanceFollowRedirects()) { + for (RequestConfig config : List.copyOf(server.apacheConfigs)) { + if (config.isRedirectsEnabled()) { failures.add(outcome.signature + " opened a connection that follows redirects"); } } @@ -160,12 +164,14 @@ void everyRequestPathRefusesARedirect() throws Exception { /** * Every request the SDK sends has the documented default connect and read - * timeout, 120 s, on the default settings: each HttpURLConnection, and each - * Apache request's config (connect, socket and connection-request - * timeouts). The exact value, so a changed or dropped default fails (T2). + * timeout, 120 s, on the default settings. HttpClient 5 configures connection + * establishment on the connection manager and response/lease timeouts on + * each request. The exact value, so a changed or dropped default fails (T2). */ @Test void everyRequestPathSetsConnectAndReadTimeouts() throws Exception { + assertEquals(DEFAULT_TIMEOUT, SdkHttp.connectionConfig(DEFAULT_TIMEOUT).getConnectTimeout().toMilliseconds()); + assertEquals(DEFAULT_TIMEOUT, SdkHttp.connectionConfig(DEFAULT_TIMEOUT).getSocketTimeout().toMilliseconds()); RequestSweep sweep = new RequestSweep(tempDir); LoopbackServer.Responder csv = LoopbackServer.answer(200, "text/csv", CSV); LoopbackServer.Responder json = LoopbackServer.answer(200, "application/json", "{}".getBytes(StandardCharsets.UTF_8)); @@ -174,21 +180,13 @@ void everyRequestPathSetsConnectAndReadTimeouts() throws Exception { (target.contains("getfile") || target.contains("download") ? csv : json).respond(request, out); })) { sweep(sweep, server, (method, outcome, failures) -> { - List connections = List.copyOf(server.connections); List configs = List.copyOf(server.apacheConfigs); - if (connections.size() + configs.size() < server.requests().size()) { + if (configs.size() < server.requests().size()) { failures.add(outcome.signature + " sent a request the sweep could not inspect"); } - for (HttpURLConnection connection : connections) { - if (connection.getConnectTimeout() != DEFAULT_TIMEOUT || connection.getReadTimeout() != DEFAULT_TIMEOUT) { - failures.add(outcome.signature + " connect " + connection.getConnectTimeout() - + " ms, read " + connection.getReadTimeout() + " ms"); - } - } for (RequestConfig config : configs) { - if (config == null || config.getConnectTimeout() != DEFAULT_TIMEOUT - || config.getSocketTimeout() != DEFAULT_TIMEOUT - || config.getConnectionRequestTimeout() != DEFAULT_TIMEOUT) { + if (config == null || config.getResponseTimeout().toMilliseconds() != DEFAULT_TIMEOUT + || config.getConnectionRequestTimeout().toMilliseconds() != DEFAULT_TIMEOUT) { failures.add(outcome.signature + " Apache config " + config); } } @@ -196,6 +194,181 @@ void everyRequestPathSetsConnectAndReadTimeouts() throws Exception { } } + /** + * The real client honours the JVM proxy settings, as HttpURLConnection did: + * with {@code http.proxyHost} set, a request for another host goes to the + * proxy, in absolute form, instead of straight to that host. + */ + @Test + void theJvmProxySettingsAreHonoured() throws Exception { + String host = System.getProperty("http.proxyHost"); + String port = System.getProperty("http.proxyPort"); + try (LoopbackServer proxy = new LoopbackServer(LoopbackServer.answer(200, "application/json", + "{}".getBytes(StandardCharsets.UTF_8)))) { + SdkHttp.closeSharedClients(); + System.setProperty("http.proxyHost", "127.0.0.1"); + System.setProperty("http.proxyPort", String.valueOf(proxy.port())); + String url = "http://proxied.invalid/v2/getcredits?api_key=" + KEY; + SdkHttp.Result result = SdkHttp.exchange("GET", URI.create(url), null, null, null, 5_000); + assertEquals(200, result.status); + assertEquals(1, proxy.requests().size()); + assertEquals(url, proxy.requests().get(0).target); + } finally { + restoreProperty("http.proxyHost", host); + restoreProperty("http.proxyPort", port); + SdkHttp.closeSharedClients(); + } + } + + private static void restoreProperty(String name, String value) { + if (value == null) { + System.clearProperty(name); + } else { + System.setProperty(name, value); + } + } + + /** + * Requests carry the HTTP client's own User-Agent, as HttpURLConnection sent + * its own: a request with none is one some Cloudflare rules block. + */ + @Test + void requestsCarryTheHttpClientsUserAgent() throws Exception { + try (LoopbackServer server = new LoopbackServer(LoopbackServer.answer(200, "application/json", + "{}".getBytes(StandardCharsets.UTF_8)))) { + SdkHttp.exchange("GET", URI.create("http://127.0.0.1:" + server.port() + "/v2/getcredits"), + null, null, null, 5_000); + String agent = server.requests().get(0).headers.get("user-agent"); + assertTrue(agent != null && agent.startsWith("Apache-HttpClient/"), String.valueOf(agent)); + } + } + + /** + * Calls with the same timeout share one client, and so its connection pool, + * across calls and instances. Past eight distinct timeouts a call gets a + * client of its own instead of growing the set without bound. + */ + @Test + void callsWithTheSameTimeoutShareOneClient() { + SdkHttp.closeSharedClients(); + try { + assertSame(SdkHttp.sharedClient(1_234), SdkHttp.sharedClient(1_234)); + assertNotSame(SdkHttp.sharedClient(1_234), SdkHttp.sharedClient(4_321)); + for (int timeout = 1; timeout <= 6; timeout++) { + assertNotNull(SdkHttp.sharedClient(timeout), "shared client " + timeout); + } + assertNull(SdkHttp.sharedClient(99_999), "a ninth distinct timeout"); + } finally { + SdkHttp.closeSharedClients(); + } + } + + /** + * Callers that arrive together with distinct timeouts cannot push the shared + * clients past eight: the size check and the insert are one step. + */ + @Test + void concurrentCallersCannotPassTheSharedClientLimit() throws Exception { + SdkHttp.closeSharedClients(); + int callers = 64; + ExecutorService pool = Executors.newFixedThreadPool(callers); + try { + CountDownLatch start = new CountDownLatch(1); + List> admitted = new ArrayList<>(); + for (int i = 0; i < callers; i++) { + int timeout = 10_000 + i; + admitted.add(pool.submit(() -> { + start.await(); + return SdkHttp.sharedClient(timeout) != null; + })); + } + start.countDown(); + int shared = 0; + for (Future result : admitted) { + if (result.get(10, TimeUnit.SECONDS)) { + shared++; + } + } + assertEquals(8, shared, "distinct timeouts given a shared client"); + } finally { + pool.shutdownNow(); + SdkHttp.closeSharedClients(); + } + } + + @Test + void everyRequestPathReports429And503WithoutRetrying() throws Exception { + for (int status : new int[]{429, 503}) { + Path dir = tempDir.resolve(String.valueOf(status)); + Files.createDirectories(dir); + RequestSweep sweep = new RequestSweep(dir); + try (LoopbackServer server = new LoopbackServer(LoopbackServer.answer(status, + "application/json", "{\"error\":\"Try again later\"}".getBytes(StandardCharsets.UTF_8)))) { + sweep(sweep, server, (method, outcome, failures) -> { + if (server.requests().size() != 1 || !outcome.successes.isEmpty() + || outcome.errors.size() != 1 || outcome.errors.get(0).getStatusCode() != status) { + failures.add(status + " " + outcome + " requests=" + server.requests().size()); + } + }); + } + } + } + + @Test + void jsonFormsAndAuthenticationReachTheServerUnchanged() throws Exception { + String key = "key+with/slash"; + String email = "té+tag@example.com"; + List errors = new ArrayList<>(); + try (LoopbackServer server = new LoopbackServer(LoopbackServer.answer(400, + "application/json", "{\"error\":\"offline fixture\"}".getBytes(StandardCharsets.UTF_8))); + MockedStatic ignored = server.apacheClients()) { + ZeroBounceSDK sdk = server.sdk(); + sdk.initialize(key); + sdk.validateBatch(List.of(new ZBValidateBatchData(email, null)), r -> { + throw new AssertionError("expected fixture error"); + }, errors::add); + LoopbackServer.Request json = server.requests().get(0); + assertEquals("POST", json.method); + assertEquals("application/json; charset=UTF-8", json.headers.get("content-type")); + assertEquals("{\"api_key\":\"" + key + "\",\"email_batch\":[{\"email_address\":\"" + email + "\"}]}", + new String(json.body, StandardCharsets.UTF_8)); + + ZBValidateRequestOptions options = new ZBValidateRequestOptions(); + options.setUsePost(true); + sdk.validateWithOptions(email, options, r -> { + throw new AssertionError("expected fixture error"); + }, errors::add); + LoopbackServer.Request form = server.requests().get(1); + assertEquals("POST", form.method); + assertEquals("application/x-www-form-urlencoded", form.headers.get("content-type")); + String body = new String(form.body, StandardCharsets.UTF_8); + assertTrue(body.contains("api_key=key%2Bwith%2Fslash"), body); + assertTrue(body.contains("email=t%C3%A9%2Btag%40example.com"), body); + + sdk.createInboxPlacementTest("wire check", null, r -> { + throw new AssertionError("expected fixture error"); + }, errors::add); + LoopbackServer.Request bearer = server.requests().get(2); + assertEquals("Bearer " + key, bearer.headers.get("authorization")); + assertFalse(bearer.target.contains("api_key"), bearer.target); + assertEquals("{\"name\":\"wire check\"}", new String(bearer.body, StandardCharsets.UTF_8)); + + ZeroBounceWarmup warmup = server.warmup(); + warmup.initialize(key); + warmup.getSeedCount(r -> { + throw new AssertionError("expected fixture error"); + }, errors::add); + LoopbackServer.Request warmupRequest = server.requests().get(3); + assertEquals(key, warmupRequest.headers.get("api-key")); + assertFalse(warmupRequest.target.contains(key), warmupRequest.target); + assertEquals(4, server.requests().size()); + assertEquals(4, errors.size()); + for (ErrorResponse error : errors) { + assertEquals(400, error.getStatusCode()); + } + } + } + /** * A server that accepts the request and never answers ends in a timeout * error (status 0) on each kind of transport: the JSON calls, the bulk-root diff --git a/zero-bounce-sdk/src/test/java/com/zerobounce/OfflineWarmupTest.java b/zero-bounce-sdk/src/test/java/com/zerobounce/OfflineWarmupTest.java index 17854a9..6cf313b 100644 --- a/zero-bounce-sdk/src/test/java/com/zerobounce/OfflineWarmupTest.java +++ b/zero-bounce-sdk/src/test/java/com/zerobounce/OfflineWarmupTest.java @@ -9,11 +9,7 @@ import org.mockito.Spy; import org.mockito.junit.jupiter.MockitoExtension; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; -import java.net.HttpURLConnection; -import java.net.URL; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; import java.util.ArrayList; @@ -27,7 +23,7 @@ /** * Offline tests for the Warmup API client. Every request is answered by a - * mocked {@link HttpURLConnection}; nothing here reaches the live API. The + * replacement HTTP exchange; nothing here reaches the live API. The * assertions are on what actually went on the wire. */ @ExtendWith(MockitoExtension.class) @@ -88,50 +84,21 @@ private void mockAll(int status, @NotNull String responseJson) throws IOExceptio private void mockAll(int status, @NotNull String responseJson, @NotNull String contentType) throws IOException { - ByteArrayOutputStream sentBody = new ByteArrayOutputStream(); - - URL url = mock(URL.class, - withSettings().useConstructor("https://warmup-api.zerobounce.net/api/v1/warmup/seeds")); - HttpURLConnection con = mock(HttpURLConnection.class); - lenient().when(url.openConnection()).thenReturn(con); - lenient().when(con.getResponseCode()).thenReturn(status); - lenient().when(con.getHeaderField("Content-Type")).thenReturn(contentType); - lenient().when(con.getOutputStream()).thenReturn(sentBody); - lenient().when(con.getInputStream()) - .thenAnswer(i -> new ByteArrayInputStream(responseJson.getBytes(StandardCharsets.UTF_8))); - lenient().when(con.getErrorStream()) - .thenAnswer(i -> new ByteArrayInputStream(responseJson.getBytes(StandardCharsets.UTF_8))); - lenient().doAnswer(invocation -> { Recorded record = new Recorded(); - record.url = invocation.getArgument(0); + record.method = invocation.getArgument(0); + record.url = invocation.getArgument(1); + record.headers.put("Accept", "application/json"); + String type = invocation.getArgument(2); + if (type != null) record.headers.put("Content-Type", type); + byte[] body = invocation.getArgument(3); + record.body = body == null ? "" : new String(body, StandardCharsets.UTF_8); + Map headers = invocation.getArgument(4); + if (headers != null) record.headers.putAll(headers); recorded.add(record); - sentBody.reset(); - return url; - }).when(warmup).createUrlFrom(anyString()); - - lenient().doAnswer(invocation -> { - if (!recorded.isEmpty()) { - recorded.get(recorded.size() - 1).method = invocation.getArgument(0); - } - return null; - }).when(con).setRequestMethod(anyString()); - - lenient().doAnswer(invocation -> { - if (!recorded.isEmpty()) { - recorded.get(recorded.size() - 1).headers - .put(invocation.getArgument(0), invocation.getArgument(1)); - } - return null; - }).when(con).setRequestProperty(anyString(), anyString()); - - // The body is written after setRequestMethod, so read it back lazily. - lenient().doAnswer(invocation -> { - if (!recorded.isEmpty()) { - recorded.get(recorded.size() - 1).body = sentBody.toString(StandardCharsets.UTF_8); - } - return null; - }).when(con).disconnect(); + return new SdkHttp.Result(status, contentType, responseJson.getBytes(StandardCharsets.UTF_8)); + }).when(warmup).exchangeHttp(anyString(), anyString(), nullable(String.class), + nullable(byte[].class), nullable(Map.class)); } private Recorded only() { @@ -198,9 +165,6 @@ public void aClientCanBeConstructedAndKeepsItsOwnKey() throws Exception { public void aFailureWithNoBodyKeepsItsStatus() throws IOException { // HttpURLConnection has no error stream for a failed response with no body. mockAll(500, ""); - HttpURLConnection con = (HttpURLConnection) warmup.createUrlFrom("https://x").openConnection(); - recorded.clear(); - when(con.getErrorStream()).thenReturn(null); warmup.getSeedCount(r -> fail("success"), collect); assertEquals(List.of("Empty response from ZeroBounce (HTTP 500)"), errors); assertEquals(500, lastStatus); diff --git a/zero-bounce-sdk/src/test/java/com/zerobounce/ZeroBounceSDKTest.java b/zero-bounce-sdk/src/test/java/com/zerobounce/ZeroBounceSDKTest.java index 00e5f1d..28eb2ae 100644 --- a/zero-bounce-sdk/src/test/java/com/zerobounce/ZeroBounceSDKTest.java +++ b/zero-bounce-sdk/src/test/java/com/zerobounce/ZeroBounceSDKTest.java @@ -3,16 +3,16 @@ import com.google.gson.FieldNamingPolicy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; -import org.apache.http.Header; -import org.apache.http.HttpEntity; -import org.apache.http.StatusLine; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.methods.HttpUriRequest; -import org.apache.http.client.utils.URIBuilder; -import org.apache.http.entity.ContentType; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; +import org.apache.hc.core5.http.Header; +import org.apache.hc.core5.http.HttpEntity; +import org.apache.hc.core5.http.io.HttpClientResponseHandler; +import org.apache.hc.core5.http.ClassicHttpResponse; +import org.apache.hc.client5.http.classic.methods.HttpPost; +import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase; +import org.apache.hc.core5.net.URIBuilder; +import org.apache.hc.core5.http.ContentType; +import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; +import org.apache.hc.client5.http.impl.classic.HttpClients; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.junit.jupiter.api.BeforeEach; @@ -26,9 +26,7 @@ import org.mockito.junit.jupiter.MockitoExtension; import java.io.*; -import java.net.HttpURLConnection; import java.net.URISyntaxException; -import java.net.URL; import java.nio.charset.StandardCharsets; import java.text.SimpleDateFormat; import java.util.*; @@ -1609,20 +1607,20 @@ public void getFile_JsonBodyWithHttp200_InvokesErrorCallback() throws Exception @Test public void getFile_WithOptions_AppendsDownloadTypeAndActivityData() throws Exception { CloseableHttpClient httpClient = mock(CloseableHttpClient.class); - CloseableHttpResponse mockedResponse = mock(CloseableHttpResponse.class); + ClassicHttpResponse mockedResponse = mock(ClassicHttpResponse.class); HttpEntity mockedEntity = mock(HttpEntity.class); - StatusLine statusLine = mock(StatusLine.class); Header header = mock(Header.class); - ArgumentCaptor captor = ArgumentCaptor.forClass(HttpUriRequest.class); + ArgumentCaptor captor = ArgumentCaptor.forClass(HttpUriRequestBase.class); - try (MockedStatic httpClients = Mockito.mockStatic(HttpClients.class)) { - httpClients.when(HttpClients::createDefault).thenReturn(httpClient); - when(httpClient.execute(captor.capture())).thenReturn(mockedResponse); + try (MockedStatic httpClients = HttpClientTestSupport.mockClients()) { + httpClients.when(HttpClients::custom).thenAnswer(invocation -> HttpClientTestSupport.builder(httpClient)); + when(httpClient.execute(captor.capture(), org.mockito.ArgumentMatchers.>any())) + .thenAnswer(invocation -> invocation.>getArgument(1) + .handleResponse(mockedResponse)); when(mockedResponse.getEntity()).thenReturn(mockedEntity); - when(mockedResponse.getStatusLine()).thenReturn(statusLine); when(mockedResponse.getFirstHeader("Content-Type")).thenReturn(header); when(header.getValue()).thenReturn("text/csv"); - when(statusLine.getStatusCode()).thenReturn(200); + when(mockedResponse.getCode()).thenReturn(200); when(mockedEntity.getContent()).thenReturn(new ByteArrayInputStream("x".getBytes(StandardCharsets.UTF_8))); File out = File.createTempFile("zbj-getfile-opts", ".csv"); @@ -1637,7 +1635,7 @@ public void getFile_WithOptions_AppendsDownloadTypeAndActivityData() throws Exce response -> assertEquals(out.getAbsolutePath(), response.getLocalFilePath()), err -> fail(err.toString())); - String uri = captor.getValue().getURI().toString(); + String uri = captor.getValue().getUri().toString(); assertTrue(uri.contains("download_type=combined"), uri); assertTrue(uri.contains("activity_data=true"), uri); assertTrue(uri.contains("file_id=abc-id"), uri); @@ -1647,20 +1645,20 @@ public void getFile_WithOptions_AppendsDownloadTypeAndActivityData() throws Exce @Test public void scoringGetFile_WithOptions_DoesNotAppendActivityData() throws Exception { CloseableHttpClient httpClient = mock(CloseableHttpClient.class); - CloseableHttpResponse mockedResponse = mock(CloseableHttpResponse.class); + ClassicHttpResponse mockedResponse = mock(ClassicHttpResponse.class); HttpEntity mockedEntity = mock(HttpEntity.class); - StatusLine statusLine = mock(StatusLine.class); Header header = mock(Header.class); - ArgumentCaptor captor = ArgumentCaptor.forClass(HttpUriRequest.class); + ArgumentCaptor captor = ArgumentCaptor.forClass(HttpUriRequestBase.class); - try (MockedStatic httpClients = Mockito.mockStatic(HttpClients.class)) { - httpClients.when(HttpClients::createDefault).thenReturn(httpClient); - when(httpClient.execute(captor.capture())).thenReturn(mockedResponse); + try (MockedStatic httpClients = HttpClientTestSupport.mockClients()) { + httpClients.when(HttpClients::custom).thenAnswer(invocation -> HttpClientTestSupport.builder(httpClient)); + when(httpClient.execute(captor.capture(), org.mockito.ArgumentMatchers.>any())) + .thenAnswer(invocation -> invocation.>getArgument(1) + .handleResponse(mockedResponse)); when(mockedResponse.getEntity()).thenReturn(mockedEntity); - when(mockedResponse.getStatusLine()).thenReturn(statusLine); when(mockedResponse.getFirstHeader("Content-Type")).thenReturn(header); when(header.getValue()).thenReturn("text/csv"); - when(statusLine.getStatusCode()).thenReturn(200); + when(mockedResponse.getCode()).thenReturn(200); when(mockedEntity.getContent()).thenReturn(new ByteArrayInputStream("x".getBytes(StandardCharsets.UTF_8))); File out = File.createTempFile("zbj-scoring-opts", ".csv"); @@ -1675,7 +1673,7 @@ public void scoringGetFile_WithOptions_DoesNotAppendActivityData() throws Except response -> assertEquals(out.getAbsolutePath(), response.getLocalFilePath()), err -> fail(err.toString())); - String uri = captor.getValue().getURI().toString(); + String uri = captor.getValue().getUri().toString(); assertTrue(uri.contains("download_type=phase_2"), uri); assertFalse(uri.contains("activity_data"), uri); } @@ -1701,14 +1699,10 @@ private void mockRequest( @NotNull String errorResponse, Runnable block ) throws IOException { - URL url = mock(URL.class, withSettings().useConstructor(urlPath)); - HttpURLConnection con = mock(HttpURLConnection.class); - lenient().when(url.openConnection()).thenReturn(con); - lenient().when(con.getResponseCode()).thenReturn(statusCode); - lenient().when(con.getOutputStream()).thenReturn(new ByteArrayOutputStream()); - lenient().when(con.getInputStream()).thenReturn(new ByteArrayInputStream(response.getBytes())); - lenient().when(con.getErrorStream()).thenReturn(new ByteArrayInputStream(errorResponse.getBytes())); - lenient().doReturn(url).when(zeroBounceSDK).createUrlFrom(anyString()); + lenient().doReturn(new SdkHttp.Result(statusCode, "application/json", + (statusCode > 299 ? errorResponse : response).getBytes(StandardCharsets.UTF_8))) + .when(zeroBounceSDK).exchangeHttp(anyString(), anyString(), nullable(String.class), + nullable(byte[].class), nullable(Map.class)); block.run(); } @@ -1720,9 +1714,8 @@ private void mockMultipartRequest( ThrowingRunnable block ) throws Exception { CloseableHttpClient httpClient = mock(CloseableHttpClient.class); - CloseableHttpResponse mockedResponse = mock(CloseableHttpResponse.class); + ClassicHttpResponse mockedResponse = mock(ClassicHttpResponse.class); HttpEntity mockedEntity = mock(HttpEntity.class); - StatusLine statusLine = mock(StatusLine.class); Header header = mock(Header.class); try ( @@ -1730,15 +1723,16 @@ private void mockMultipartRequest( HttpPost.class, withSettings().useConstructor(urlPath) ); - MockedStatic ignored1 = Mockito.mockStatic(HttpClients.class) + MockedStatic ignored1 = HttpClientTestSupport.mockClients() ) { - lenient().when(HttpClients.createDefault()).thenReturn(httpClient); - lenient().when(httpClient.execute(any())).thenReturn(mockedResponse); + lenient().when(HttpClients.custom()).thenAnswer(invocation -> HttpClientTestSupport.builder(httpClient)); + lenient().when(httpClient.execute(any(), org.mockito.ArgumentMatchers.>any())) + .thenAnswer(invocation -> invocation.>getArgument(1) + .handleResponse(mockedResponse)); lenient().when(mockedResponse.getEntity()).thenReturn(mockedEntity); - lenient().when(mockedResponse.getStatusLine()).thenReturn(statusLine); lenient().when(mockedResponse.getFirstHeader("Content-Type")).thenReturn(header); lenient().when(header.getValue()).thenReturn(contentType); - lenient().when(statusLine.getStatusCode()).thenReturn(statusCode); + lenient().when(mockedResponse.getCode()).thenReturn(statusCode); lenient().when(mockedEntity.getContent()).thenReturn(new ByteArrayInputStream(response.getBytes())); block.run();