Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<sdk.version>` inside `<properties>`.
- `pom.xml`: the JavaFX sample. Its `<version>` is `1.0-SNAPSHOT` and is not the SDK version.
Expand Down Expand Up @@ -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 `<sdk.version>`.
- 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 `<sdk.version>`.
- Match the surrounding style. Do not reformat unrelated code.

## Changelog
Expand Down
14 changes: 14 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
34 changes: 31 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -101,9 +102,36 @@ ZeroBounceSDK.getInstance().initialize("<YOUR_API_KEY>", "<YOUR_API_BASE_URL>");

### 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
<!-- src/main/resources/logback.xml -->
<configuration>
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>

<!-- HttpClient writes API keys and passwords at DEBUG. -->
<logger name="org.apache.hc" level="INFO"/>

<root level="INFO">
<appender-ref ref="CONSOLE"/>
</root>
</configuration>
```

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
Expand Down
34 changes: 12 additions & 22 deletions zero-bounce-sdk/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<mockito.version>5.23.0</mockito.version>
<!-- The HttpCore that httpclient5 itself depends on; httpcore5 and httpcore5-h2 move together. -->
<httpcore5.version>5.4.4</httpcore5.version>
</properties>

<dependencies>
Expand All @@ -54,39 +56,27 @@
<scope>provided</scope>
</dependency>

<!-- Not imported by the SDK: it pins the commons-codec that httpclient 4.5.14
brings in (1.11) to a current release. -->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.22.1</version>
</dependency>

<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.14.0</version>
</dependency>

<!-- The SDK uses Apache HttpClient 4 (org.apache.http) for the multipart
uploads and file downloads, and nothing from HttpClient 5. -->
<!-- All HTTP calls, including multipart uploads, use the supported 5.x APIs. -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.14</version>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
<version>5.6.5</version>
</dependency>

<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.16</version>
<groupId>org.apache.httpcomponents.core5</groupId>
<artifactId>httpcore5</artifactId>
<version>${httpcore5.version}</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.14</version>
<groupId>org.apache.httpcomponents.core5</groupId>
<artifactId>httpcore5-h2</artifactId>
<version>${httpcore5.version}</version>
</dependency>

<!-- https://mvnrepository.com/artifact/junit/junit -->
Expand Down
69 changes: 19 additions & 50 deletions zero-bounce-sdk/src/main/java/com/zerobounce/Priority3Api.java
Original file line number Diff line number Diff line change
@@ -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;

Expand Down Expand Up @@ -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)));
Expand Down Expand Up @@ -290,23 +281,22 @@ 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<String, String> entry : fields.entrySet()) {
builder.addPart(entry.getKey(), new StringBody(entry.getValue(), ContentType.TEXT_PLAIN));
}
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);
}

Expand All @@ -322,23 +312,22 @@ 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<String, String> entry : fields.entrySet()) {
builder.addPart(entry.getKey(), new StringBody(entry.getValue(), ContentType.TEXT_PLAIN));
}
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);
}

Expand Down Expand Up @@ -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()));
}
}
Loading
Loading