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
20 changes: 4 additions & 16 deletions src/main/java/com/mailosaur/Files.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
* Operations for downloading the raw content associated with a message — file attachments,
Expand Down Expand Up @@ -58,7 +56,7 @@ public byte[] getEmail(String messageId) throws MailosaurException, IOException
public byte[] getPreview(String previewId) throws MailosaurException, IOException {
int timeout = 120000;
int pollCount = 0;
long startTime = new Date().getTime();
long startTime = client.clock.currentTimeMillis();

while(true) {
HttpResponse response = client.request("GET", "api/files/screenshots/" + previewId);
Expand All @@ -69,26 +67,16 @@ public byte[] getPreview(String previewId) throws MailosaurException, IOExceptio
return stream.toByteArray();
}

List<String> headerValues = response.getHeaders().getHeaderStringValues("x-ms-delay");
String[] delayStrings = (headerValues.size() == 0 ? "1000" : headerValues.get(0)).split(",");
int delayPattern[] = new int[delayStrings.length];
for (int i = 0; i < delayStrings.length; i++) {
delayPattern[i] = Integer.parseInt(delayStrings[i].trim());
}

int delay = pollCount >= delayPattern.length ?
delayPattern[delayPattern.length - 1] :
delayPattern[pollCount];

int delay = MailosaurClient.pollDelay(response.getHeaders().getFirstHeaderStringValue("x-ms-delay"), pollCount);
pollCount++;

// Stop if timeout will be exceeded
if ((new Date().getTime() - startTime) + delay > timeout) {
if ((client.clock.currentTimeMillis() - startTime) + delay > timeout) {
throw new MailosaurException("An email preview was not generated in time. The email client may not be available, or the preview ID ["+previewId+"] may be incorrect.", "preview_timeout");
}

try {
Thread.sleep(delay);
client.sleeper.sleep(delay);
} catch (InterruptedException e) {
e.printStackTrace();
}
Expand Down
53 changes: 42 additions & 11 deletions src/main/java/com/mailosaur/MailosaurClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,16 @@
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Pattern;

import com.google.api.client.http.*;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.http.json.JsonHttpContent;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.JsonObjectParser;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.client.util.Clock;
import com.google.api.client.util.Sleeper;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
Expand All @@ -30,16 +33,15 @@ public class MailosaurClient {
final String VERSION = "9.0.0";
final String API_KEY;
final String BASE_URL;
final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
final HttpTransport HTTP_TRANSPORT;
final JsonFactory JSON_FACTORY = new GsonFactory();

final HttpRequestFactory requestFactory =
HTTP_TRANSPORT.createRequestFactory(new HttpRequestInitializer() {
public void initialize(HttpRequest request) {
request.setParser(new JsonObjectParser(JSON_FACTORY));
}
});

final HttpRequestFactory requestFactory;

private static final Pattern ASCII_DIGITS = Pattern.compile("[0-9]+");

Sleeper sleeper = Sleeper.DEFAULT;
Clock clock = Clock.SYSTEM;

/**
* Initializes an instance of the Mailosaur client using the
* MAILOSAUR_API_KEY environment variable.
Expand All @@ -66,9 +68,19 @@ public MailosaurClient(String apiKey) {
* @param baseUrl Alternative base URL of the Mailosaur service.
*/
public MailosaurClient(String apiKey, String baseUrl) {
this(apiKey, baseUrl, new NetHttpTransport());
}

MailosaurClient(String apiKey, String baseUrl, HttpTransport transport) {
API_KEY = apiKey;
BASE_URL = baseUrl != null ? baseUrl : "https://mailosaur.com/";

HTTP_TRANSPORT = transport;
requestFactory = transport.createRequestFactory(new HttpRequestInitializer() {
public void initialize(HttpRequest request) {
request.setParser(new JsonObjectParser(JSON_FACTORY));
}
});

this.analysis = new Analysis(this);
this.files = new Files(this);
this.messages = new Messages(this);
Expand All @@ -87,7 +99,26 @@ private static String resolveApiKeyFromEnv() throws MailosaurException {
}
return apiKey;
}


static int pollDelay(String header, int pollCount) {
if (header == null) {
return 1000;
}

String[] entries = header.split(",", -1);
String entry = entries[Math.min(pollCount, entries.length - 1)].trim();

if (!ASCII_DIGITS.matcher(entry).matches()) {
return 1000;
}

try {
return Integer.parseInt(entry);
} catch (NumberFormatException e) {
return 1000;
}
}

/**
* Operations for analyzing email content and deliverability, including spam scoring.
*/
Expand Down
20 changes: 4 additions & 16 deletions src/main/java/com/mailosaur/Messages.java
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
package com.mailosaur;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.google.api.client.http.HttpResponse;
import com.google.gson.Gson;
Expand Down Expand Up @@ -315,7 +313,7 @@ public MessageListResult search(MessageSearchParams params, SearchCriteria crite
}

int pollCount = 0;
long startTime = new Date().getTime();
long startTime = client.clock.currentTimeMillis();

while(true) {
HttpResponse response = client.request("POST", "api/messages/search", criteria, query);
Expand All @@ -325,21 +323,11 @@ public MessageListResult search(MessageSearchParams params, SearchCriteria crite
return result;
}

List<String> headerValues = response.getHeaders().getHeaderStringValues("x-ms-delay");
String[] delayStrings = (headerValues.size() == 0 ? "1000" : headerValues.get(0)).split(",");
int delayPattern[] = new int[delayStrings.length];
for (int i = 0; i < delayStrings.length; i++) {
delayPattern[i] = Integer.parseInt(delayStrings[i].trim());
}

int delay = pollCount >= delayPattern.length ?
delayPattern[delayPattern.length - 1] :
delayPattern[pollCount];

int delay = MailosaurClient.pollDelay(response.getHeaders().getFirstHeaderStringValue("x-ms-delay"), pollCount);
pollCount++;

// Stop if timeout will be exceeded
if ((new Date().getTime() - startTime) + delay > params.timeout()) {
if ((client.clock.currentTimeMillis() - startTime) + delay > params.timeout()) {
if (params.errorOnTimeout() == false) {
return result;
}
Expand All @@ -349,7 +337,7 @@ public MessageListResult search(MessageSearchParams params, SearchCriteria crite
}

try {
Thread.sleep(delay);
client.sleeper.sleep(delay);
} catch (InterruptedException e) {
e.printStackTrace();
}
Expand Down
190 changes: 190 additions & 0 deletions src/test/java/com/mailosaur/PollingTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
package com.mailosaur;

import com.google.api.client.http.LowLevelHttpRequest;
import com.google.api.client.http.LowLevelHttpResponse;
import com.google.api.client.testing.http.MockHttpTransport;
import com.google.api.client.testing.http.MockLowLevelHttpRequest;
import com.google.api.client.testing.http.MockLowLevelHttpResponse;
import com.mailosaur.models.MessageListResult;
import com.mailosaur.models.MessageSearchParams;
import com.mailosaur.models.MessageSummary;
import com.mailosaur.models.SearchCriteria;
import org.junit.Test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import static org.junit.Assert.*;

public class PollingTest {
private static final int MAX_REQUESTS = 20;
private static final byte[] IMAGE = { (byte) 0x89, 'P', 'N', 'G' };
private static final SearchCriteria CRITERIA = new SearchCriteria().withSentTo("test@abcd1234.mailosaur.net");

private final List<Long> waits = new ArrayList<>();
private long now;
private int requests;

private interface Reply {
MockLowLevelHttpResponse create();
}

@Test
public void searchWaits1000MsWhenThereIsNoDelayHeader() throws IOException, MailosaurException {
MessageListResult result = stubClient(empty(null), match(null)).messages().search(params(60000), CRITERIA);

assertEquals(Arrays.asList(1000L), waits);
assertEquals(2, requests);
assertEquals(Arrays.asList("match-id"), ids(result));
}

@Test
public void searchUsesEachListedDelayInTurnThenRepeatsTheLast() throws IOException, MailosaurException {
String delay = "1000,2000,3000";
MessageListResult result = stubClient(empty(delay), empty(delay), empty(delay), empty(delay), match(delay))
.messages().search(params(60000), CRITERIA);

assertEquals(Arrays.asList(1000L, 2000L, 3000L, 3000L), waits);
assertEquals(5, requests);
assertEquals(Arrays.asList("match-id"), ids(result));
}

@Test
public void searchTreatsADelayThatIsNotANumberAs1000Ms() throws IOException, MailosaurException {
String delay = "abc,,+500,-500,1500";
MessageListResult result = stubClient(empty(delay), empty(delay), empty(delay), empty(delay), empty(delay), match(delay))
.messages().search(params(60000), CRITERIA);

assertEquals(Arrays.asList(1000L, 1000L, 1000L, 1000L, 1500L), waits);
assertEquals(6, requests);
assertEquals(Arrays.asList("match-id"), ids(result));
}

@Test
public void searchReadsTheDelayFromTheLatestResponse() throws IOException, MailosaurException {
MessageListResult result = stubClient(empty("500"), empty("1500"), match(null))
.messages().search(params(60000), CRITERIA);

assertEquals(Arrays.asList(500L, 1500L), waits);
assertEquals(3, requests);
assertEquals(Arrays.asList("match-id"), ids(result));
}

@Test
public void searchThrowsATimeoutErrorWhenNothingMatchesInTime() {
// 700 + 1500 would pass the 2000 ms timeout, so polling stops. Counting elapsed
// time in whole seconds, or checking only after the timeout has passed, would wait again.
final MailosaurClient client = stubClient(empty("700,1500"));

MailosaurException error = assertThrows(MailosaurException.class,
() -> client.messages().search(params(2000), CRITERIA));

assertEquals(Arrays.asList(700L), waits);
assertEquals(2, requests);
assertEquals("search_timeout", error.errorType());
}

@Test
public void previewWaits1000MsWhenThereIsNoDelayHeader() throws IOException, MailosaurException {
byte[] bytes = stubClient(pending(null), ready(null)).files().getPreview("preview-id");

assertEquals(Arrays.asList(1000L), waits);
assertEquals(2, requests);
assertArrayEquals(IMAGE, bytes);
}

@Test
public void previewUsesEachListedDelayInTurnThenRepeatsTheLast() throws IOException, MailosaurException {
String delay = "1000,2000,3000";
byte[] bytes = stubClient(pending(delay), pending(delay), pending(delay), pending(delay), ready(delay))
.files().getPreview("preview-id");

assertEquals(Arrays.asList(1000L, 2000L, 3000L, 3000L), waits);
assertEquals(5, requests);
assertArrayEquals(IMAGE, bytes);
}

@Test
public void previewReadsTheDelayFromTheLatestResponse() throws IOException, MailosaurException {
byte[] bytes = stubClient(pending("500"), pending("1500"), ready(null)).files().getPreview("preview-id");

assertEquals(Arrays.asList(500L, 1500L), waits);
assertEquals(3, requests);
assertArrayEquals(IMAGE, bytes);
}

@Test
public void previewThrowsATimeoutErrorWhenThePreviewIsNotReadyInTime() {
// 60700 + 59500 would pass the fixed 120 s preview timeout, so polling stops. Counting elapsed
// time in whole seconds, or checking only after the timeout has passed, would wait again.
final MailosaurClient client = stubClient(pending("60700,59500"));

MailosaurException error = assertThrows(MailosaurException.class,
() -> client.files().getPreview("preview-id"));

assertEquals(Arrays.asList(60700L), waits);
assertEquals(2, requests);
assertEquals("preview_timeout", error.errorType());
}

private MailosaurClient stubClient(final Reply... replies) {
MockHttpTransport transport = new MockHttpTransport() {
@Override
public LowLevelHttpRequest buildRequest(String method, String url) {
return new MockLowLevelHttpRequest(url) {
@Override
public LowLevelHttpResponse execute() {
requests++;
if (requests > MAX_REQUESTS) {
fail("The client sent more than " + MAX_REQUESTS + " requests, so polling never stopped");
}
return replies[Math.min(requests, replies.length) - 1].create();
}
};
}
};

MailosaurClient client = new MailosaurClient("placeholder-api-key", null, transport);
client.sleeper = millis -> {
waits.add(millis);
now += millis;
};
client.clock = () -> now;
return client;
}

private static List<String> ids(MessageListResult result) {
return result.items().stream().map(MessageSummary::id).collect(Collectors.toList());
}

private static MessageSearchParams params(int timeout) {
return new MessageSearchParams().withServer("abcd1234").withTimeout(timeout);
}

private static Reply empty(final String delay) {
return () -> withDelay(json("{\"items\":[]}"), delay);
}

private static Reply match(final String delay) {
return () -> withDelay(json("{\"items\":[{\"id\":\"match-id\"}]}"), delay);
}

private static Reply pending(final String delay) {
return () -> withDelay(new MockLowLevelHttpResponse().setStatusCode(202), delay);
}

private static Reply ready(final String delay) {
return () -> withDelay(new MockLowLevelHttpResponse().setContentType("image/png").setContent(IMAGE), delay);
}

private static MockLowLevelHttpResponse json(String body) {
return new MockLowLevelHttpResponse().setContentType("application/json; charset=UTF-8").setContent(body);
}

private static MockLowLevelHttpResponse withDelay(MockLowLevelHttpResponse response, String delay) {
return delay == null ? response : response.addHeader("x-ms-delay", delay);
}
}
Loading