forked from dominicschaff/ClickatellJavaLibrary
-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathClickatellRest.java
More file actions
403 lines (368 loc) · 12.1 KB
/
ClickatellRest.java
File metadata and controls
403 lines (368 loc) · 12.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
/**
* This is an example of how to use the Clickatell REST API. NOTE: this is not
* the only way, this is just an example. This class can also be used as a
* library if you wish.
*
* @date Dec 2, 2014
* @author Dominic Schaff <dominic.schaff@gmail.com>
*/
public class ClickatellRest {
/**
* @var The URL to use for the base of the REST API.
*/
private static final String CLICKATELL_REST_BASE_URL = "https://api.clickatell.com/rest/";
private static final String POST = "POST", GET = "GET", DELETE = "DELETE";
/**
* @var The three private variables to use for authentication.
*/
private String apiKey;
/**
* Create a REST object, and set the auth, but not test the auth.
*/
public ClickatellRest(String apiKey) {
this.apiKey = apiKey;
}
/**
* This will attempt to get your current balance.
*
* @throws Exception
* This will be thrown if your auth details were incorrect.
*
* @return Your balance.
*/
public double getBalance() throws Exception {
// Send Request:
String response = this.excute("account/balance", GET, null);
JSONObject obj = (JSONObject) JSONValue.parse(response);
CheckForError(obj);
JSONObject objData = (JSONObject) obj.get("data");
String balance = (String) objData.get("balance");
return Double.parseDouble(balance);
}
/**
* This sends a single message.
*
* @param number
* The number that you wish to send to. This should be in
* international format.
* @param message
* The message you want to send,
*
* @throws Exception
* This gets thrown on an auth failure.
* @return A Message object which will contain the information from the
* request.
*/
public Message sendMessage(String number, String message) throws Exception {
// Send Request:
String response = this.excute("message", POST, "{\"to\":[\"" + number
+ "\"],\"text\":\"" + message + "\"}");
JSONObject obj = (JSONObject) JSONValue.parse(response);
CheckForError(obj);
Message msg = new Message();
JSONObject objData = (JSONObject) obj.get("data");
JSONArray msgArray = (JSONArray) objData.get("message");
JSONObject firstMsg = (JSONObject) msgArray.get(0);
msg.number = (String) firstMsg.get("to");
if (!((boolean) firstMsg.get("accepted"))) {
try {
CheckForError(firstMsg);
} catch (Exception e) {
msg.error = e.getMessage();
}
} else {
msg.message_id = (String) firstMsg.get("apiMessageId");
}
return msg;
}
/**
* This is to send the same message to multiple people.
*
* @param numbers
* The array of numbers that are to be sent to.
* @param message
* The message that you would like to send.
*
* @return An Array of Message objects which will contain the information
* from the request.
*
* @throws Exception
* This gets thrown on auth errors.
*/
public Message[] sendMessage(String[] numbers, String message)
throws Exception {
String number = numbers[0];
for (int x = 1; x < numbers.length; x++) {
number += "\",\"" + numbers[x];
}
ArrayList<Message> messages = new ArrayList<Message>();
// Send Request:
String response = this.excute("message", POST, "{\"to\":[\"" + number
+ "\"],\"text\":\"" + message + "\"}");
JSONObject obj = (JSONObject) JSONValue.parse(response);
CheckForError(obj);
JSONObject objData = (JSONObject) obj.get("data");
JSONArray msgArray = (JSONArray) objData.get("message");
for (int i = 0; i < msgArray.size(); i++) {
Message msg = new Message();
JSONObject firstMsg = (JSONObject) msgArray.get(i);
msg.number = (String) firstMsg.get("to");
if (!((boolean) firstMsg.get("accepted"))) {
try {
CheckForError(firstMsg);
} catch (Exception e) {
msg.error = e.getMessage();
}
} else {
msg.message_id = (String) firstMsg.get("apiMessageId");
}
messages.add(msg);
}
return messages.toArray(new Message[0]);
}
/**
* This will get the status and charge of the message given by the
* messageId.
*
* @param messageId
* The message ID that should be searched for.
*
* @return A Message object which will contain the information from the
* request.
*
* @throws Exception
* If there was an error with the request.
*/
public Message getMessageStatus(String messageId) throws Exception {
String response = this.excute("message/" + messageId, GET, null);
JSONObject obj = (JSONObject) JSONValue.parse(response);
CheckForError(obj);
Message msg = new Message();
JSONObject objData = (JSONObject) obj.get("data");
msg.message_id = (String) objData.get("apiMessageId");
msg.charge = String.valueOf(objData.get("charge"));
msg.status = (String) objData.get("messageStatus");
msg.statusString = (String) objData.get("description");
return msg;
}
/**
* This will try to stop a message that has been sent. Note that only
* messages that are going to be sent in the future can be stopped. Or if by
* some luck you message has not been sent to the operator yet.
*
* @param messageId
* The message ID that is to be stopped.
*
* @return A Message object which will contain the information from the
* request.
*
* @throws Exception
* If there was something wrong with the request.
*/
public Message stopMessage(String messageId) throws Exception {
// Send Request:
String response = this.excute("message/" + messageId, DELETE, null);
JSONObject obj = (JSONObject) JSONValue.parse(response);
CheckForError(obj);
Message msg = new Message();
JSONObject objData = (JSONObject) obj.get("data");
msg.message_id = (String) objData.get("apiMessageId");
msg.status = (String) objData.get("messageStatus");
msg.statusString = (String) objData.get("description");
return msg;
}
/**
* This will allow you to use any feature of the API. Note that you can do
* more powerful things with this function. And as such should only be used
* once you have read the documentation, as the parameters are passed
* directly to the API.
*
* @param numbers
* The list of numbers that must be sent to.
* @param message
* The message that is to be sent.
* @param features
* The extra features that should be included.
*
* @return An Array of Message objects which will contain the information
* from the request.
*
* @throws Exception
* If there is anything wrong with the submission this will get
* thrown.
*/
public Message[] sendAdvancedMessage(String[] numbers, String message,
HashMap<String, String> features) throws Exception {
ArrayList<Message> messages = new ArrayList<Message>();
String dataPacket = "{\"to\":[\"" + numbers[0];
for (int x = 1; x < numbers.length; x++) {
dataPacket += "\",\"" + numbers[x];
}
dataPacket += "\"],\"text\":\"" + message + "\"";
for (Entry<String, String> entry : features.entrySet()) {
dataPacket += ",\"" + entry.getKey() + "\":\"" + entry.getValue()
+ "\"";
}
dataPacket += "}";
// Send Request:
String response = this.excute("message", POST, dataPacket);
JSONObject obj = (JSONObject) JSONValue.parse(response);
CheckForError(obj);
JSONObject objData = (JSONObject) obj.get("data");
JSONArray msgArray = (JSONArray) objData.get("message");
for (int i = 0; i < msgArray.size(); i++) {
Message msg = new Message();
JSONObject firstMsg = (JSONObject) msgArray.get(i);
msg.number = (String) firstMsg.get("to");
if (!((boolean) firstMsg.get("accepted"))) {
try {
CheckForError(firstMsg);
} catch (Exception e) {
msg.error = e.getMessage();
}
} else {
msg.message_id = (String) firstMsg.get("apiMessageId");
}
messages.add(msg);
}
return messages.toArray(new Message[0]);
}
/**
* This attempts to get coverage data for the given number. A -1 means no
* coverage, all else is the minimum cost the message could charge.
*
* @param number
* The number the lookup should be done on.
* @return The minimum possible cost, or a -1 on error.
* @throws Exception
* If there was something wrong with the request.
*/
public double getCoverage(String number) throws Exception {
String response = this.excute("coverage/" + number, GET, null);
JSONObject obj = (JSONObject) JSONValue.parse(response);
CheckForError(obj);
JSONObject objData = (JSONObject) obj.get("data");
if (!((boolean) objData.get("routable"))) {
return -1;
}
return Double.parseDouble(String.valueOf(objData
.get("minimumCharge")));
}
/**
* This executes a POST query with the given parameters.
*
* @param resource
* The URL that should get hit.
* @param urlParameters
* The data you want to send via the POST.
*
* @return The content of the request.
* @throws UnknownHostException
*/
private String excute(String resource, String method, String dataPacket) throws UnknownHostException {
URL url;
HttpURLConnection connection = null;
try {
// Create connection
url = new URL(CLICKATELL_REST_BASE_URL + resource);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(method);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("X-Version", "1");
connection.setRequestProperty("Authorization", "Bearer " + apiKey);
String l = "0";
if (dataPacket != null) {
l = Integer.toString(dataPacket.getBytes().length);
}
connection.setRequestProperty("Content-Length", "" + l);
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(dataPacket != null);
// Send request
if (dataPacket != null) {
DataOutputStream wr = new DataOutputStream(
connection.getOutputStream());
wr.writeBytes(dataPacket);
wr.flush();
wr.close();
}
// Get Response
connection.getResponseCode();
InputStream stream = connection.getErrorStream();
if (stream == null) {
stream = connection.getInputStream();
}
BufferedReader rd = new BufferedReader(
new InputStreamReader(stream));
String line;
StringBuffer response = new StringBuffer();
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\n');
}
rd.close();
return response.toString().trim();
} catch (UnknownHostException e) {
throw e;
} catch (Exception e) {
return "";
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
/**
* This is an internal function used to shorten other functions. Checks for
* an error object, and throws it.
*
* @param obj
* The object that needs to be checked.
* @throws Exception
* The exception that was found.
*/
private void CheckForError(JSONObject obj) throws Exception {
JSONObject objError = (JSONObject) obj.get("error");
if (objError != null) {
throw new Exception((String) objError.get("description"));
}
}
/**
* This is the Message class that gets used as return values for some of the
* functions.
*
* @author Dominic Schaff <dominic.schaff@gmail.com>
*
*/
public class Message {
public String number = null, message_id = null, content = null,
charge = null, status = null, error = null, statusString;
public Message(String message_id) {
this.message_id = message_id;
}
public Message() {
}
public String toString() {
if (message_id != null) {
return number + ": " + message_id;
}
return number + ": " + error;
}
}
}