-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathApplitoolsTestResultsHandler.java
More file actions
948 lines (795 loc) · 37.7 KB
/
Copy pathApplitoolsTestResultsHandler.java
File metadata and controls
948 lines (795 loc) · 37.7 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
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
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
package TestResultsHandler;
import com.applitools.eyes.TestResults;
import com.sun.glass.ui.Size;
import org.apache.http.HttpHost;
import org.apache.http.HttpStatus;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import javax.imageio.*;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.metadata.IIOMetadataNode;
import javax.imageio.stream.FileImageOutputStream;
import javax.imageio.stream.ImageOutputStream;
import javax.net.ssl.HttpsURLConnection;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ApplitoolsTestResultsHandler {
private static final String VERSION = "1.3.3";
protected static final String STEP_RESULT_API_FORMAT = "/api/sessions/batches/%s/%s/?ApiKey=%s&format=json";
private static final String RESULT_REGEX = "(?<serverURL>^.+)\\/app\\/batches\\/(?<batchId>\\d+)\\/(?<sessionId>\\d+).*$";
private static final String IMAGE_TMPL = "%s/step %s %s-%s.png";
private static final int DEFAULT_TIME_BETWEEN_FRAMES = 500;
private static final String DiffsUrlTemplate = "%s/api/sessions/batches/%s/%s/steps/%s/diff?ApiKey=%s";
private static final String UPDATE_SESSIONS = "/api/sessions/batches/%s/updates";
private static final String UPDATE_SESSIONS_BASELINES = "/api/sessions/batches/%s/baselines";
private static final int RETRY_REQUEST_INTERVAL = 500; // ms
private static final int LONG_REQUEST_DELAY_MS = 2000; // ms
private static final int MAX_LONG_REQUEST_DELAY_MS = 10000; // ms
private static final int DEFAULT_TIMEOUT_MS = 300000; // ms (5 min)
private static final int REDUCED_TIMEOUT_MS = 15000; // ms (15 sec)
private static final double LONG_REQUEST_DELAY_MULTIPLICATIVE_INCREASE_FACTOR = 1.5;
protected String applitoolsRunKey;
protected String applitoolsViewKey;
protected String applitoolsWriteKey;
protected String serverURL;
protected String batchID;
protected String sessionID;
protected String accountID;
protected HttpHost proxy = null;
protected CredentialsProvider credsProvider = null;
private TestResults testResults;
private String[] stepsNames;
private ResultStatus[] stepsState;
private JSONObject testData;
private String prefix = "";
private String preparePath(String Path) {
Path += "/" + prefix;
if (!Path.contains("/" + batchID + "/" + sessionID)) {
Path = Path + "/" + batchID + "/" + sessionID;
File folder = new File(Path);
if (!folder.exists()) folder.mkdirs();
}
return Path;
}
private List<BufferedImage> baselineImages;
private List<BufferedImage> currentImages;
private List<BufferedImage> diffImages;
private int counter = 0;
public ApplitoolsTestResultsHandler(TestResults testResults, String viewKey, String proxyServer, String proxyPort, String proxyUser, String proxyPassword) throws Exception {
if ((proxyServer != null) && (proxyPort != null)) {
proxy = new HttpHost(proxyServer, Integer.parseInt(proxyPort));
if ((proxyPassword != null) && (proxyUser != null)) {
Credentials credentials = new UsernamePasswordCredentials(proxyUser, proxyPassword);
AuthScope authScope = new AuthScope(proxyServer, Integer.parseInt(proxyPort));
credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(authScope, credentials);
}
}
this.applitoolsViewKey = viewKey;
this.testResults = testResults;
Pattern pattern = Pattern.compile(RESULT_REGEX);
Matcher matcher = pattern.matcher(testResults.getUrl());
if (!matcher.find()) throw new Exception("Unexpected result URL - Not parsable");
this.batchID = matcher.group("batchId");
this.sessionID = matcher.group("sessionId");
this.serverURL = matcher.group("serverURL");
String accountIdParamName = "accountId=";
this.accountID = testResults.getUrl().substring(testResults.getUrl().indexOf(accountIdParamName) + accountIdParamName.length());
String url = String.format(serverURL + STEP_RESULT_API_FORMAT, this.batchID, this.sessionID, this.applitoolsViewKey);
String json = readJsonStringFromUrl(url);
this.testData = new JSONObject(json);
this.stepsNames = calculateStepsNames();
this.stepsState = prepareStepResults();
this.baselineImages = getBufferedImagesByType("Baseline");
this.currentImages = getBufferedImagesByType("Current");
this.diffImages = getBufferedImagesByType("Diff");
}
public ApplitoolsTestResultsHandler(TestResults testResults, String viewKey, String proxyServer, String proxyPort) throws Exception {
this(testResults, viewKey, proxyServer, proxyPort, null, null);
}
public ApplitoolsTestResultsHandler(TestResults testResults, String viewKey) throws Exception {
this(testResults, viewKey, null, null, null, null);
}
public void acceptChanges(List<ResultStatus> desiredStatuses, String writeKey) {
try {
if (writeKey != null) {
this.applitoolsWriteKey = writeKey;
acceptChangesToSteps(this.stepsState, desiredStatuses);
} else {
throw new Error("No Write Key was provided to the function!");
}
} catch (Exception e) {
e.printStackTrace();
}
}
private URL[] getDiffUrls() {
URL[] urls = new URL[stepsState.length];
for (int step = 0; step < this.testResults.getSteps(); ++step) {
if ((stepsState[step] == ResultStatus.UNRESOLVED) || (stepsState[step] == ResultStatus.FAILED)) {
try {
urls[step] = new URL(String.format(DiffsUrlTemplate, this.serverURL, this.batchID, this.sessionID, step + 1, this.applitoolsViewKey));
} catch (MalformedURLException e) {
e.printStackTrace();
}
} else urls[step] = null;
}
return urls;
}
public ResultStatus[] calculateStepResults() {
if (stepsState == null) try {
stepsState = prepareStepResults();
} catch (Exception e) {
e.printStackTrace();
}
return stepsState;
}
public String getLinkToStep(int step) {
String link = testResults.getUrl().replaceAll("batches", "sessions");
StringBuffer buf = new StringBuffer(link);
int index = link.indexOf("?accountId=");
return (buf.insert(index, "/steps/" + step).toString());
}
private ResultStatus[] prepareStepResults() throws Exception {
JSONArray expected = this.testData.getJSONArray("expectedAppOutput");
JSONArray actual = this.testData.getJSONArray("actualAppOutput");
int steps = Math.max(expected.length(), actual.length());
ResultStatus[] retStepResults = new ResultStatus[steps];
for (int i = 0; i < steps; i++) {
if (expected.get(i) == JSONObject.NULL) {
retStepResults[i] = ResultStatus.NEW;
} else if (actual.get(i) == JSONObject.NULL) {
retStepResults[i] = ResultStatus.MISSING;
} else if (actual.getJSONObject(i).getBoolean("isMatching")) {
retStepResults[i] = ResultStatus.PASSED;
} else {
retStepResults[i] = checkStepIfFailedOrUnresolved(i);
}
}
return retStepResults;
}
private void acceptChangesToSteps(ResultStatus[] results, List<ResultStatus> desiredStatuses) throws Exception {
int sizeResultStatus = results.length;
for (int i = 0; i < sizeResultStatus; i++) {
if (desiredStatuses.contains(results[i])) {
String url = String.format(serverURL + UPDATE_SESSIONS, this.batchID);
url = url + "?apiKey=" + this.applitoolsWriteKey;
String payload = String.format("{\"updates\":[{\"id\":\"%s\",\"batchId\":\"%s\",\"stepUpdates\":[{\"index\":%d,\"replaceExpected\":true}]}]}",
this.sessionID, this.batchID, i);
String json = postJsonToURL(url, payload);
url = String.format(serverURL + UPDATE_SESSIONS_BASELINES, this.batchID);
url = url + "?accountId=" + this.accountID + "&apiKey=" + this.applitoolsWriteKey;
payload = String.format("{\"ids\":[\"%s\"]}",
this.sessionID);
json = postJsonToURL(url, payload);
}
}
}
private ResultStatus checkStepIfFailedOrUnresolved(int i) throws JSONException {
if (getBugRegionsOfStep(i).length() == 0) {
return ResultStatus.UNRESOLVED;
} else {
JSONArray bugRegions = getBugRegionsOfStep(i);
for (int j = 1; j < bugRegions.length(); j++) {
if (!(((JSONObject) (bugRegions.get(j))).getBoolean("isDisabled"))) {
return ResultStatus.FAILED;
}
}
}
return ResultStatus.UNRESOLVED;
}
private JSONArray getBugRegionsOfStep(int i) throws JSONException {
JSONArray expected = this.testData.getJSONArray("expectedAppOutput");
return expected.getJSONObject(i).getJSONObject("annotations").getJSONArray("mismatching");
}
public String[] getStepsNames() {
return this.stepsNames;
}
private String[] calculateStepsNames() throws Exception {
ResultStatus[] stepResults = calculateStepResults();
JSONArray expected = this.testData.getJSONArray("expectedAppOutput");
JSONArray actual = this.testData.getJSONArray("actualAppOutput");
int steps = expected.length();
String[] StepsNames = new String[steps];
for (int i = 0; i < steps; i++) {
if (stepResults[i] != ResultStatus.NEW) {
StepsNames[i] = expected.getJSONObject(i).optString("tag");
} else {
StepsNames[i] = actual.getJSONObject(i).optString("tag");
}
}
return StepsNames;
}
private String readJsonStringFromUrl(String url) throws Exception {
HttpsURLConnection.setDefaultSSLSocketFactory(new sun.security.ssl.SSLSocketFactoryImpl());
CloseableHttpResponse response = null;
HttpGet get = new HttpGet(url);
CloseableHttpClient client = getCloseableHttpClient();
response = runLongRequest(client, get);
InputStream is = response.getEntity().getContent();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
return readAll(rd);
} finally {
if (null != is)
is.close();
if (null != client)
client.close();
if (null != response)
response.close();
}
}
private String postJsonToURL(String url, String payload) throws Exception {
HttpsURLConnection.setDefaultSSLSocketFactory(new sun.security.ssl.SSLSocketFactoryImpl());
CloseableHttpResponse response = null;
HttpPost post = new HttpPost(url);
post.setHeader("Accept", "application/json");
post.setHeader("Content-Type", "application/json");
StringEntity entity = new StringEntity(payload, "application/json", "utf-8");
post.setEntity(entity);
CloseableHttpClient client = getCloseableHttpClient();
response = runLongRequest(client, post);
InputStream is = response.getEntity().getContent();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
return readAll(rd);
} finally {
if (null != is)
is.close();
if (null != client)
client.close();
if (null != response)
response.close();
}
}
protected String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
private ArrayList<BufferedImage> getBufferedImagesByType(String type) throws IOException, JSONException, InterruptedException {
URL[] urls = null;
ArrayList<BufferedImage> images = new ArrayList<BufferedImage>();
if (type == "Baseline")
urls = getBaselineImagesURLS();
else if (type == "Current")
urls = getCurrentImagesURLS();
else if (type == "Diff")
urls = getDiffUrls();
if (urls != null) {
for (int i = 0; i < urls.length; i++) {
if (null != urls[i]) {
String windowsCompatibleStepName = makeWindowsFileNameCompatible(stepsNames[i]);
CloseableHttpResponse response = null;
HttpGet get = new HttpGet(urls[i].toString());
CloseableHttpClient client = getCloseableHttpClient();
response = runLongRequest(client, get);
InputStream is = response.getEntity().getContent();
try {
BufferedImage image = ImageIO.read(is);
images.add(image);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != is)
is.close();
if (null != client)
client.close();
if (null != response)
response.close();
}
} else {
images.add(null);
}
}
}
return images;
}
public List<BufferedImage> getBaselineBufferedImages() throws JSONException {
return this.baselineImages;
}
public List<BufferedImage> getCurrentBufferedImages() throws JSONException {
return this.currentImages;
}
public List<BufferedImage> getDiffsBufferedImages() throws JSONException {
return this.diffImages;
}
public void downloadDiffs(String path) throws Exception {
URL[] urls = getDiffUrls();
if (urls != null) {
saveImagesInFolder(preparePath(path), "Diff");
}
}
public void downloadBaselineImages(String path) throws IOException, InterruptedException, JSONException {
saveImagesInFolder(preparePath(path), "Baseline");
}
public void downloadCurrentImages(String path) throws IOException, InterruptedException, JSONException {
saveImagesInFolder(preparePath(path), "Current");
}
public void downloadImages(String path) throws Exception {
downloadBaselineImages(path);
downloadCurrentImages(path);
}
private void saveImagesInFolder(String path, String imageType) {
List<BufferedImage> imagesList = null;
ResultStatus[] resultStatus = this.calculateStepResults();
if (imageType == "Current")
imagesList = this.currentImages;
else if (imageType == "Baseline")
imagesList = this.baselineImages;
else if (imageType == "Diff")
imagesList = this.diffImages;
if (null != imagesList) {
for (int i = 0; i < imagesList.size(); i++) {
if (null != imagesList.get(i)) {
String windowsCompatibleStepName = makeWindowsFileNameCompatible(stepsNames[i]);
File outputFile = new File(String.format(IMAGE_TMPL, path, (i + 1), windowsCompatibleStepName, imageType));
try {
ImageIO.write(imagesList.get(i), "png", outputFile);
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("No " + imageType + " image was downloaded at step " + (i + 1) + " as this step status is " + resultStatus[i]);
}
}
}
}
private void saveImagesInFolder(String path, String imageType, URL[] imageURLS) throws InterruptedException, IOException, JSONException {
for (int i = 0; i < imageURLS.length; i++) {
if (imageURLS[i] == null) {
System.out.println("No " + imageType + " image in step " + (i + 1) + ": " + stepsNames[i]);
} else {
String windowsCompatibleStepName = makeWindowsFileNameCompatible(stepsNames[i]);
CloseableHttpResponse response = null;
HttpGet get = new HttpGet(imageURLS[i].toString());
CloseableHttpClient client = getCloseableHttpClient();
response = runLongRequest(client, get);
InputStream is = response.getEntity().getContent();
try {
BufferedImage bi = ImageIO.read(is);
ImageIO.write(bi, "png", new File(String.format(IMAGE_TMPL, path, (i + 1), windowsCompatibleStepName, imageType)));
} finally {
if (null != is)
is.close();
if (null != client)
client.close();
if (null != response)
response.close();
}
}
}
}
private String makeWindowsFileNameCompatible(String stepName) {
stepName = stepName.replace('/', '~');
stepName = stepName.replace("\\", "~");
stepName = stepName.replace(':', '~');
stepName = stepName.replace('*', '~');
stepName = stepName.replace('?', '~');
stepName = stepName.replace('"', '~');
stepName = stepName.replace("'", "~");
stepName = stepName.replace('<', '~');
stepName = stepName.replace('>', '~');
stepName = stepName.replace('|', '~');
while (!stepName.equals(stepName.replace("~~", "~"))) {
stepName = stepName.replace("~~", "~");
}
return stepName;
}
private URL[] getDownloadImagesURLSByType(String imageType) throws JSONException {
String[] imageIds = getImagesUIDs(this.sessionID, this.batchID, imageType);
URL[] URLS = new URL[calculateStepResults().length];
for (int i = 0; i < imageIds.length; i++) {
if (imageIds[i] == null) {
URLS[i] = null;
} else try {
URLS[i] = new URL(String.format("%s/api/images/%s?apiKey=%s", this.serverURL, imageIds[i], this.applitoolsViewKey));
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
return URLS;
}
private URL[] getCurrentImagesURLS() throws JSONException {
return getDownloadImagesURLSByType("Current");
}
private URL[] getBaselineImagesURLS() throws JSONException {
return getDownloadImagesURLSByType("Baseline");
}
private String[] getImagesUIDs(String sessionId, String batchId, String imageType) throws JSONException {
String sessionInfo = null;
try {
sessionInfo = getSessionInfo(sessionId, batchId);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
JSONObject obj = new JSONObject(sessionInfo);
if (imageType == "Baseline") {
return getImagesUIDs(obj.getJSONArray("expectedAppOutput"));
} else if (imageType == "Current") {
return getImagesUIDs(obj.getJSONArray("actualAppOutput"));
}
return null;
}
private String[] getImagesUIDs(JSONArray infoTable) throws JSONException {
String[] retUIDs = new String[infoTable.length()];
for (int i = 0; i < infoTable.length(); i++) {
if (infoTable.isNull(i)) {
retUIDs[i] = null;
} else {
JSONObject entry = infoTable.getJSONObject(i);
JSONObject image = entry.getJSONObject("image");
retUIDs[i] = (image.getString("id"));
}
}
return retUIDs;
}
public void downloadAnimatedGif(String path) throws JSONException {
downloadAnimatedGif(path, DEFAULT_TIME_BETWEEN_FRAMES);
}
public void downloadAnimatedGif(String path, int timeBetweenFramesMS) throws JSONException {
if (testResults.getMismatches() + testResults.getMatches() > 0) // only if the test isn't new and not all of his steps are missing
{
URL[] baselineImagesURLS = getBaselineImagesURLS();
URL[] currentImagesURL = getCurrentImagesURLS();
URL[] diffImagesURL = getDiffUrls();
List<BufferedImage> base = getBaselineBufferedImages(); // get Baseline Images as BufferedImage
List<BufferedImage> curr = getCurrentBufferedImages(); // get Current Images as BufferedImage
List<BufferedImage> diff = getDiffsBufferedImages(); // get Diff Images as BufferedImage
for (int i = 0; i < stepsState.length; i++) {
if ((stepsState[i] == ResultStatus.UNRESOLVED) || (stepsState[i] == ResultStatus.FAILED)) {
List<BufferedImage> list = new ArrayList<BufferedImage>();
try {
if (currentImagesURL[i] != null) list.add(curr.get(i));
if (baselineImagesURLS[i] != null) list.add(base.get(i));
if (diffImagesURL[i] != null) list.add(diff.get(i));
String tempPath = preparePath(path) + "/" + (i + 1) + " - AnimatedGif.gif";
createAnimatedGif(list, new File(tempPath), timeBetweenFramesMS);
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("No Animated GIf created for Step " + (i + 1) + " " + stepsNames[i] + " as it is " + stepsState[i]);
}
}
}
}
private String getSessionInfo(String sessionId, String batchId) throws IOException, InterruptedException {
URL url = new URL(String.format("%s/api/sessions/batches/%s/%s?apiKey=%s&format=json", this.serverURL, batchId, sessionId, this.applitoolsViewKey));
HttpGet get = new HttpGet(url.toString());
CloseableHttpClient client = getCloseableHttpClient();
CloseableHttpResponse response = null;
response = runLongRequest(client, get);
InputStream stream = response.getEntity().getContent();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(stream, Charset.forName("UTF-8")));
return readAll(rd);
} finally {
if (null != stream)
stream.close();
if (null != client)
client.close();
if (null != response)
response.close();
}
}
private static void createAnimatedGif(List<BufferedImage> images, File target, int timeBetweenFramesMS) throws IOException {
ImageOutputStream output = new FileImageOutputStream(target);
GifSequenceWriter writer = null;
Size max = getMaxSize(images);
try {
for (BufferedImage image : images) {
BufferedImage normalized = new BufferedImage(max.width, max.height, image.getType());
normalized.getGraphics().drawImage(image, 0, 0, null);
if (writer == null) writer = new GifSequenceWriter(output, image.getType(), timeBetweenFramesMS, true);
writer.writeToSequence(normalized);
}
} finally {
writer.close();
output.close();
}
}
private static Size getMaxSize(List<BufferedImage> images) {
Size max = new Size(0, 0);
for (BufferedImage image : images) {
if (max.height < image.getHeight()) max.height = image.getHeight();
if (max.width < image.getWidth()) max.width = image.getWidth();
}
return max;
}
private static class GifSequenceWriter {
protected ImageWriter gifWriter;
protected ImageWriteParam imageWriteParam;
protected IIOMetadata imageMetaData;
/**
* Creates a new GifSequenceWriter
*
* @param outputStream the ImageOutputStream to be written to
* @param imageType one of the imageTypes specified in BufferedImage
* @param timeBetweenFramesMS the time between frames in miliseconds
* @param loopContinuously wether the gif should loop repeatedly
* @throws IIOException if no gif ImageWriters are found
* @author Elliot Kroo (elliot[at]kroo[dot]net)
*/
public GifSequenceWriter(
ImageOutputStream outputStream,
int imageType,
int timeBetweenFramesMS,
boolean loopContinuously) throws IIOException, IOException {
// my method to create a writer
gifWriter = getWriter();
imageWriteParam = gifWriter.getDefaultWriteParam();
ImageTypeSpecifier imageTypeSpecifier =
ImageTypeSpecifier.createFromBufferedImageType(imageType);
imageMetaData =
gifWriter.getDefaultImageMetadata(imageTypeSpecifier,
imageWriteParam);
String metaFormatName = imageMetaData.getNativeMetadataFormatName();
IIOMetadataNode root = (IIOMetadataNode)
imageMetaData.getAsTree(metaFormatName);
IIOMetadataNode graphicsControlExtensionNode = getNode(
root,
"GraphicControlExtension");
graphicsControlExtensionNode.setAttribute("disposalMethod", "none");
graphicsControlExtensionNode.setAttribute("userInputFlag", "FALSE");
graphicsControlExtensionNode.setAttribute(
"transparentColorFlag",
"FALSE");
graphicsControlExtensionNode.setAttribute(
"delayTime",
Integer.toString(timeBetweenFramesMS / 10));
graphicsControlExtensionNode.setAttribute(
"transparentColorIndex",
"0");
IIOMetadataNode commentsNode = getNode(root, "CommentExtensions");
commentsNode.setAttribute("CommentExtension", "Created by MAH");
IIOMetadataNode appEntensionsNode = getNode(
root,
"ApplicationExtensions");
IIOMetadataNode child = new IIOMetadataNode("ApplicationExtension");
child.setAttribute("applicationID", "NETSCAPE");
child.setAttribute("authenticationCode", "2.0");
int loop = loopContinuously ? 0 : 1;
child.setUserObject(new byte[]{0x1, (byte) (loop & 0xFF), (byte)
((loop >> 8) & 0xFF)});
appEntensionsNode.appendChild(child);
imageMetaData.setFromTree(metaFormatName, root);
gifWriter.setOutput(outputStream);
gifWriter.prepareWriteSequence(null);
}
public void writeToSequence(RenderedImage img) throws IOException {
gifWriter.writeToSequence(
new IIOImage(
img,
null,
imageMetaData),
imageWriteParam);
}
/**
* Close this GifSequenceWriter object. This does not close the underlying
* stream, just finishes off the GIF.
*/
public void close() throws IOException {
gifWriter.endWriteSequence();
}
/**
* Returns the first available GIF ImageWriter using
* ImageIO.getImageWritersBySuffix("gif").
*
* @return a GIF ImageWriter object
* @throws IIOException if no GIF image writers are returned
*/
private static ImageWriter getWriter() throws IIOException {
Iterator<ImageWriter> iter = ImageIO.getImageWritersBySuffix("gif");
if (!iter.hasNext()) {
throw new IIOException("No GIF Image Writers Exist");
} else {
return iter.next();
}
}
/**
* Returns an existing child node, or creates and returns a new child node (if
* the requested node does not exist).
*
* @param rootNode the <tt>IIOMetadataNode</tt> to search for the child node.
* @param nodeName the name of the child node.
* @return the child node, if found or a new node created with the given name.
*/
private static IIOMetadataNode getNode(
IIOMetadataNode rootNode,
String nodeName) {
int nNodes = rootNode.getLength();
for (int i = 0; i < nNodes; i++) {
if (rootNode.item(i).getNodeName().compareToIgnoreCase(nodeName)
== 0) {
return ((IIOMetadataNode) rootNode.item(i));
}
}
IIOMetadataNode node = new IIOMetadataNode(nodeName);
rootNode.appendChild(node);
return (node);
}
/**
* public GifSequenceWriter(
* BufferedOutputStream outputStream,
* int imageType,
* int timeBetweenFramesMS,
* boolean loopContinuously) {
*/
public static void main(String[] args) throws Exception {
if (args.length > 1) {
// grab the output image type from the first image in the sequence
BufferedImage firstImage = ImageIO.read(new File(args[0]));
// create a new BufferedOutputStream with the last argument
ImageOutputStream output =
new FileImageOutputStream(new File(args[args.length - 1]));
// create a gif sequence with the type of the first image, 1 second
// between frames, which loops continuously
GifSequenceWriter writer =
new GifSequenceWriter(output, firstImage.getType(), 1, false);
// write out the first image to our sequence...
writer.writeToSequence(firstImage);
for (int i = 1; i < args.length - 1; i++) {
BufferedImage nextImage = ImageIO.read(new File(args[i]));
writer.writeToSequence(nextImage);
}
writer.close();
output.close();
} else {
System.out.println(
"Usage: java GifSequenceWriter [list of gif files] [output file]");
}
}
}
public void SetPathPrefixStructure(String pathPrefix) throws JSONException {
pathPrefix = pathPrefix.replaceAll("TestName", this.getTestName());
pathPrefix = pathPrefix.replaceAll("AppName", this.getAppName());
pathPrefix = pathPrefix.replaceAll("viewport", this.getViewportSize());
pathPrefix = pathPrefix.replaceAll("hostingOS", this.getHostingOS());
pathPrefix = pathPrefix.replaceAll("hostingApp", this.getHostingApp());
prefix = pathPrefix;
}
public String getTestName() throws JSONException {
return this.testData.getJSONObject("startInfo").optString("scenarioName");
}
public String getAppName() throws JSONException {
return this.testData.getJSONObject("startInfo").optString("appName");
}
public String getViewportSize() throws JSONException {
return this.testData.getJSONObject("startInfo").getJSONObject("environment").getJSONObject("displaySize").optString("width").toString() + "x" + this.testData.getJSONObject("startInfo").getJSONObject("environment").getJSONObject("displaySize").optString("height").toString();
}
public String getHostingOS() throws JSONException {
return this.testData.getJSONObject("startInfo").getJSONObject("environment").optString("os");
}
public String getHostingApp() throws JSONException {
return this.testData.getJSONObject("startInfo").getJSONObject("environment").optString("hostingApp");
}
public CloseableHttpResponse runLongRequest(CloseableHttpClient client, HttpRequestBase apiCall) throws InterruptedException {
HttpRequestBase requestBase = createHttpRequest(apiCall);
CloseableHttpResponse response = sendRequest(client, requestBase, 1, false);
return longRequestCheckStatus(response);
}
public CloseableHttpResponse sendRequest(CloseableHttpClient client, HttpRequestBase apiCall, int retry, boolean delayBeforeRetry) throws InterruptedException {
counter += 1;
String requestId = counter + "--" + UUID.randomUUID();
apiCall.addHeader("x-applitools-eyes-client-request-id", requestId);
CloseableHttpResponse response;
try {
response = client.execute(apiCall);
return response;
} catch (Exception e) {
String errorMessage = "error message: " + e.getMessage();
System.out.println(errorMessage);
if (retry > 0) {
if (delayBeforeRetry) {
Thread.sleep(RETRY_REQUEST_INTERVAL);
return sendRequest(client, apiCall, retry - 1, delayBeforeRetry);
}
return sendRequest(client, apiCall, retry - 1, delayBeforeRetry);
}
throw new Error(errorMessage);
}
}
public CloseableHttpResponse longRequestCheckStatus(CloseableHttpResponse responseReceived) throws InterruptedException {
int status = responseReceived.getStatusLine().getStatusCode();
HttpRequestBase request = null;
String URI;
switch (status) {
case HttpStatus.SC_OK:
return responseReceived;
case HttpStatus.SC_ACCEPTED:
URI = responseReceived.getFirstHeader("Location").getValue() + "?apiKey=" + this.applitoolsViewKey;
request = new HttpGet(URI);
request = createHttpRequest(request);
CloseableHttpResponse requestResponse = longRequestLoop(request, LONG_REQUEST_DELAY_MS);
return longRequestCheckStatus(requestResponse);
case HttpStatus.SC_CREATED:
URI = responseReceived.getFirstHeader("Location").getValue() + "?apiKey=" + this.applitoolsViewKey;
request = new HttpDelete(URI);
request = createHttpRequest(request);
return sendRequest(getCloseableHttpClient(), request, 1, false);
case HttpStatus.SC_GONE:
throw new Error("The server task is gone");
default:
throw new Error("Unknown error during long request: " + responseReceived.getStatusLine());
}
}
public CloseableHttpResponse longRequestLoop(HttpRequestBase options, int delay) throws InterruptedException {
delay = (int) Math.min(
MAX_LONG_REQUEST_DELAY_MS,
Math.floor(delay * LONG_REQUEST_DELAY_MULTIPLICATIVE_INCREASE_FACTOR));
System.out.println("Still running... Retrying in " + delay);
Thread.sleep(delay);
CloseableHttpResponse response = sendRequest(getCloseableHttpClient(), options, 1, false);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return longRequestLoop(options, delay);
}
return response;
}
private CloseableHttpClient getCloseableHttpClient() {
CloseableHttpClient client;
if (proxy == null) {
client = HttpClientBuilder.create().build();
} else if (credsProvider == null) {
client = HttpClientBuilder.create().setProxy(proxy).build();
} else {
client = HttpClientBuilder.create().setProxy(proxy).setDefaultCredentialsProvider(credsProvider).build();
}
return client;
}
public HttpRequestBase createHttpRequest(HttpRequestBase apiCall) {
try {
if (this.proxy != null) {
RequestConfig requestConfig = RequestConfig.custom()
.setProxy(this.proxy)
.build();
apiCall.setConfig(requestConfig);
}
return apiCall;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public HttpRequestBase createHttpRequestWithHeaders(HttpRequestBase apiCall) {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz");
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
String RFC1123_formatted_current_client_time = dateFormat.format(calendar.getTime());
try {
if (this.proxy != null) {
RequestConfig requestConfig = RequestConfig.custom()
.setProxy(this.proxy)
.build();
apiCall.setConfig(requestConfig);
}
apiCall.addHeader("Eyes-Expect", "202+location");
apiCall.addHeader("Eyes-Date", RFC1123_formatted_current_client_time);
return apiCall;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}