-
Notifications
You must be signed in to change notification settings - Fork 0
/
AmazonMTurkClient.java
586 lines (471 loc) · 20 KB
/
AmazonMTurkClient.java
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
package com.cclo7;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.TimeZone;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.codec.binary.Base64;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class AmazonMTurkClient {
private final String ACCESS_KEY;
private final String SECRET_KEY;
private final String REST_API_VERSION;
private final String SERVICE_URL;
private final String PREVIEW_URL;
private static final String DEFAULT_REST_API_VERSION = "2011-10-01";
private static final String MTURK_SERVICE_NAME = "AWSMechanicalTurkRequester";
private static final String PRODUCTION_SERVICE_URL = "https://mechanicalturk.amazonaws.com/";
private static final String SANDBOX_SERVICE_URL = "https://mechanicalturk.sandbox.amazonaws.com/";
private static final String PRODUCTION_PREVIEW_URL = "https://www.mturk.com/mturk/preview?";
private static final String SANDBOX_PREVIEW_URL = "https://workersandbox.mturk.com/mturk/preview?";
//operation name
private static final String APPROVE_ASSIGNMENT_OPERATION = "ApproveAssignment";
private static final String CREATE_HIT_OPERATION = "CreateHIT";
private static final String EXTEND_HIT_OPERATION = "ExtendHIT";
private static final String GET_ASSIGNMENTS_FOR_HIT_OPERATION = "GetAssignmentsForHIT";
private static final String GRANT_BONUS_OPERATION = "GrantBonus";
private static final String REJECT_ASSIGNMENT_OPERATION = "RejectAssignment";
private static final String SET_HITTYPE_NOTIFICATION_OPERATION = "SetHITTypeNotification";
private static final int REST_REQUEST_RETRY_LIMIT = 15;
public AmazonMTurkClient(String accessKey, String secretKey, String restApiVersion, boolean isUseSandbox){
this.ACCESS_KEY = accessKey;
this.SECRET_KEY = secretKey;
this.REST_API_VERSION = restApiVersion;
if(isUseSandbox){
this.SERVICE_URL = SANDBOX_SERVICE_URL;
this.PREVIEW_URL = SANDBOX_PREVIEW_URL;
}else{
this.SERVICE_URL = PRODUCTION_SERVICE_URL;
this.PREVIEW_URL = PRODUCTION_PREVIEW_URL;
}
}
public AmazonMTurkClient(String accessKey, String secretKey, boolean isUseSandbox){
this(accessKey, secretKey, DEFAULT_REST_API_VERSION, isUseSandbox);
}
/*
* functions for MTurk operations
*/
public boolean approveAssignment(String assignmentId){
Map<String, String> parameters = new HashMap<String, String>(1);
parameters.put("AssignmentId", assignmentId);
String response = this.makeMTurkRequest(APPROVE_ASSIGNMENT_OPERATION, parameters);
if(response != null && response.length() > 0){
String responseXML = this.decodeXML(response.toString());
try{
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new InputSource(new StringReader(responseXML)));
doc.getDocumentElement().normalize();
NodeList isValidNodeList = doc.getElementsByTagName("IsValid");
if(isValidNodeList.getLength() > 0){
Element isValidElement = (Element) isValidNodeList.item(0);
String isValid = isValidElement.getTextContent();
if(isValid.equals("True")){
return true;
}
}
NodeList messageNodeList = doc.getElementsByTagName("Message");
if(messageNodeList.getLength() > 0){
Element messageElement = (Element) messageNodeList.item(0);
String message = messageElement.getTextContent();
if(message.contains("Submitted")){
return true;
}
}
} catch(ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
public Map<String, String> createHIT(String title, String description, String question, double rewardAmt,
long maxAssignments, long assignmentDurationInSeconds, long lifetimeInSeconds,
long autoApprovalDelayInSeconds, QualificationRequirement qualificationRequirement){
Map<String, String> responseMap = new HashMap<String, String>(3);
Map<String, String> parameters = new HashMap<String, String>(1);
parameters.put("Title", title);
parameters.put("Description", description);
parameters.put("Question", question);
parameters.put("Reward.1.Amount", Double.toString(rewardAmt));
parameters.put("Reward.1.CurrencyCode", "USD");
parameters.put("MaxAssignments", Long.toString(maxAssignments));
parameters.put("AssignmentDurationInSeconds", Long.toString(assignmentDurationInSeconds));
parameters.put("LifetimeInSeconds", Long.toString(lifetimeInSeconds));
parameters.put("AutoApprovalDelayInSeconds", Long.toString(autoApprovalDelayInSeconds));
if(qualificationRequirement != null){
parameters.put("QualificationRequirement.1.QualificationTypeId", qualificationRequirement.getTypeId());
parameters.put("QualificationRequirement.1.Comparator", qualificationRequirement.getComparator());
parameters.put("QualificationRequirement.1.IntegerValue", Integer.toString(qualificationRequirement.getIntegerValue()));
}
String response = this.makeMTurkRequest(CREATE_HIT_OPERATION, parameters);
if(response != null && response.length() > 0){
String responseXML = this.decodeXML(response.toString());
try{
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new InputSource(new StringReader(responseXML)));
doc.getDocumentElement().normalize();
NodeList isValidNodeList = doc.getElementsByTagName("IsValid");
if(isValidNodeList.getLength() > 0){
Element isValidElement = (Element) isValidNodeList.item(0);
String isValid = isValidElement.getTextContent();
if(isValid.equals("True")){
String hitId = null;
NodeList hitIdNodeList = doc.getElementsByTagName("HITId");
if(hitIdNodeList.getLength() > 0){
Element hitIdElement = (Element) hitIdNodeList.item(0);
hitId = hitIdElement.getTextContent();
responseMap.put("hitId", hitId);
}
String hitTypeId = null;
NodeList hitTypeIdNodeList = doc.getElementsByTagName("HITTypeId");
if(hitTypeIdNodeList.getLength() > 0){
Element hitTypeIdElement = (Element) hitTypeIdNodeList.item(0);
hitTypeId = hitTypeIdElement.getTextContent();
responseMap.put("hitTypeId", hitTypeId);
}
if(hitId != null && hitTypeId != null){
String previewUrl = this.getPreviewUrl(hitTypeId);
responseMap.put("previewUrl", previewUrl);
System.out.println("createHIT success: " + previewUrl);
}
}else{
System.err.println("createHIT operation: invalid request");
}
}
} catch(ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return responseMap;
}
public Map<String, String> createHITWithExternalQuestion(String title, String description,
String questionUrl, int externalFrameHeight, double rewardAmt, long maxAssignments,
long assignmentDurationInSeconds, long lifetimeInSeconds, long autoApprovalDelayInSeconds,
QualificationRequirement qualificationRequirement){
String question = this.getExternalQuestion(questionUrl, externalFrameHeight);
return this.createHIT(title, description, question, rewardAmt, maxAssignments,
assignmentDurationInSeconds, lifetimeInSeconds, autoApprovalDelayInSeconds,
qualificationRequirement);
}
public boolean extendHIT(String hitId, int maxAssignmentsIncrement){
Map<String, String> parameters = new HashMap<String, String>(1);
parameters.put("HITId", hitId);
parameters.put("MaxAssignmentsIncrement", Integer.toString(maxAssignmentsIncrement));
String response = this.makeMTurkRequest(EXTEND_HIT_OPERATION, parameters);
if(response != null && response.length() > 0){
String responseXML = this.decodeXML(response.toString());
try{
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new InputSource(new StringReader(responseXML)));
doc.getDocumentElement().normalize();
NodeList isValidNodeList = doc.getElementsByTagName("IsValid");
if(isValidNodeList.getLength() > 0){
Element isValidElement = (Element) isValidNodeList.item(0);
String isValid = isValidElement.getTextContent();
if(isValid.equals("True")){
return true;
}
}
} catch(ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
public Map<String, String> getAssignmentsForHIT(String hitId){
HashMap<String, String> answerMap = new HashMap<String, String>(3);
Map<String, String> parameters = new HashMap<String, String>(1);
parameters.put("HITId", hitId);
String response = this.makeMTurkRequest(GET_ASSIGNMENTS_FOR_HIT_OPERATION, parameters);
//parse XML response for worker's submitted answer
if(response != null && response.length() > 0){
String responseXML = this.decodeXML(response.toString());
//DOM ran into problems when using it to parse this nested xml
//so we use substring here
//check value of IsValid node
String tagName = "<IsValid>";
int first = responseXML.indexOf(tagName) + tagName.length();
int last = responseXML.indexOf("</IsValid>");
String isValidValue = responseXML.substring(first, last);
if(isValidValue.equals("True")){
//get assignmentId
tagName = "<AssignmentId>";
first = responseXML.lastIndexOf(tagName) + tagName.length();
last = responseXML.lastIndexOf("</AssignmentId>");
String assignmentId = responseXML.substring(first, last);
answerMap.put("assignmentId", assignmentId);
//get workerId
tagName = "<WorkerId>";
first = responseXML.lastIndexOf(tagName) + tagName.length();
last = responseXML.lastIndexOf("</WorkerId>");
String workerId = responseXML.substring(first, last);
answerMap.put("workerId", workerId);
//get the inner nested xml data
tagName = "</QuestionFormAnswers>";
first = responseXML.lastIndexOf("<?xml");
last = responseXML.lastIndexOf(tagName) + tagName.length();
responseXML = responseXML.substring(first, last);
try{
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new InputSource(new StringReader(responseXML)));
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("Answer");
for(int i = 0; i < nodeList.getLength(); i++){
Element answerElement = (Element) nodeList.item(i);
Element idElement = (Element) answerElement.getElementsByTagName("QuestionIdentifier").item(0);
Element textElement = (Element) answerElement.getElementsByTagName("FreeText").item(0);
String id = idElement.getTextContent();
String text = textElement.getTextContent();
answerMap.put(id, text);
}
} catch(ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}else{
System.err.println("Request of GetAssignmentsForHIT is invalid");
}
}
return answerMap;
}
public boolean grantBonus(String workerId, String assignmentId, double bonusAmt, String reason){
Map<String, String> parameters = new HashMap<String, String>(5);
parameters.put("WorkerId", workerId);
parameters.put("AssignmentId", assignmentId);
parameters.put("BonusAmount.1.Amount", Double.toString(bonusAmt));
parameters.put("BonusAmount.1.CurrencyCode", "USD");
parameters.put("Reason", reason);
String response = this.makeMTurkRequest(GRANT_BONUS_OPERATION, parameters);
if(response != null && response.length() > 0){
String responseXML = this.decodeXML(response.toString());
try{
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new InputSource(new StringReader(responseXML)));
doc.getDocumentElement().normalize();
NodeList isValidNodeList = doc.getElementsByTagName("IsValid");
if(isValidNodeList.getLength() > 0){
Element isValidElement = (Element) isValidNodeList.item(0);
String isValid = isValidElement.getTextContent();
if(isValid.equals("True")){
return true;
}
}
} catch(ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
public boolean rejectAssignment(String assignmentId, String requesterFeedback){
Map<String, String> parameters = new HashMap<String, String>(5);
parameters.put("AssignmentId", assignmentId);
if(requesterFeedback != null && requesterFeedback.length() > 0){
parameters.put("RequesterFeedback", requesterFeedback);
}
String response = this.makeMTurkRequest(REJECT_ASSIGNMENT_OPERATION, parameters);
if(response != null && response.length() > 0){
String responseXML = this.decodeXML(response.toString());
try{
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new InputSource(new StringReader(responseXML)));
doc.getDocumentElement().normalize();
NodeList isValidNodeList = doc.getElementsByTagName("IsValid");
if(isValidNodeList.getLength() > 0){
Element isValidElement = (Element) isValidNodeList.item(0);
String isValid = isValidElement.getTextContent();
if(isValid.equals("True")){
return true;
}
}
} catch(ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
public boolean setHITTypeNotification(String hitTypeId, String destination, String[] eventTypes,
String transport, boolean isMakeActive){
Map<String, String> parameters = new HashMap<String, String>(5);
parameters.put("HITTypeId", hitTypeId);
parameters.put("Active", Boolean.toString(isMakeActive));
parameters.put("Notification.1.Destination", destination);
parameters.put("Notification.1.Transport", transport);
parameters.put("Notification.1.Version", "2006-05-05");
parameters.put("Notification.1.Destination", destination);
if(eventTypes.length < 1){
return false;
}else if(eventTypes.length == 1){
parameters.put("Notification.1.EventType", eventTypes[0]);
}else{
for(int i = 0; i < eventTypes.length; i++){
parameters.put("Notification.1.EventType." + i, eventTypes[i]);
}
}
boolean success = false;
String response = this.makeMTurkRequest(SET_HITTYPE_NOTIFICATION_OPERATION, parameters);
if(response != null && response.length() > 0){
String responseXML = this.decodeXML(response.toString());
try{
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new InputSource(new StringReader(responseXML)));
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("IsValid");
if(nodeList.getLength() > 0){
Element isValidElement = (Element) nodeList.item(0);
if(isValidElement.getTextContent().equals("True")){
success = true;
System.out.println("Successfully set notification endpoint at:" + destination);
}
}
} catch(ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return success;
}
public String getPreviewURL(){
return this.PREVIEW_URL;
}
/*
* private Helper functions
*/
private String decodeXML(String rawXML){
return rawXML.replace("<", "<").replace(">", ">");
}
private String getExternalQuestion(String url, int externalFrameHeight){
StringBuffer q = new StringBuffer();
q.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
q.append("<ExternalQuestion xmlns=\"http://mechanicalturk.amazonaws.com/AWSMechanicalTurkDataSchemas/2006-07-14/ExternalQuestion.xsd\">");
q.append(" <ExternalURL>" + url + "</ExternalURL>");
q.append(" <FrameHeight>" + externalFrameHeight + "</FrameHeight>");
q.append("</ExternalQuestion>");
return q.toString();
}
/*
* Note: HitTypeId can be used for the groupId parameter as well
*/
private String getPreviewUrl(String groupId){
return this.PREVIEW_URL + "groupId=" + groupId;
}
private String getTimestamp(){
Calendar cal = Calendar.getInstance();
DateFormat dfm = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
dfm.setTimeZone(TimeZone.getTimeZone("GMT"));
String timestamp = dfm.format(cal.getTime());
return timestamp;
}
private String getSignature(String operation, String timestamp){
String signatureData = MTURK_SERVICE_NAME + operation + timestamp;
String signature = null;
try{
Mac mac = Mac.getInstance("HmacSHA1");
SecretKeySpec signingKey = new SecretKeySpec(this.SECRET_KEY.getBytes(), mac.getAlgorithm());
mac.init(signingKey);
byte[] rawHmac = mac.doFinal(signatureData.getBytes());
Base64 encoder = new Base64();
signature = new String(encoder.encode(rawHmac));
}catch(NoSuchAlgorithmException e){
}catch(InvalidKeyException e){
e.printStackTrace();
}
return signature;
}
private String makeMTurkRequest(String operation, Map<String, String> parameters){
String result = null;
int i = 0;
while(i < REST_REQUEST_RETRY_LIMIT){ //loop until success or reach limit
String timestamp = this.getTimestamp();
String signature = this.getSignature(operation, timestamp);
StringBuffer requestUrl = new StringBuffer(this.SERVICE_URL);
StringBuffer response = new StringBuffer();
try{
requestUrl.append("?Service=" + MTURK_SERVICE_NAME);
requestUrl.append("&AWSAccessKeyId=" + this.ACCESS_KEY);
requestUrl.append("&Version=" + this.REST_API_VERSION);
requestUrl.append("&Operation=" + operation);
requestUrl.append("&Signature=" + signature);
requestUrl.append("&Timestamp=" + timestamp);
for(Map.Entry<String, String> entry : parameters.entrySet()){
requestUrl.append("&" + entry.getKey() + "=");
requestUrl.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
URL url = new URL(requestUrl.toString());
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while((line = reader.readLine()) != null){
response.append(line);
}
reader.close();
}catch(MalformedURLException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
result = response.toString();
if(!result.contains("<Errors>") || result.contains("InvalidAssignmentState")){
//no error
break;
}
System.err.println("makeMTurkRequest error response: " + result);
i++;
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return result;
}
}