Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Initial put

  • Loading branch information...
commit 9ab0cc51d3de56929c31573126732069201857cd 0 parents
k-shunji authored
Showing with 1,001 additions and 0 deletions.
  1. +3 −0  .gitignore
  2. +19 −0 LICENSE.txt
  3. +11 −0 README.md
  4. +52 −0 pom.xml
  5. +189 −0 src/main/java/jp/co/flect/sendgrid/SendGridClient.java
  6. +48 −0 src/main/java/jp/co/flect/sendgrid/SendGridException.java
  7. +13 −0 src/main/java/jp/co/flect/sendgrid/event/Event.java
  8. +11 −0 src/main/java/jp/co/flect/sendgrid/json/Json.java
  9. +24 −0 src/main/java/jp/co/flect/sendgrid/json/JsonByGson.java
  10. +46 −0 src/main/java/jp/co/flect/sendgrid/json/JsonUtils.java
  11. +23 −0 src/main/java/jp/co/flect/sendgrid/model/AbstractGetRequest.java
  12. +87 −0 src/main/java/jp/co/flect/sendgrid/model/AbstractModel.java
  13. +82 −0 src/main/java/jp/co/flect/sendgrid/model/AbstractRequest.java
  14. +4 −0 src/main/java/jp/co/flect/sendgrid/model/App.java
  15. +22 −0 src/main/java/jp/co/flect/sendgrid/model/BasicGetRequest.java
  16. +12 −0 src/main/java/jp/co/flect/sendgrid/model/Block.java
  17. +15 −0 src/main/java/jp/co/flect/sendgrid/model/Bounce.java
  18. +22 −0 src/main/java/jp/co/flect/sendgrid/model/InvalidEmail.java
  19. +4 −0 src/main/java/jp/co/flect/sendgrid/model/Profile.java
  20. +11 −0 src/main/java/jp/co/flect/sendgrid/model/SpamReport.java
  21. +11 −0 src/main/java/jp/co/flect/sendgrid/model/Statistic.java
  22. +14 −0 src/main/java/jp/co/flect/sendgrid/model/Unsubscribe.java
  23. +4 −0 src/main/java/jp/co/flect/sendgrid/model/WebMail.java
  24. +103 −0 src/main/java/jp/co/flect/sendgrid/transport/HttpClientTransport.java
  25. +27 −0 src/main/java/jp/co/flect/sendgrid/transport/ProxyInfo.java
  26. +17 −0 src/main/java/jp/co/flect/sendgrid/transport/Transport.java
  27. +62 −0 src/test/java/jp/co/flect/sendgrid/JsonTest.java
  28. +65 −0 src/test/java/jp/co/flect/sendgrid/SendGridTest.java
3  .gitignore
@@ -0,0 +1,3 @@
+target/
+build.xml
+test.properties
19 LICENSE.txt
@@ -0,0 +1,19 @@
+Copyright (c) 2013 Shunji Konishi and FLECT CO.,LTD.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
11 README.md
@@ -0,0 +1,11 @@
+sendgrid4j
+----------
+----------
+
+Overview
+--------
+Simple java client for SendGrid
+
+License
+-------
+MIT
52 pom.xml
@@ -0,0 +1,52 @@
+<project
+ xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+
+ <groupId>jp.co.flect</groupId>
+ <artifactId>sendgrid4j</artifactId>
+ <version>1.0-SNAPSHOT</version>
+ <packaging>jar</packaging>
+
+ <name>sendgrid4j</name>
+ <url>http://maven.apache.org</url>
+
+ <properties>
+ <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+ </properties>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.httpcomponents</groupId>
+ <artifactId>httpclient</artifactId>
+ <version>4.2.3</version>
+ </dependency>
+ <dependency>
+ <groupId>com.google.code.gson</groupId>
+ <artifactId>gson</artifactId>
+ <version>2.2</version>
+ </dependency>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <version>4.10</version>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <version>2.3.2</version>
+ <configuration>
+ <source>1.5</source>
+ <target>1.5</target>
+ <encoding>UTF-8</encoding>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+</project>
+
189 src/main/java/jp/co/flect/sendgrid/SendGridClient.java
@@ -0,0 +1,189 @@
+package jp.co.flect.sendgrid;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.io.File;
+import java.io.IOException;
+
+import jp.co.flect.sendgrid.transport.Transport;
+import jp.co.flect.sendgrid.transport.HttpClientTransport;
+import jp.co.flect.sendgrid.model.AbstractRequest;
+import jp.co.flect.sendgrid.model.App;
+import jp.co.flect.sendgrid.model.Block;
+import jp.co.flect.sendgrid.model.Bounce;
+import jp.co.flect.sendgrid.model.WebMail;
+import jp.co.flect.sendgrid.model.InvalidEmail;
+import jp.co.flect.sendgrid.model.Profile;
+import jp.co.flect.sendgrid.model.SpamReport;
+import jp.co.flect.sendgrid.model.Statistic;
+import jp.co.flect.sendgrid.model.Unsubscribe;
+import jp.co.flect.sendgrid.event.Event;
+import jp.co.flect.sendgrid.json.JsonUtils;
+
+public class SendGridClient {
+
+ private String username;
+ private String apikey;
+ private Transport transport;
+
+ private String baseUrl = "https://sendgrid.com/api";
+
+ public SendGridClient(String username, String apikey) {
+ this.username = username;
+ this.apikey = apikey;
+ this.transport = createDefaultTransport();
+ }
+
+ protected Transport createDefaultTransport() {
+ return new HttpClientTransport();
+ }
+
+ public String getBaseUrl() { return this.baseUrl;}
+ public void setBaseUrl(String url) { this.baseUrl = url;}
+
+ public Transport getTransport() { return this.transport;}
+ public void setTransport(Transport t) { this.transport = t;}
+
+ private String doRequest(String path, AbstractRequest request) throws IOException, SendGridException {
+ Map<String, String[]> map = request.getParams();
+ map.put("api_user", new String[] { this.username});
+ map.put("api_key", new String[] { this.apikey});
+
+ return this.transport.send(this.baseUrl + path, map);
+ }
+
+ //Blocks
+ public List<Block> getBlocks(Block.Get request) {
+ return null;
+ }
+
+ public void deleteBlocks(Block.Delete request) {
+ }
+
+ //Bounce
+ public List<Bounce> getBounces(Bounce.Get request) {
+ return null;
+ }
+
+ public void deleteBounces(Bounce.Delete request) {
+ }
+
+ public int countBounces(Bounce.Count request) {
+ return 0;
+ }
+
+ //Filter commands
+ public List<App> getAvailableApps() {
+ return null;
+ }
+
+ public void activateApp(String name) {
+ }
+
+ public void deactivateApp(String name) {
+ }
+
+ public void setupApp(App app) {
+ }
+
+ public App getAppSettings(String name) {
+ return null;
+ }
+
+ //Individual apps
+ public List<String> getAddressWhilteList() {
+ return null;
+ }
+
+ public void setAddressWhiteList(List<String> list) {
+ }
+
+ public String getBcc() {
+ return null;
+ }
+
+ public void setBcc(String bcc) {
+ }
+
+ public boolean isEnableClickTrackingInPlainText() {
+ return false;
+ }
+
+ public void setEnableClickTrackingInPlainText(boolean b) {
+ }
+
+ public void setDomainKeys(String domain, boolean sender) {
+ }
+
+ public void setDKIM(String domain, boolean useFrom) {
+ }
+
+ public void setEventNotification(String url, List<Event> enableEvents) {
+ }
+
+ //InvalidEmails
+ public List<InvalidEmail> getInvalidEmails(InvalidEmail.Get request) throws IOException, SendGridException {
+ String json = doRequest("/invalidemails.get.json", request);
+ List<Map<String, Object>> list = JsonUtils.parseArray(json);
+ List<InvalidEmail> ret = new ArrayList<InvalidEmail>();
+ for (Map<String, Object> map : list) {
+ ret.add(new InvalidEmail(map));
+ }
+ return ret;
+ }
+
+ public void deleteInvalidEmails(InvalidEmail.Delete request) {
+ }
+
+ //Mail
+ public void mail(WebMail mail, File... attachements) {
+ }
+
+ //Multiple Credentials - NOT IMPLEMENTED
+ //Parse WebHook Settings - NOT IMPLEMENTED
+
+ //Profile
+ public Profile getProfile() {
+ return null;
+ }
+
+ public void setProfile(Profile profile) {
+ }
+
+ public void setPassword(String newPassword) {
+ }
+
+ public void setUsername(String newUsername) {
+ }
+
+ public void setEmail(String newEmail) {
+ }
+
+ //SpamReports
+ public List<SpamReport> getSpamReports(SpamReport.Get request) {
+ return null;
+ }
+
+ public void deleteSpamReports(SpamReport.Delete request) {
+ }
+
+ public List<Statistic> getStatistics(Statistic.Get request) {
+ return null;
+ }
+
+ public List<String> getCategoryList() {
+ return null;
+ }
+
+ //Unsubscribles
+ public List<Unsubscribe> getUnsubscribes(Unsubscribe.Get request) {
+ return null;
+ }
+
+ public void deleteUnsubscribes(Unsubscribe.Delete request) {
+ }
+
+ public void addUnsubscribes(Unsubscribe.Add request) {
+ }
+}
48 src/main/java/jp/co/flect/sendgrid/SendGridException.java
@@ -0,0 +1,48 @@
+package jp.co.flect.sendgrid;
+
+import java.util.Arrays;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+public class SendGridException extends Exception {
+
+ private static String getMessageFromMap(Map<String, Object> map) {
+ Object msg = map.get("error");
+ if (msg != null) {
+ return msg.toString();
+ }
+ msg = map.get("errors");
+ if (msg instanceof List) {
+ return ((List)msg).get(0).toString();
+ }
+ throw new IllegalArgumentException(map.toString());
+ }
+
+ private List<String> msgs;
+
+ public SendGridException(String msg) {
+ super(msg);
+ this.msgs = Arrays.asList(msg);
+ }
+
+ public SendGridException(List<String> msgs) {
+ super(msgs.get(0));
+ this.msgs = msgs;
+ }
+
+ public SendGridException(Map<String, Object> map) {
+ super(getMessageFromMap(map));
+ this.msgs = new ArrayList<String>();
+ this.msgs.add(super.getMessage());
+ Object errors = map.get("errors");
+ if (errors instanceof List) {
+ List list = (List)errors;
+ for (int i=1; i<list.size(); i++) {//Skip 0
+ this.msgs.add(list.get(i).toString());
+ }
+ }
+ }
+
+ public List<String> getAllMessages() { return this.msgs;}
+}
13 src/main/java/jp/co/flect/sendgrid/event/Event.java
@@ -0,0 +1,13 @@
+package jp.co.flect.sendgrid.event;
+
+public enum Event {
+ Processed,
+ Dropped,
+ Deferred,
+ Delivered,
+ Bounce,
+ Click,
+ Open,
+ Unsubscribe,
+ SpamReport
+}
11 src/main/java/jp/co/flect/sendgrid/json/Json.java
@@ -0,0 +1,11 @@
+package jp.co.flect.sendgrid.json;
+
+import java.util.List;
+import java.util.Map;
+
+public interface Json {
+
+ public List<Map<String, Object>> parseArray(String str);
+ public Map<String, Object> parse(String str);
+ public String serialize(Object obj);
+}
24 src/main/java/jp/co/flect/sendgrid/json/JsonByGson.java
@@ -0,0 +1,24 @@
+package jp.co.flect.sendgrid.json;
+
+import java.util.List;
+import java.util.Map;
+import java.lang.reflect.Type;
+import com.google.gson.Gson;
+import com.google.gson.reflect.TypeToken;
+
+public class JsonByGson implements Json {
+
+ public List<Map<String, Object>> parseArray(String str) {
+ Type type = new TypeToken<List<Map<String, Object>>>() {}.getType();
+ return new Gson().fromJson(str, type);
+ }
+
+ public Map<String, Object> parse(String str) {
+ Type type = new TypeToken<Map<String, Object>>() {}.getType();
+ return new Gson().fromJson(str, type);
+ }
+
+ public String serialize(Object obj) {
+ return new Gson().toJson(obj);
+ }
+}
46 src/main/java/jp/co/flect/sendgrid/json/JsonUtils.java
@@ -0,0 +1,46 @@
+package jp.co.flect.sendgrid.json;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+
+public class JsonUtils {
+
+ private static final Json json;
+
+ static {
+ Json ret = null;
+ try {
+ Class.forName("com.google.gson.Gson");
+ ret = new JsonByGson();
+ } catch (Exception e) {
+ }
+ if (ret == null) {
+ throw new IllegalStateException("Jsonlibraries not found.");
+ }
+ json = ret;
+ }
+
+ public static List<Map<String, Object>> parseArray(String str) {
+ if (str == null || str.length() == 0) {
+ return null;
+ }
+ char c = str.charAt(0);
+ if (c == '[') {
+ return json.parseArray(str);
+ } else if (c == '{') {
+ Map<String, Object> map = json.parse(str);
+ return Arrays.asList(map);
+ } else {
+ throw new IllegalArgumentException(str);
+ }
+ }
+
+ public static Map<String, Object> parse(String str) {
+ return json.parse(str);
+ }
+
+ public static String serialize(Object obj) {
+ return json.serialize(obj);
+ }
+}
23 src/main/java/jp/co/flect/sendgrid/model/AbstractGetRequest.java
@@ -0,0 +1,23 @@
+package jp.co.flect.sendgrid.model;
+
+import java.util.Date;
+
+abstract class AbstractGetRequest extends AbstractRequest {
+
+ protected AbstractGetRequest(boolean includeDateParameter) {
+ if (includeDateParameter) {
+ doSetInt("date", 1);
+ }
+ }
+
+ public int getDays() { return doGetInt("days", 0);}
+ public void setDays(int n) { doSetInt("days", n);}
+
+ public Date getStartDate() { return doGetDate("start_date");}
+ public Date getEndDate() { return doGetDate("end_date");}
+ public void setStartAndEndDate(Date start, Date end) {
+ doSetDate("start_date", start);
+ doSetDate("end_date", end);
+ }
+
+}
87 src/main/java/jp/co/flect/sendgrid/model/AbstractModel.java
@@ -0,0 +1,87 @@
+package jp.co.flect.sendgrid.model;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Date;
+import java.text.SimpleDateFormat;
+import java.text.ParseException;
+
+public abstract class AbstractModel {
+
+ private static final String DATE_FORMAT = "yyyy-MM-dd";
+ private static final String DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
+
+ private Map<String, Object> map;
+ private SimpleDateFormat dateFormat = null;
+ private SimpleDateFormat datetimeFormat = null;
+
+ protected AbstractModel(Map<String, Object> map) {
+ this.map = map;
+ }
+
+ private SimpleDateFormat getDatetimeFormat() {
+ if (this.datetimeFormat == null) {
+ this.datetimeFormat = new SimpleDateFormat(DATETIME_FORMAT);
+ }
+ return this.datetimeFormat;
+ }
+
+ private SimpleDateFormat getDateFormat() {
+ if (this.dateFormat == null) {
+ this.dateFormat = new SimpleDateFormat(DATE_FORMAT);
+ }
+ return this.dateFormat;
+ }
+
+ protected int doGetInt(String name, int defaultValue) {
+ Object o = this.map.get(name);
+ if (o == null) {
+ return defaultValue;
+ } else if (o instanceof Number) {
+ return ((Number)o).intValue();
+ } else {
+ try {
+ return Integer.parseInt(o.toString());
+ } catch (NumberFormatException e) {
+ throw new IllegalStateException(name + ": " + o);
+ }
+ }
+ }
+
+ protected String doGetString(String name) {
+ Object o = this.map.get(name);
+ return o == null ? null : o.toString();
+ }
+
+ protected List<String> doGetList(String name) {
+ Object o = this.map.get(name);
+ if (o == null) {
+ return null;
+ }
+ List<String> ret = new ArrayList<String>();
+ if (o instanceof List) {
+ List list = (List)o;
+ for (Object value : list) {
+ ret.add(value.toString());
+ }
+ } else {
+ ret.add(o.toString());
+ }
+ return ret;
+ }
+
+ protected Date doGetDate(String name, boolean includeTime) {
+ String s = doGetString(name);
+ if (s == null) {
+ return null;
+ }
+ try {
+ SimpleDateFormat format = includeTime ? getDatetimeFormat() : getDateFormat();
+ return format.parse(s);
+ } catch (ParseException e) {
+ throw new IllegalStateException(name + ": " + s);
+ }
+ }
+
+}
82 src/main/java/jp/co/flect/sendgrid/model/AbstractRequest.java
@@ -0,0 +1,82 @@
+package jp.co.flect.sendgrid.model;
+
+import java.util.List;
+import java.util.Arrays;
+import java.util.Map;
+import java.util.HashMap;
+import java.util.Date;
+import java.text.SimpleDateFormat;
+import java.text.ParseException;
+
+public abstract class AbstractRequest {
+
+ private static final String DATE_FORMAT = "yyyy-MM-dd";
+
+ private Map<String, String[]> map = new HashMap<String, String[]>();
+ private SimpleDateFormat dateFormat = null;
+
+ private SimpleDateFormat getDateFormat() {
+ if (this.dateFormat == null) {
+ this.dateFormat = new SimpleDateFormat(DATE_FORMAT);
+ }
+ return this.dateFormat;
+ }
+
+ protected int doGetInt(String name, int defaultValue) {
+ String s = doGetString(name);
+ if (s == null) {
+ return defaultValue;
+ }
+ try {
+ return Integer.parseInt(s);
+ } catch (NumberFormatException e) {
+ throw new IllegalStateException(name + ": " + s);
+ }
+ }
+
+ protected void doSetInt(String name, int n) {
+ doSetString(name, Integer.toString(n));
+ }
+
+ protected String doGetString(String name) {
+ String[] strs = this.map.get(name);
+ return strs != null && strs.length > 0 ? strs[0] : null;
+ }
+
+ protected void doSetString(String name, String s) {
+ String[] strs = new String[1];
+ strs[0] = s;
+ this.map.put(name, strs);
+ }
+
+ protected List<String> doGetList(String name) {
+ String[] strs = map.get(name);
+ return strs != null && strs.length > 0 ? Arrays.asList(strs) : null;
+ }
+
+ protected void doSetList(String name, List<String> list) {
+ String[] strs = new String[list.size()];
+ strs = list.toArray(strs);
+ this.map.put(name, strs);
+ }
+
+ protected Date doGetDate(String name) {
+ String s = doGetString(name);
+ if (s == null) {
+ return null;
+ }
+ try {
+ return getDateFormat().parse(s);
+ } catch (ParseException e) {
+ throw new IllegalStateException(name + ": " + s);
+ }
+ }
+
+ protected void doSetDate(String name, Date d) {
+ doSetString(name, getDateFormat().format(d));
+ }
+
+ public Map<String, String[]> getParams() {
+ return new HashMap<String, String[]>(this.map);
+ }
+}
4 src/main/java/jp/co/flect/sendgrid/model/App.java
@@ -0,0 +1,4 @@
+package jp.co.flect.sendgrid.model;
+
+public class App {
+}
22 src/main/java/jp/co/flect/sendgrid/model/BasicGetRequest.java
@@ -0,0 +1,22 @@
+package jp.co.flect.sendgrid.model;
+
+import java.util.Date;
+import java.util.List;
+
+abstract class BasicGetRequest extends AbstractGetRequest {
+
+ protected BasicGetRequest() {
+ super(true);
+ }
+
+ public int getLimit() { return doGetInt("limit", 0);}
+ public void setLimit(int n) { doSetInt("limit", n);}
+
+ public int getOffset() { return doGetInt("offset", 0);}
+ public void setOffset(int n) { doSetInt("offset", n);}
+
+ public String getEmali() { return doGetString("email");}
+ public List<String> getEmailList() { return doGetList("email");}
+ public void setEmail(String s) { doSetString("email", s);}
+ public void setEmailList(List<String> list) { doSetList("email", list);}
+}
12 src/main/java/jp/co/flect/sendgrid/model/Block.java
@@ -0,0 +1,12 @@
+package jp.co.flect.sendgrid.model;
+
+public class Block {
+
+ public static class Get {
+
+ }
+
+ public static class Delete {
+ }
+
+}
15 src/main/java/jp/co/flect/sendgrid/model/Bounce.java
@@ -0,0 +1,15 @@
+package jp.co.flect.sendgrid.model;
+
+public class Bounce {
+
+ public static class Get {
+
+ }
+
+ public static class Delete {
+ }
+
+ public static class Count {
+ }
+
+}
22 src/main/java/jp/co/flect/sendgrid/model/InvalidEmail.java
@@ -0,0 +1,22 @@
+package jp.co.flect.sendgrid.model;
+
+import java.util.Date;
+import java.util.Map;
+
+public class InvalidEmail extends AbstractModel {
+
+ public InvalidEmail(Map<String, Object> map) {
+ super(map);
+ }
+
+ public String getReason() { return doGetString("reason");}
+ public Date getCreated() { return doGetDate("created", true);}
+ public String getEmail() { return doGetString("email");}
+
+ public static class Get extends BasicGetRequest {
+ }
+
+ public static class Delete {
+ }
+
+}
4 src/main/java/jp/co/flect/sendgrid/model/Profile.java
@@ -0,0 +1,4 @@
+package jp.co.flect.sendgrid.model;
+
+public class Profile {
+}
11 src/main/java/jp/co/flect/sendgrid/model/SpamReport.java
@@ -0,0 +1,11 @@
+package jp.co.flect.sendgrid.model;
+
+public class SpamReport {
+ public static class Get {
+
+ }
+
+ public static class Delete {
+ }
+
+}
11 src/main/java/jp/co/flect/sendgrid/model/Statistic.java
@@ -0,0 +1,11 @@
+package jp.co.flect.sendgrid.model;
+
+public class Statistic {
+ public static class Get {
+
+ }
+
+ public static class Delete {
+ }
+
+}
14 src/main/java/jp/co/flect/sendgrid/model/Unsubscribe.java
@@ -0,0 +1,14 @@
+package jp.co.flect.sendgrid.model;
+
+public class Unsubscribe {
+ public static class Get {
+
+ }
+
+ public static class Delete {
+ }
+
+ public static class Add {
+ }
+
+}
4 src/main/java/jp/co/flect/sendgrid/model/WebMail.java
@@ -0,0 +1,4 @@
+package jp.co.flect.sendgrid.model;
+
+public class WebMail {
+}
103 src/main/java/jp/co/flect/sendgrid/transport/HttpClientTransport.java
@@ -0,0 +1,103 @@
+package jp.co.flect.sendgrid.transport;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.HashMap;
+import jp.co.flect.sendgrid.json.JsonUtils;
+import jp.co.flect.sendgrid.model.WebMail;
+import jp.co.flect.sendgrid.SendGridException;
+
+import org.apache.http.auth.AuthScope;
+import org.apache.http.auth.UsernamePasswordCredentials;
+import org.apache.http.client.entity.UrlEncodedFormEntity;
+import org.apache.http.client.HttpClient;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.conn.params.ConnRoutePNames;
+import org.apache.http.HttpHost;
+import org.apache.http.HttpResponse;
+import org.apache.http.impl.client.DefaultHttpClient;
+import org.apache.http.message.BasicNameValuePair;
+import org.apache.http.NameValuePair;
+import org.apache.http.params.BasicHttpParams;
+import org.apache.http.params.HttpConnectionParams;
+import org.apache.http.util.EntityUtils;
+
+public class HttpClientTransport implements Transport {
+
+ private HttpClient client = null;
+ private ProxyInfo proxyInfo = null;
+
+ private int soTimeout = 0;
+ private int connectionTimeout = 0;
+
+ public String send(String url, Map<String, String[]> params) throws IOException, SendGridException {
+ HttpClient client = getHttpClient();
+ List<NameValuePair> list = new ArrayList<NameValuePair>();
+ for (Map.Entry<String, String[]> entry : params.entrySet()) {
+ String key = entry.getKey();
+ for (String s : entry.getValue()) {
+ list.add(new BasicNameValuePair(key, s));
+ }
+ }
+ HttpPost method = new HttpPost(url);
+ method.setEntity(new UrlEncodedFormEntity(list, "utf-8"));
+
+ HttpResponse res = client.execute(method);
+ String body = EntityUtils.toString(res.getEntity(), "utf-8");
+System.out.println("execute " + url + ": " + res.getStatusLine());
+System.out.println(body);
+
+ if (res.getStatusLine().getStatusCode() != 200) {
+ if (body != null && body.length() > 0 && body.charAt(0) == '{') {
+ Map<String, Object> map = null;
+ try {
+ map = JsonUtils.parse(body);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ if (map != null && (map.get("error") != null || map.get("errors") != null)) {
+ throw new SendGridException(map);
+ }
+ }
+ throw new SendGridException(res.getStatusLine().toString());
+ }
+ return body;
+ }
+
+ public void send(String url, WebMail mail, File... attachement) throws IOException, SendGridException {
+ }
+
+ public ProxyInfo getProxyInfo() { return this.proxyInfo;}
+ public void setProxyInfo(ProxyInfo proxy) { this.proxyInfo = proxy;}
+
+ private HttpClient getHttpClient() {
+ if (this.client == null) {
+ BasicHttpParams params = new BasicHttpParams();
+ HttpConnectionParams.setConnectionTimeout(params, this.connectionTimeout);
+ HttpConnectionParams.setSoTimeout(params, this.soTimeout);
+
+ DefaultHttpClient client = new DefaultHttpClient(params);
+ if (this.proxyInfo != null) {
+ HttpHost proxy = new HttpHost(proxyInfo.getHost(), proxyInfo.getPort());
+ client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
+ if (proxyInfo.getUserName() != null && proxyInfo.getPassword() != null) {
+ client.getCredentialsProvider().setCredentials(
+ new AuthScope(proxyInfo.getHost(), proxyInfo.getPort()),
+ new UsernamePasswordCredentials(proxyInfo.getUserName(), proxyInfo.getPassword()));
+ }
+ }
+ this.client = client;
+ }
+ return this.client;
+ }
+
+ public int getSoTimeout() { return this.soTimeout;}
+ public void setSoTimeout(int n) { this.soTimeout = n;}
+
+ public int getConnectionTimeout() { return this.connectionTimeout;}
+ public void setConnectionTimeout(int n) { this.connectionTimeout = n;}
+}
+
27 src/main/java/jp/co/flect/sendgrid/transport/ProxyInfo.java
@@ -0,0 +1,27 @@
+package jp.co.flect.sendgrid.transport;
+
+public class ProxyInfo {
+
+ private String host;
+ private int port;
+ private String username;
+ private String password;
+
+ public ProxyInfo(String host, int port) {
+ this(host, port, null, null);
+ }
+
+ public ProxyInfo(String host, int port, String username, String password) {
+ this.host = host;
+ this.port = port;
+ this.username = username;
+ this.password = password;
+ }
+
+ public String getHost() { return this.host;}
+ public int getPort() { return this.port;}
+ public String getUserName() { return this.username;}
+ public String getPassword() { return this.password;}
+
+}
+
17 src/main/java/jp/co/flect/sendgrid/transport/Transport.java
@@ -0,0 +1,17 @@
+package jp.co.flect.sendgrid.transport;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.Map;
+import jp.co.flect.sendgrid.SendGridException;
+import jp.co.flect.sendgrid.model.WebMail;
+
+public interface Transport {
+
+ public String send(String url, Map<String, String[]> params) throws IOException, SendGridException;
+ public void send(String url, WebMail mail, File... attachement) throws IOException, SendGridException;
+
+ public ProxyInfo getProxyInfo();
+ public void setProxyInfo(ProxyInfo proxy);
+}
+
62 src/test/java/jp/co/flect/sendgrid/JsonTest.java
@@ -0,0 +1,62 @@
+package jp.co.flect.sendgrid;
+
+import java.util.Arrays;
+import java.util.Map;
+import java.util.List;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.fail;
+import org.junit.Test;
+import org.junit.BeforeClass;
+
+import jp.co.flect.sendgrid.json.JsonUtils;
+
+public class JsonTest {
+
+ @Test
+ public void parse() throws Exception {
+ String str = "{\"str1\" : \"str\", "+
+ "\"num1\" : 5, " +
+ "\"num2\" : 6.0, " +
+ "\"num3\" : 3.14, " +
+ "\"bool1\" : true, " +
+ "\"bool2\" : false, " +
+ "\"array1\" : [\"str1\", \"str2\", \"str3\"], " +
+ "\"array2\" : [1, 2, 3], " +
+ "\"array3\" : [true, false, true], " +
+ "\"array4\" : [\"str1\", 2, true]}";
+
+ Map<String, Object> map = JsonUtils.parse(str);
+ test(map, "str1", "str");
+ test(map, "num1", 5.0);
+ test(map, "num2", 6.0);
+ test(map, "num3", 3.14);
+ test(map, "bool1", true);
+ test(map, "bool2", false);
+ test(map, "array1", Arrays.asList("str1", "str2", "str3"));
+ test(map, "array2", Arrays.asList(1.0, 2.0, 3.0));
+ test(map, "array3", Arrays.asList(true, false, true));
+ test(map, "array4", Arrays.asList("str1", 2.0, true));
+ }
+
+ private void test(Map<String, Object> map, String key, Object expected) {
+ Object value = map.get(key);
+ assertNotNull(value);
+ System.out.println(key + ", " + value.getClass().getName() + ", " + value);
+ if (value instanceof List) {
+ List list = (List)value;
+ List exList = (List)expected;
+ assertEquals(list.size(), exList.size());
+ for (int i=0; i<list.size(); i++) {
+ Object o = list.get(i);
+ Object o2 = exList.get(i);
+ System.out.println("array: " + o.getClass().getName() + ", " + o);
+ assertEquals(o, o2);
+ }
+ } else {
+ assertEquals(expected, value);
+ }
+ }
+}
65 src/test/java/jp/co/flect/sendgrid/SendGridTest.java
@@ -0,0 +1,65 @@
+package jp.co.flect.sendgrid;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.fail;
+import org.junit.Test;
+import org.junit.BeforeClass;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.InputStream;
+import java.util.Properties;
+import java.util.List;
+
+import jp.co.flect.sendgrid.model.InvalidEmail;
+
+public class SendGridTest {
+
+ private static String USERNAME;
+ private static String PASSWORD;
+ @BeforeClass
+ public static void setup() throws Exception {
+ Properties props = new Properties();
+
+ InputStream is = new FileInputStream(new File("test.properties"));
+ try {
+ props.load(is);
+ } finally {
+ is.close();
+ }
+ USERNAME = props.getProperty("SENDGRID_USERNAME");
+ PASSWORD = props.getProperty("SENDGRID_PASSWORD");
+
+ assertNotNull(USERNAME);
+ assertNotNull(PASSWORD);
+ }
+
+ @Test
+ public void invalidMails() throws Exception {
+ SendGridClient client = new SendGridClient(USERNAME, PASSWORD);
+ InvalidEmail.Get request = new InvalidEmail.Get();
+ List<InvalidEmail> list = client.getInvalidEmails(request);
+ assertTrue(list.size() > 0);
+ for (InvalidEmail mail : list) {
+ System.out.println("InvalidEmail: " + mail.getEmail() + ", " + mail.getCreated() + ", " + mail.getReason());
+ }
+ }
+
+ @Test
+ public void limitError() throws Exception {
+ SendGridClient client = new SendGridClient(USERNAME, PASSWORD);
+ InvalidEmail.Get request = new InvalidEmail.Get();
+ request.setLimit(0);
+ try {
+ client.getInvalidEmails(request);
+ fail();
+ } catch (SendGridException e) {
+ System.out.println("limitError:" + e.getMessage());
+ System.out.println("limitError2:" + e.getAllMessages());
+ assertTrue(e.getMessage().indexOf("Limit") > 0);
+ }
+ }
+}
Please sign in to comment.
Something went wrong with that request. Please try again.