Skip to content

Conversation

@vitalii-t
Copy link
Collaborator

@vitalii-t vitalii-t commented Sep 2, 2025

Motivation

Next steps implementing Mailtrap API - Suppressions

Changes

  • Added the Suppressions interface and implementation
  • Added request and response models
  • Covered with unit tests
  • Added an example class

Summary by CodeRabbit

  • New Features

    • Added Suppressions support to the Email Sending API, enabling you to search suppressions by email and delete specific entries.
    • Responses now include suppression type and sending stream details.
  • Documentation

    • Added a Java example demonstrating how to search for suppressions and delete one.
  • Tests

    • Introduced unit tests and fixtures covering suppression search and deletion workflows.

@coderabbitai
Copy link

coderabbitai bot commented Sep 2, 2025

Walkthrough

Introduces a new Suppressions API: interface, implementation, models, client wiring, example usage, and tests. MailtrapEmailSendingApi now exposes suppressions(), wired via MailtrapClientFactory. Supports searching suppressions by email and deleting a suppression by ID. Adds DTOs/enums for JSON mapping and test fixtures.

Changes

Cohort / File(s) Summary of changes
Examples: Suppressions usage
examples/java/io/mailtrap/examples/suppressions/Suppressions.java
New Java example demonstrating search and delete suppression calls via Mailtrap client.
API: Suppressions contract & impl
src/main/java/io/mailtrap/api/suppressions/Suppressions.java, src/main/java/io/mailtrap/api/suppressions/SuppressionsImpl.java
New interface with search and delete methods; implementation performs GET/DELETE against /api/accounts/{accountId}/suppressions, URL-encodes IDs, maps to response DTOs.
Client wiring
src/main/java/io/mailtrap/client/api/MailtrapEmailSendingApi.java, src/main/java/io/mailtrap/factory/MailtrapClientFactory.java
Adds Suppressions dependency, exposes suppressions() getter; factory now constructs and injects SuppressionsImpl into MailtrapEmailSendingApi.
Models: Suppressions DTOs/enums
src/main/java/io/mailtrap/model/response/suppressions/SuppressionsResponse.java, src/main/java/io/mailtrap/model/response/suppressions/SendingStream.java, src/main/java/io/mailtrap/model/response/suppressions/SuppressionType.java
New DTO and enums with Jackson annotations for (de)serialization of suppression records, including sending stream and suppression type.
Tests: API and fixtures
src/test/java/io/mailtrap/api/suppressions/SuppressionsImplTest.java, src/test/java/io/mailtrap/testutils/BaseTest.java, src/test/resources/api/suppressions/searchSuppressions.json, src/test/resources/api/suppressions/deleteSuppression.json
Adds unit tests for search/delete; updates BaseTest constants for suppression IDs; introduces JSON fixtures for mocked responses.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant App as Application
  participant Factory as MailtrapClientFactory
  participant Client as MailtrapEmailSendingApi
  participant Supp as SuppressionsImpl
  participant HTTP as HTTP API

  App->>Factory: createMailtrapClient(config)
  Factory->>Client: new MailtrapEmailSendingApi(emails, domains, suppressions)

  App->>Client: suppressions()
  App->>Supp: search(accountId, email)
  Supp->>HTTP: GET /api/accounts/{id}/suppressions?email={email}
  HTTP-->>Supp: 200 [SuppressionsResponse...]
  Supp-->>App: List<SuppressionsResponse>

  App->>Supp: deleteSuppression(accountId, suppressionId)
  Supp->>HTTP: DELETE /api/accounts/{id}/suppressions/{encodedId}
  HTTP-->>Supp: 200 SuppressionsResponse
  Supp-->>App: SuppressionsResponse
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Suggested reviewers

  • mklocek
  • vittorius

Poem

A hop and a bop through suppressions I go,
With ears tall and code all in tidy flow.
I search, I delete—IDs neatly encoded,
Streams BULK or TRANSACTIONAL duly noted.
Carrot in paw, I test with delight—
Green bars twinkle like stars at night. 🌟🐇

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feature/suppressions

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (15)
src/test/resources/api/suppressions/deleteSuppression.json (1)

1-16: Fixture looks good; tiny evergreen tweak optional

Consider using a past timestamp (e.g., 2024-01-01T00:00:00Z) to avoid “future” dates when reading logs; no impact on parsing.

src/test/java/io/mailtrap/testutils/BaseTest.java (1)

24-26: Use a deterministic charset and avoid form-encoding for path segments

  • Prefer StandardCharsets.UTF_8 over Charset.defaultCharset() for consistent results.
  • Since suppressionId is a UUID used in a path segment, encoding isn’t necessary; if you do encode, prefer a path-segment encoder over URLEncoder (which is for x-www-form-urlencoded). For this test it’s harmless, but worth aligning.

Apply within-range change:

-    protected final String suppressionIdEncoded = URLEncoder.encode(suppressionId, Charset.defaultCharset());
+    protected final String suppressionIdEncoded = URLEncoder.encode(suppressionId, java.nio.charset.StandardCharsets.UTF_8);

Also consider updating similar usages for emailEncoded/contactUUIDEncoded above to StandardCharsets.UTF_8.

src/main/java/io/mailtrap/model/response/suppressions/SendingStream.java (1)

22-30: Harden fromValue against null/whitespace and be explicit about @JsonCreator mode

Avoid NPE on null JSON and accept surrounding whitespace.

-  @JsonCreator
-  public static SendingStream fromValue(String value) {
-    for (SendingStream type : SendingStream.values()) {
-      if (type.value.equalsIgnoreCase(value)) {
-        return type;
-      }
-    }
-    throw new IllegalArgumentException("Unknown value: " + value);
-  }
+  @JsonCreator(mode = JsonCreator.Mode.DELEGATING)
+  public static SendingStream fromValue(String value) {
+    if (value == null || value.isBlank()) {
+      throw new IllegalArgumentException("Unknown value: " + value);
+    }
+    final String v = value.trim();
+    for (SendingStream type : SendingStream.values()) {
+      if (type.value.equalsIgnoreCase(v)) {
+        return type;
+      }
+    }
+    throw new IllegalArgumentException("Unknown value: " + value);
+  }
src/main/java/io/mailtrap/model/response/suppressions/SuppressionType.java (1)

23-31: Same robustness improvements as SendingStream.fromValue

Mirror null/whitespace handling and explicit creator mode for consistency.

-  @JsonCreator
-  public static SuppressionType fromValue(String value) {
-    for (SuppressionType type : SuppressionType.values()) {
-      if (type.value.equalsIgnoreCase(value)) {
-        return type;
-      }
-    }
-    throw new IllegalArgumentException("Unknown value: " + value);
-  }
+  @JsonCreator(mode = JsonCreator.Mode.DELEGATING)
+  public static SuppressionType fromValue(String value) {
+    if (value == null || value.isBlank()) {
+      throw new IllegalArgumentException("Unknown value: " + value);
+    }
+    final String v = value.trim();
+    for (SuppressionType type : SuppressionType.values()) {
+      if (type.value.equalsIgnoreCase(v)) {
+        return type;
+      }
+    }
+    throw new IllegalArgumentException("Unknown value: " + value);
+  }
src/test/resources/api/suppressions/searchSuppressions.json (1)

1-18: Fixture aligns with enums; optional timestamp nit

Values map cleanly to SuppressionType.SPAM_COMPLAINT and SendingStream.BULK. Consider past timestamps for evergreen readability as noted on the delete fixture.

examples/java/io/mailtrap/examples/suppressions/Suppressions.java (3)

8-15: Avoid hardcoding secrets; read token from an env var

Keeps examples safe while still runnable.

-  private static final String TOKEN = "<YOUR MAILTRAP TOKEN>";
+  private static final String TOKEN =
+      System.getenv().getOrDefault("MAILTRAP_TOKEN", "<YOUR MAILTRAP TOKEN>");

6-6: Rename example class to avoid name collision with API interface

Prevents import confusion when examples expand.

-public class Suppressions {
+public class SuppressionsExample {

24-29: Guard destructive delete in example

Make deletion explicit to avoid accidental data changes when copy-running.

-    if (!searchResponse.isEmpty()) {
+    if (Boolean.parseBoolean(System.getenv().getOrDefault("DELETE_SUPPRESSION", "false"))
+        && !searchResponse.isEmpty()) {
src/main/java/io/mailtrap/api/suppressions/Suppressions.java (2)

9-17: Clarify nullability/behavior of email in Javadoc

Implementation accepts null (omits the param). Make the contract explicit.

-  /**
-   * List and search suppressions by email. The endpoint returns up to 1000 suppressions per request.
-   *
-   * @param accountId - unique account ID
-   * @param email     - search suppressions for this email
-   * @return a list of suppressions
-   */
+  /**
+   * List and search suppressions. The endpoint returns up to 1000 suppressions per request.
+   *
+   * @param accountId - unique account ID
+   * @param email     - optional; if null, returns all suppressions for the account; if provided, filters by email
+   * @return a list of suppressions
+   */

16-16: Optional overload for discoverability

Consider an overload List<SuppressionsResponse> search(long accountId) to make “list all” explicit, delegating to the existing method with null.

src/test/java/io/mailtrap/api/suppressions/SuppressionsImplTest.java (1)

21-45: Add a test for special-character encoding and for “list all”

To future-proof encoding and optional email behavior, add:

  • a test with an email containing “+” or spaces
  • a test with email = null (no query param expected)

Example (non-diff, new tests):

@Test
void test_search_withSpecialCharsEmail() {
  String trickyEmail = "first.last+tag@mailtrap.io";
  TestHttpClient httpClient = new TestHttpClient(List.of(
      DataMock.build(
          Constants.GENERAL_HOST + "/api/accounts/" + accountId + "/suppressions",
          "GET", null, "api/suppressions/searchSuppressions.json",
          Map.of("email", trickyEmail)
      )
  ));
  // build api with httpClient and assert like in test_search
}

@Test
void test_search_listAll_whenEmailNull() {
  TestHttpClient httpClient = new TestHttpClient(List.of(
      DataMock.build(
          Constants.GENERAL_HOST + "/api/accounts/" + accountId + "/suppressions",
          "GET", null, "api/suppressions/searchSuppressions.json"
      )
  ));
  // build api with httpClient and assert not empty, etc.
}

Also consider standardizing encoding on UTF‑8 in both BaseTest and SuppressionsImpl to avoid locale-specific defaults.

src/main/java/io/mailtrap/api/suppressions/SuppressionsImpl.java (3)

36-36: Validate suppressionId early.

Fail fast on null/blank IDs to avoid confusing 4xx from the server.

   @Override
   public SuppressionsResponse deleteSuppression(long accountId, String suppressionId) {
+    if (suppressionId == null || suppressionId.isBlank()) {
+      throw new IllegalArgumentException("suppressionId must not be null or blank");
+    }
     return

25-25: Don’t send empty email query param.

Trim and drop when blank.

-    var queryParams = RequestData.buildQueryParams(entry("email", Optional.ofNullable(email)));
+    var queryParams = RequestData.buildQueryParams(
+        entry("email", Optional.ofNullable(email).map(String::trim).filter(s -> !s.isEmpty()))
+    );

29-29: Style: avoid concatenation inside String.format.

Clearer and avoids accidental double slashes.

-            String.format(apiHost + "/api/accounts/%d/suppressions", accountId),
+            String.format("%s/api/accounts/%d/suppressions", apiHost, accountId),
src/main/java/io/mailtrap/model/response/suppressions/SuppressionsResponse.java (1)

3-6: Harden JSON mapping: ignore unknowns and omit nulls.

More resilient to backend additions and cleaner (re-)serialization.

 import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonInclude;
 import lombok.Data;

@@
-@Data
+@JsonIgnoreProperties(ignoreUnknown = true)
+@JsonInclude(JsonInclude.Include.NON_NULL)
+@Data
 public class SuppressionsResponse {

Also applies to: 8-9

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 9dfd60d and de8564c.

📒 Files selected for processing (12)
  • examples/java/io/mailtrap/examples/suppressions/Suppressions.java (1 hunks)
  • src/main/java/io/mailtrap/api/suppressions/Suppressions.java (1 hunks)
  • src/main/java/io/mailtrap/api/suppressions/SuppressionsImpl.java (1 hunks)
  • src/main/java/io/mailtrap/client/api/MailtrapEmailSendingApi.java (2 hunks)
  • src/main/java/io/mailtrap/factory/MailtrapClientFactory.java (2 hunks)
  • src/main/java/io/mailtrap/model/response/suppressions/SendingStream.java (1 hunks)
  • src/main/java/io/mailtrap/model/response/suppressions/SuppressionType.java (1 hunks)
  • src/main/java/io/mailtrap/model/response/suppressions/SuppressionsResponse.java (1 hunks)
  • src/test/java/io/mailtrap/api/suppressions/SuppressionsImplTest.java (1 hunks)
  • src/test/java/io/mailtrap/testutils/BaseTest.java (1 hunks)
  • src/test/resources/api/suppressions/deleteSuppression.json (1 hunks)
  • src/test/resources/api/suppressions/searchSuppressions.json (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (6)
examples/java/io/mailtrap/examples/suppressions/Suppressions.java (1)
src/main/java/io/mailtrap/factory/MailtrapClientFactory.java (1)
  • MailtrapClientFactory (31-116)
src/main/java/io/mailtrap/api/suppressions/Suppressions.java (1)
examples/java/io/mailtrap/examples/suppressions/Suppressions.java (1)
  • Suppressions (6-31)
src/main/java/io/mailtrap/api/suppressions/SuppressionsImpl.java (2)
src/main/java/io/mailtrap/Constants.java (1)
  • Constants (6-15)
src/main/java/io/mailtrap/api/apiresource/ApiResource.java (1)
  • ApiResource (10-34)
src/test/java/io/mailtrap/api/suppressions/SuppressionsImplTest.java (4)
src/main/java/io/mailtrap/Constants.java (1)
  • Constants (6-15)
src/main/java/io/mailtrap/factory/MailtrapClientFactory.java (1)
  • MailtrapClientFactory (31-116)
src/test/java/io/mailtrap/testutils/BaseTest.java (1)
  • BaseTest (6-26)
src/test/java/io/mailtrap/testutils/TestHttpClient.java (1)
  • TestHttpClient (19-160)
src/main/java/io/mailtrap/factory/MailtrapClientFactory.java (1)
src/main/java/io/mailtrap/api/suppressions/SuppressionsImpl.java (1)
  • SuppressionsImpl (16-44)
src/main/java/io/mailtrap/client/api/MailtrapEmailSendingApi.java (1)
examples/java/io/mailtrap/examples/suppressions/Suppressions.java (1)
  • Suppressions (6-31)
🔇 Additional comments (6)
src/main/java/io/mailtrap/client/api/MailtrapEmailSendingApi.java (2)

17-20: LGTM: clean wiring and fluent accessor for suppressions()

Field addition aligns with existing Lombok patterns; accessor shape is consistent with emails() and domains().


15-20: No legacy usages found – constructor updated correctly. Only instantiation in MailtrapClientFactory (line 79) already uses all three parameters (emails, domains, suppressions).

src/main/java/io/mailtrap/factory/MailtrapClientFactory.java (1)

74-80: LGTM: Suppressions wired into Sending API

Instantiation and injection look correct; host selection is handled in SuppressionsImpl.

src/test/java/io/mailtrap/api/suppressions/SuppressionsImplTest.java (2)

47-56: LGTM: search flow covered with field-level assertions

Good coverage of id/email/stream/type; mock query param matching protects against regressions.


58-67: LGTM: delete flow verifies ID round‑trip and enum mapping

Nicely validates path handling and response mapping.

src/main/java/io/mailtrap/api/suppressions/SuppressionsImpl.java (1)

18-21: No change required: SuppressionsImpl host is correct SuppressionsImpl and its tests consistently use Constants.GENERAL_HOST like other non-email APIs; centralizing host configuration remains an optional improvement.

Comment on lines +9 to +11
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.List;
Copy link

@coderabbitai coderabbitai bot Sep 2, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Encode path segment correctly and use UTF-8 (URLEncoder here is incorrect).

URLEncoder is for form/query encoding and will turn spaces into '+', which is wrong for path segments. Also avoid platform-default charset.

Apply:

-import java.nio.charset.Charset;
+import java.nio.charset.StandardCharsets;
-            String.format(apiHost + "/api/accounts/%d/suppressions/%s", accountId, URLEncoder.encode(suppressionId, Charset.defaultCharset())),
+            String.format(apiHost + "/api/accounts/%d/suppressions/%s", accountId, encodePathSegment(suppressionId)),

Add this helper inside the class:

private static String encodePathSegment(String segment) {
  return URLEncoder.encode(segment, StandardCharsets.UTF_8).replace("+", "%20");
}

Also applies to: 39-39

🤖 Prompt for AI Agents
In src/main/java/io/mailtrap/api/suppressions/SuppressionsImpl.java around lines
9-11 (and also line 39), the code imports and uses URLEncoder with the
platform-default Charset which is incorrect for path segments and may produce
'+' for spaces; replace usages with a dedicated helper that URL-encodes using
StandardCharsets.UTF_8 and converts '+' to '%20', and add that helper as a
private static method inside the class (named e.g. encodePathSegment) so all
path segment encodings call it instead of raw URLEncoder calls.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@vitalii-t Out of curiosity, how valid is this AI suggestion for modern Java?

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@vittorius, It is a valid workaround, but since the suppressionId here is a UUID, encoding is not necessary and is done "just in case."
In general, this AI bot suggests valid things, especially in the "nitpicks" section. I collect some of them, and will edit for all APIs - like adding @JsonIgnoreProperties(ignoreUnknown = true) for the response classes, null checks for enums, and so on - some polishing stuff

Comment on lines +9 to +11
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.List;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@vitalii-t Out of curiosity, how valid is this AI suggestion for modern Java?

@vitalii-t vitalii-t merged commit b3ae7da into main Sep 4, 2025
2 checks passed
@vitalii-t vitalii-t deleted the feature/suppressions branch September 4, 2025 19:42
@vitalii-t vitalii-t mentioned this pull request Sep 4, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants