-
Notifications
You must be signed in to change notification settings - Fork 0
/
CApiSmsResponseWithTracking.groovy
118 lines (99 loc) · 4.16 KB
/
CApiSmsResponseWithTracking.groovy
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
package dist
import org.apache.http.HttpResponse
import org.apache.http.client.HttpClient
import org.apache.http.client.methods.HttpGet
import org.apache.http.impl.client.HttpClientBuilder
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager
import org.apache.http.protocol.HttpContext
import org.apache.log4j.Logger
import org.simpleframework.http.Request
import java.util.concurrent.Executors
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.TimeUnit
class RequestHandler {
private static final Logger logger = Logger.getLogger(RequestHandler.class)
private static final Map contentByEventId = Collections.synchronizedMap(new LinkedHashMap());
private static final int THREADS = 10
private static final ScheduledExecutorService pool = Executors.newScheduledThreadPool(THREADS)
private static final int apiId = 1
private static final int shortCode = 123456
private static final String HOST_URL = "http://localhost:8888"
Map handleRequest(Request request) {
logger.info("Request received for: ${request.form.collect { key, value -> "[${key} : ${value}]" }.join(" ")}");
def message = request.form.find { key, value -> key.toLowerCase() == "text" }?.value
def code = getResponseCode(message)
if (code >= 0) {
def from = request.form.find { key, value -> key.toLowerCase() == "to" }?.value
def url = "${HOST_URL}/services/cns-sms?text=${code}&from=${from}&destination=${shortCode}"
logger.info("Will schedule response to ${url} in 30s")
pool.schedule(new ResponseHandler(url), 30, TimeUnit.SECONDS)
}
while (contentByEventId.size() > 10) {
contentByEventId.remove(contentByEventId.keySet()[0])
}
def eventId = request.form.find { key, value -> key.toLowerCase() == "event_id" }?.value
if (eventId && !message) {
def oldest = contentByEventId.isEmpty() ? "n/a" : contentByEventId.keySet()[0]
logger.info("Cached # of events ${contentByEventId.size()}; oldest: ${oldest}")
return [HttpStatus: 200, responseText: "${contentByEventId.get(eventId)}"]
}
if (eventId && message) {
contentByEventId.put(eventId, message)
}
return [HttpStatus: 200, responseText: "success"]
}
int getResponseCode(String content) {
logger.debug("Request message: '${content}'")
if (!content) {
return -1
}
// add 'reply' to the end of your message.
def matcher = content =~ '(?i)(?s).*reply\\s*(.*).*'
def found = []
if (matcher.matches()) {
def replyText = matcher.group(1)
found = replyText.findAll("(\\d+) to") { group ->
group[1] as int
}
}
return found ? found[(int) System.currentTimeMillis() % found.size()] : -1
}
}
class ResponseHandler implements Runnable {
private static final Logger logger = Logger.getLogger(ResponseHandler.class)
static HttpClient client = null;
final def url
ResponseHandler(def url) {
this.url = url
}
@Override
void run() {
HttpGet method = new HttpGet(url);
try {
HttpResponse response = getClient().execute(method, (HttpContext) null)
logger.info("GetMethod ${url} return code: ${response.statusLine.statusCode}.")
} catch (Exception e) {
logger.error("GetMethod ${url}.", e)
e.printStackTrace()
} finally {
method.releaseConnection()
}
}
static HttpClient getClient() {
if (!client) {
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
// Increase max total connection to 200
cm.setMaxTotal(200);
// Increase default max connection per route to 20
cm.setDefaultMaxPerRoute(20);
client = HttpClientBuilder.create().setConnectionManager(cm).build()
}
return client
}
}
/**
* return a map, including an entry for HttpStatus
*/
Map handleRequest(Request request) {
return new RequestHandler().handleRequest(request)
}