Perform better validation on Mandrill responses

This commit is contained in:
Colin McDonald 2016-07-23 18:46:02 -04:00
parent 70b4f079c1
commit 1b1e1bb3e9
3 changed files with 22 additions and 12 deletions

View File

@ -4,10 +4,13 @@ import com.google.common.net.MediaType;
import com.mongodb.async.SingleResultCallback;
import io.vertx.core.http.HttpClient;
import io.vertx.core.http.HttpHeaders;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import lombok.experimental.UtilityClass;
import net.frozenorb.apiv3.APIv3;
import java.io.IOException;
@UtilityClass
public class MandrillUtils {
@ -15,16 +18,28 @@ public class MandrillUtils {
private static final HttpClient httpClient = APIv3.getVertxInstance().createHttpClient();
public static void sendEmail(JsonObject message, SingleResultCallback<Void> callback) {
JsonObject body = new JsonObject()
JsonObject requestBody = new JsonObject()
.put("key", mandrillApiKey)
.put("message", message);
httpClient.post("mandrillapp.com", "/api/1.0/messages/send.json", (response) -> {
response.bodyHandler((ignored) -> callback.onResult(null, null));
response.bodyHandler((responseBody) -> {
try {
JsonArray bodyJson = new JsonArray(responseBody.toString());
JsonObject emailJson = bodyJson.getJsonObject(0);
String emailStatus = emailJson.getString("status");
if (emailStatus.equals("rejected") || emailStatus.equals("invalid")) {
callback.onResult(null, new IOException("Illegal email status while reading Mandrill response: " + emailStatus + " (" + emailJson.encode() + ")"));
} else {
callback.onResult(null, null);
}
} catch (Exception ex) {
callback.onResult(null, new IOException("Failed to process Mandrill response: " + responseBody, ex));
}
});
response.exceptionHandler((error) -> callback.onResult(null, error));
})
.putHeader(HttpHeaders.CONTENT_TYPE, MediaType.JSON_UTF_8.toString())
.end(body.encode());
}).putHeader(HttpHeaders.CONTENT_TYPE, MediaType.JSON_UTF_8.toString()).end(requestBody.encode());
}
}

View File

@ -62,9 +62,7 @@ public class MaxMindUtils {
future.fail(error);
}
});
})
.putHeader("Authorization", authHeader)
.end();
}).putHeader("Authorization", authHeader).end();
}).setHandler((result) -> {
if (result.failed()) {
callback.onResult(null, result.cause());

View File

@ -36,10 +36,7 @@ public class ZangUtils {
});
response.exceptionHandler((error) -> callback.onResult(null, error));
})
.putHeader("Authorization", authHeader)
.putHeader(HttpHeaders.CONTENT_TYPE, MediaType.JSON_UTF_8.toString())
.end("To=" + to + "&From=339-337-5300&Body=" + messageBody);
}).putHeader("Authorization", authHeader).putHeader(HttpHeaders.CONTENT_TYPE, MediaType.JSON_UTF_8.toString()).end("To=" + to + "&From=339-337-5300&Body=" + messageBody);
}
public static void getCarrierInfo(String phoneNumber, SingleResultCallback<ZangResult> callback) {