-
Notifications
You must be signed in to change notification settings - Fork 396
/
ConnectionRequest.java
2936 lines (2681 loc) · 106 KB
/
ConnectionRequest.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
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
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores
* CA 94065 USA or visit www.oracle.com if you need additional information or
* have any questions.
*/
package com.codename1.io;
import com.codename1.impl.CodenameOneImplementation;
import com.codename1.l10n.ParseException;
import com.codename1.l10n.SimpleDateFormat;
import com.codename1.ui.Dialog;
import com.codename1.ui.Display;
import com.codename1.ui.EncodedImage;
import com.codename1.ui.Image;
import com.codename1.ui.events.ActionEvent;
import com.codename1.ui.events.ActionListener;
import com.codename1.ui.util.EventDispatcher;
import com.codename1.util.AsyncResource;
import com.codename1.util.Base64;
import com.codename1.util.Callback;
import com.codename1.util.CallbackAdapter;
import com.codename1.util.CallbackDispatcher;
import com.codename1.util.FailureCallback;
import com.codename1.util.StringUtil;
import com.codename1.util.SuccessCallback;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
/**
* <p>This class represents a connection object in the form of a request response
* typically common for HTTP/HTTPS connections. A connection request is added to
* the {@link com.codename1.io.NetworkManager} for processing in a queue on one of the
* network threads. You can read more about networking in Codename One {@link com.codename1.io here}</p>
*
* <p>The sample
* code below fetches a page of data from the nestoria housing listing API.<br>
* You can see instructions on how to display the data in the {@link com.codename1.components.InfiniteScrollAdapter}
* class. You can read more about networking in Codename One {@link com.codename1.io here}.</p>
* <script src="https://gist.github.com/codenameone/22efe9e04e2b8986dfc3.js"></script>
*
* @author Shai Almog
*/
public class ConnectionRequest implements IOProgressListener {
/**
* A critical priority request will "push" through the queue to the highest point
* regardless of anything else and ignoring anything that is not in itself of
* critical priority.
* A critical priority will stop any none critical connection in progress
*/
public static final byte PRIORITY_CRITICAL = (byte)100;
/**
* A high priority request is the second highest level, it will act exactly like
* a critical priority with one difference. It doesn't block another incoming high priority
* request. E.g. if a high priority request
*/
public static final byte PRIORITY_HIGH = (byte)80;
/**
* Normal priority executes as usual on the queue
*/
public static final byte PRIORITY_NORMAL = (byte)50;
/**
* Low priority requests are mostly background tasks that should still be accomplished though
*/
public static final byte PRIORITY_LOW = (byte)30;
/**
* Redundant elements can be discarded from the queue when paused
*/
public static final byte PRIORITY_REDUNDANT = (byte)0;
/**
* The default value for the cacheMode property see {@link #getCacheMode()}
* @return the defaultCacheMode
*/
public static CachingMode getDefaultCacheMode() {
return defaultCacheMode;
}
/**
* The default value for the cacheMode property see {@link #getCacheMode()}
* @param aDefaultCacheMode the defaultCacheMode to set
*/
public static void setDefaultCacheMode(CachingMode aDefaultCacheMode) {
defaultCacheMode = aDefaultCacheMode;
}
/**
* Determines the default value for {@link #isReadResponseForErrors()}
* @return the readResponseForErrorsDefault
*/
public static boolean isReadResponseForErrorsDefault() {
return readResponseForErrorsDefault;
}
/**
* Determines the default value for {@link #setReadResponseForErrors(boolean)}
* @param aReadResponseForErrorsDefault the readResponseForErrorsDefault to set
*/
public static void setReadResponseForErrorsDefault(boolean aReadResponseForErrorsDefault) {
readResponseForErrorsDefault = aReadResponseForErrorsDefault;
}
/**
* When set to true (the default), the global error handler in
* {@code NetworkManager} should receive errors for response code as well
* @return the handleErrorCodesInGlobalErrorHandler
*/
public static boolean isHandleErrorCodesInGlobalErrorHandler() {
return handleErrorCodesInGlobalErrorHandler;
}
/**
* When set to true (the default), the global error handler in
* {@code NetworkManager} should receive errors for response code as well
* @param aHandleErrorCodesInGlobalErrorHandler the handleErrorCodesInGlobalErrorHandler to set
*/
public static void setHandleErrorCodesInGlobalErrorHandler(
boolean aHandleErrorCodesInGlobalErrorHandler) {
handleErrorCodesInGlobalErrorHandler =
aHandleErrorCodesInGlobalErrorHandler;
}
/**
* <p>There are 5 caching modes:</p>
* <ol>
* <li>{@code OFF} is the default, meaning no caching.
* <li>{@code SMART} means all get requests are cached intelligently and caching is "mostly" seamless.
* <li>{@code MANUAL} means that the developer is responsible for the actual caching but the system will not do a
* request on a resource that's already "fresh".
* <li>{@code OFFLINE} will fetch data from the cache and wont try to go to the server. It will generate a 404 error
* if data isn't available.
* <li>{@code OFFLINE_FIRST} works the same way as offline but if data isn't available locally it will try to
* connect to the server.
* </ol>
*
* @return the cacheMode
*/
public CachingMode getCacheMode() {
return cacheMode;
}
/**
* <p>There are 5 caching modes:</p>
* <ol>
* <li>{@code OFF} is the default, meaning no caching.
* <li>{@code SMART} means all get requests are cached intelligently and caching is "mostly" seamless.
* <li>{@code MANUAL} means that the developer is responsible for the actual caching but the system will not do a
* request on a resource that's already "fresh".
* <li>{@code OFFLINE} will fetch data from the cache and wont try to go to the server. It will generate a 404 error
* if data isn't available.
* <li>{@code OFFLINE_FIRST} works the same way as offline but if data isn't available locally it will try to
* connect to the server.
* </ol>
*
* @param cacheMode the cacheMode to set
*/
public void setCacheMode(CachingMode cacheMode) {
this.cacheMode = cacheMode;
}
/**
* @return the checkSSLCertificates
*/
public boolean isCheckSSLCertificates() {
return checkSSLCertificates;
}
/**
* @param checkSSLCertificates the checkSSLCertificates to set
*/
public void setCheckSSLCertificates(boolean checkSSLCertificates) {
this.checkSSLCertificates = checkSSLCertificates;
}
/**
* <p>There are 5 caching modes:</p>
* <ol>
* <li>{@code OFF} is the default, meaning no caching.
* <li>{@code SMART} means all get requests are cached intelligently and caching is "mostly" seamless.
* <li>{@code MANUAL} means that the developer is responsible for the actual caching but the system will not do a
* request on a resource that's already "fresh".
* <li>{@code OFFLINE} will fetch data from the cache and wont try to go to the server. It will generate a 404 error
* if data isn't available.
* <li>{@code OFFLINE_FIRST} works the same way as offline but if data isn't available locally it will try to
* connect to the server.
* </ol>
*/
public static enum CachingMode {
OFF,
MANUAL,
SMART,
OFFLINE,
OFFLINE_FIRST
}
/**
* Connection ID. Can be used for callbacks from native layer.
*/
private int id;
/**
* The default value for the cacheMode property see {@link #getCacheMode()}
*/
private static CachingMode defaultCacheMode = CachingMode.OFF;
/**
* <p>There are 5 caching modes:</p>
* <ol>
* <li>{@code OFF} is the default, meaning no caching.
* <li>{@code SMART} means all get requests are cached intelligently and caching is "mostly" seamless.
* <li>{@code MANUAL} means that the developer is responsible for the actual caching but the system will not do a
* request on a resource that's already "fresh".
* <li>{@code OFFLINE} will fetch data from the cache and wont try to go to the server. It will generate a 404 error
* if data isn't available.
* <li>{@code OFFLINE_FIRST} works the same way as offline but if data isn't available locally it will try to
* connect to the server.
* </ol>
*/
private CachingMode cacheMode = defaultCacheMode;
/**
* Connection ID used for callbacks from native layer
* @param id
*/
void setId(int id) {
this.id = id;
}
/**
* Connection ID used for callbacks from native layer.
* @return
*/
int getId() {
return id;
}
/**
* Workaround for https://bugs.php.net/bug.php?id=65633 allowing developers to
* customize the name of the cookie header to Cookie
* @return the cookieHeader
*/
public static String getCookieHeader() {
return cookieHeader;
}
/**
* Workaround for https://bugs.php.net/bug.php?id=65633 allowing developers to
* customize the name of the cookie header to Cookie
* @param aCookieHeader the cookieHeader to set
*/
public static void setCookieHeader(String aCookieHeader) {
cookieHeader = aCookieHeader;
}
/**
* @return the cookiesEnabledDefault
*/
public static boolean isCookiesEnabledDefault() {
return cookiesEnabledDefault;
}
/**
* @param aCookiesEnabledDefault the cookiesEnabledDefault to set
*/
public static void setCookiesEnabledDefault(boolean aCookiesEnabledDefault) {
if(!aCookiesEnabledDefault) {
setUseNativeCookieStore(false);
}
cookiesEnabledDefault = aCookiesEnabledDefault;
}
private EventDispatcher actionListeners;
/**
* Enables/Disables automatic redirects globally and returns the 302 error code, <strong>IMPORTANT</strong>
* this feature doesn't work on all platforms and currently doesn't work on iOS which always implicitly redirects
* @return the defaultFollowRedirects
*/
public static boolean isDefaultFollowRedirects() {
return defaultFollowRedirects;
}
/**
* Enables/Disables automatic redirects globally and returns the 302 error code, <strong>IMPORTANT</strong>
* this feature doesn't work on all platforms and currently doesn't work on iOS which always implicitly redirects
* @param aDefaultFollowRedirects the defaultFollowRedirects to set
*/
public static void setDefaultFollowRedirects(boolean aDefaultFollowRedirects) {
defaultFollowRedirects = aDefaultFollowRedirects;
}
private byte priority = PRIORITY_NORMAL;
private long timeSinceLastUpdate;
private LinkedHashMap requestArguments;
private boolean post = true;
private String contentType = "application/x-www-form-urlencoded; charset=UTF-8";
private static String defaultUserAgent = null;
private String userAgent = getDefaultUserAgent();
private String url;
private boolean writeRequest;
private boolean readRequest = true;
private boolean paused;
private boolean killed = false;
private static boolean defaultFollowRedirects = true;
private boolean followRedirects = defaultFollowRedirects;
private int timeout = -1;
private int readTimeout = -1;
private InputStream input;
private OutputStream output;
private int progress = NetworkEvent.PROGRESS_TYPE_OUTPUT;
private int contentLength = -1;
private boolean duplicateSupported = true;
private EventDispatcher responseCodeListeners;
private EventDispatcher exceptionListeners;
private Hashtable userHeaders;
private Dialog showOnInit;
private Dialog disposeOnCompletion;
private byte[] data;
private int responseCode;
boolean complete;
private String responseErrorMessge;
private String httpMethod;
private int silentRetryCount = 0;
private boolean failSilently;
boolean retrying;
private static boolean readResponseForErrorsDefault = true;
private boolean readResponseForErrors = readResponseForErrorsDefault;
private String responseContentType;
private boolean redirecting;
private static boolean cookiesEnabledDefault = true;
private boolean cookiesEnabled = cookiesEnabledDefault;
private int chunkedStreamingLen = -1;
private Exception failureException;
private int failureErrorCode;
private String destinationFile;
private String destinationStorage;
private SSLCertificate[] sslCertificates;
private boolean checkSSLCertificates;
/**
* A flag that turns off checking for invalid certificates.
*/
private boolean insecure;
/**
* When set to true (the default), the global error handler in
* {@code NetworkManager} should receive errors for response code as well
*/
private static boolean handleErrorCodesInGlobalErrorHandler = true;
/**
* The request body can be used instead of arguments to pass JSON data to a restful request,
* it can't be used in a get request and will fail if you have arguments
*/
private String requestBody;
/**
* The request body can be used instead of arguments to pass JSON data to a restful request. It
* can't be used in a get request and will fail if you have arguments.
*/
private Data requestBodyData;
// Flag to indicate if the contentType was explicitly set for this
// request
private boolean contentTypeSetExplicitly;
/**
* Workaround for https://bugs.php.net/bug.php?id=65633 allowing developers to
* customize the name of the cookie header to Cookie
*/
private static String cookieHeader = "cookie";
/**
* Default constructor
*/
public ConnectionRequest() {
if(NetworkManager.getInstance().isAPSupported()) {
silentRetryCount = 1;
}
}
/**
* Construct a connection request to a url
*
* @param url the url
*/
public ConnectionRequest(String url) {
this();
setUrl(url);
}
/**
* Construct a connection request to a url
*
* @param url the url
* @param post whether the request is a post url or a get URL
*/
public ConnectionRequest(String url, boolean post) {
this(url);
setPost(post);
}
/**
* Turns off checking to make sure that SSL certificate is valid.
* @param insecure
* @since 7.0
*/
public void setInsecure(boolean insecure) {
this.insecure = insecure;
}
/**
* Checks if the request is insecure (default false).
* @return True if the request is insecure, i.e. does not check SSL certificate for validity.
* @since 7.0
*/
public boolean isInsecure() {
return insecure;
}
/**
* This method will return a valid value for only some of the responses and only after the response was processed
* @return null or the actual data returned
*/
public byte[] getResponseData() {
return data;
}
/**
* Sets the http method for the request
* @param httpMethod the http method string
*/
public void setHttpMethod(String httpMethod) {
this.httpMethod = httpMethod;
}
/**
* Returns the http method
* @return the http method of the request
*/
public String getHttpMethod() {
return httpMethod;
}
/**
* Adds the given header to the request that will be sent
*
* @param key the header key
* @param value the header value
*/
public void addRequestHeader(String key, String value) {
if(userHeaders == null) {
userHeaders = new Hashtable();
}
if(key.equalsIgnoreCase("content-type")) {
setContentType(value);
} else {
userHeaders.put(key, value);
}
}
/**
* Adds the given header to the request that will be sent unless the header
* is already set to something else
*
* @param key the header key
* @param value the header value
*/
void addRequestHeaderDontRepleace(String key, String value) {
if(userHeaders == null) {
userHeaders = new Hashtable();
}
if(!userHeaders.containsKey(key)) {
userHeaders.put(key, value);
}
}
void prepare() {
complete = false;
timeSinceLastUpdate = System.currentTimeMillis();
}
/**
* A callback that can be overridden by subclasses to check the SSL certificates
* for the server, and kill the connection if they don't pass muster. This can
* be used for SSL pinning.
*
* <p><strong>NOTE:</strong> This method will only be called if {@link #isCheckSSLCertificates() } is {@literal true} and the platform supports SSL certificates ({@link #canGetSSLCertificates() }.</p>
*
* <p><strong>WARNING:</strong> On iOS it is possible that certificates for a request would not be available even through the
* platform supports it, and checking certificates are enabled. This could happen if the certificates had been cached by the
* TLS cache by some network mechanism other than ConnectionRequest (e.g. native code, websockets, etc..). In such cases
* this method would receive an empty array as a parameter.</p>
*
* <p>This is called after the SSL handshake, but before any data has been sent.</p>
* @param certificates The server's SSL certificates.
* @see #setCheckSSLCertificates(boolean)
* @see #isCheckSSLCertificates()
*/
protected void checkSSLCertificates(SSLCertificate[] certificates) {
}
/**
* Sets the read timeout for the connection. This is only used if {@link #isReadTimeoutSupported() }
* is true on this platform. Currently Android, Mac Desktop, Windows Desktop, and Simulator supports read timeouts.
* @param timeout The read timeout. If less than or equal to zero, then there is no timeout.
* @see #isReadTimeoutSupported()
*/
public void setReadTimeout(int timeout) {
readTimeout = timeout;
}
/**
* Gets the read timeout for this connection. This is only used if {@link #isReadTimeoutSupported() }
* is true on this platform. Currently Android, Mac Desktop, Windows Desktop, and Simulator supports read timeouts.
* @return The read timeout.
* @since 7.0
*/
public int getReadTimeout() {
return readTimeout;
}
/**
* Checks if this platform supports read timeouts.
* @since 7.0
* @return True if this connection supports read timeouts;
*/
public static boolean isReadTimeoutSupported() {
return Util.getImplementation().isReadTimeoutSupported();
}
/**
* Invoked to initialize HTTP headers, cookies etc.
*
* @param connection the connection object
*/
protected void initConnection(Object connection) {
timeSinceLastUpdate = System.currentTimeMillis();
CodenameOneImplementation impl = Util.getImplementation();
impl.setPostRequest(connection, isPost());
if (readTimeout > 0) {
impl.setReadTimeout(connection, readTimeout);
}
if (insecure) {
impl.setInsecure(connection, insecure);
}
impl.setConnectionId(connection, id);
if(getUserAgent() != null) {
impl.setHeader(connection, "User-Agent", getUserAgent());
}
if (getContentType() != null) {
// UWP will automatically filter out the Content-Type header from GET requests
// Historically, CN1 has always included this header even though it has no meaning
// for GET requests. it would be be better if CN1 did not include this header
// with GET requests, but for backward compatibility, I'll leave it on as
// the default, and add a property to turn it off.
// -- SJH Sept. 15, 2016
boolean shouldAddContentType = contentTypeSetExplicitly ||
Display.getInstance().getProperty("ConnectionRequest.excludeContentTypeFromGetRequests", "true").equals("false");
if (isPost() || (getHttpMethod() != null && !"get".equals(getHttpMethod().toLowerCase()))) {
shouldAddContentType = true;
}
if(shouldAddContentType) {
impl.setHeader(connection, "Content-Type", getContentType());
}
}
if(chunkedStreamingLen > -1){
impl.setChunkedStreamingMode(connection, chunkedStreamingLen);
}
if(!post && (cacheMode == CachingMode.MANUAL || cacheMode == CachingMode.SMART
|| cacheMode == CachingMode.OFFLINE_FIRST)) {
String msince = Preferences.get("cn1MSince" + createRequestURL(), null);
if(msince != null) {
impl.setHeader(connection, "If-Modified-Since", msince);
} else {
String etag = Preferences.get("cn1Etag" + createRequestURL(), null);
if(etag != null) {
impl.setHeader(connection, "If-None-Match", etag);
}
}
}
if(userHeaders != null) {
Enumeration e = userHeaders.keys();
while(e.hasMoreElements()) {
String k = (String)e.nextElement();
String value = (String)userHeaders.get(k);
impl.setHeader(connection, k, value);
}
}
}
/**
* This method should be overriden in {@code CacheMode.MANUAL} to provide offline caching. The default
* implementation will work as expected in the {@code CacheMode.SMART} and {@code CacheMode.OFFLINE_FIRST} modes.
* @return the offline cached data or null/exception if unavailable
*/
protected InputStream getCachedData() throws IOException{
if(destinationFile != null) {
if(FileSystemStorage.getInstance().exists(destinationFile)) {
return FileSystemStorage.getInstance().openInputStream(destinationFile);
}
return null;
}
if(destinationStorage != null) {
if(Storage.getInstance().exists(destinationFile)) {
return Storage.getInstance().createInputStream(destinationFile);
}
return null;
}
String s = getCacheFileName();
if(FileSystemStorage.getInstance().exists(s)) {
return FileSystemStorage.getInstance().openInputStream(s);
}
return null;
}
/**
* Deletes the cache file if it exists, notice that this will not work for download files
*/
public void purgeCache() {
FileSystemStorage.getInstance().delete(getCacheFileName());
}
/**
* This callback is invoked on a 304 server response indicating the data in the server matches the result
* we currently have in the cache. This method can be overriden to detect this case
*/
protected void cacheUnmodified() throws IOException {
if(destinationFile != null || destinationStorage != null) {
if(hasResponseListeners() && !isKilled()) {
if(destinationFile != null) {
data = Util.readInputStream(FileSystemStorage.getInstance().openInputStream(destinationFile));
} else {
data = Util.readInputStream(Storage.getInstance().createInputStream(destinationStorage));
}
fireResponseListener(new NetworkEvent(this, data));
}
return;
}
InputStream is = FileSystemStorage.getInstance().openInputStream(getCacheFileName());
readResponse(is);
Util.cleanup(is);
}
/**
* Purges all locally cached files
*/
public static void purgeCacheDirectory() throws IOException {
Set<String> s = Preferences.keySet();
Iterator<String> i = s.iterator();
ArrayList<String> remove = new ArrayList<String>();
while(i.hasNext()) {
String ss = i.next();
if(ss.startsWith("cn1MSince") || ss.startsWith("cn1Etag")) {
remove.add(ss);
}
}
for(String ss : remove) {
Preferences.set(ss, null);
}
String root;
FileSystemStorage fs = FileSystemStorage.getInstance();
if(fs.hasCachesDir()) {
root = fs.getCachesDir() + "cn1ConCache/";
} else {
root = fs.getAppHomePath()+ "cn1ConCache/";
}
for(String ss : fs.listFiles(root)) {
fs.delete(ss);
}
}
private String getCacheFileName() {
String root;
if(FileSystemStorage.getInstance().hasCachesDir()) {
root = FileSystemStorage.getInstance().getCachesDir() + "cn1ConCache/";
} else {
root = FileSystemStorage.getInstance().getAppHomePath()+ "cn1ConCache/";
}
FileSystemStorage.getInstance().mkdir(root);
String fileName = Base64.encodeNoNewline(createRequestURL().getBytes()).replace('/', '-').replace('+', '_');
// limit file name length for portability: https://stackoverflow.com/questions/54644088/why-is-codenameone-rest-giving-me-file-name-too-long-error
if(fileName.length() > 255) {
String s = fileName.substring(0, 248);
int checksum = 0;
for(int iter = 248 ; iter < fileName.length() ; iter++) {
checksum += fileName.charAt(iter);
}
fileName = s + checksum;
}
return root + fileName;
}
/**
* This callback is used internally to check SSL certificates, only on platforms that require
* native callbacks for checking SSL certs. Currently only iOS requires this.
* @return True if the certificates checkout OK, or if the request doesn't require SSL cert checks.
* @deprecated For internal use only.
* @see NetworkManager#checkCertificatesNativeCallback(int)
*/
boolean checkCertificatesNativeCallback() {
if (!Util.getImplementation().checkSSLCertificatesRequiresCallbackFromNative()) {
//throw new RuntimeException("checkCertificates() can only be explicitly called on platforms that require native callbacks for checking certificates.");
return true;
}
if (!checkSSLCertificates) {
// If the request doesn't require checking SSL certificates, then this returns true.
// meaning that it checks out OK.
return true;
}
try {
checkSSLCertificates(getSSLCertificates());
if (shouldStop()) {
return false;
}
return true;
} catch (IOException ex) {
Log.e(ex);
return false;
}
}
/**
* Performs the actual network request on behalf of the network manager
*/
void performOperation() throws IOException {
performOperationComplete();
}
private Object _connection;
/**
* Performs the actual network request on behalf of the network manager
* @return true if the operation completed, false if the network request is scheduled to be retried.
*/
boolean performOperationComplete() throws IOException {
if(shouldStop()) {
return true;
}
if(cacheMode == CachingMode.OFFLINE || cacheMode == CachingMode.OFFLINE_FIRST) {
InputStream is = getCachedData();
if(is != null) {
readResponse(is);
Util.cleanup(is);
return true;
} else {
if(cacheMode == CachingMode.OFFLINE) {
responseCode = 404;
throw new IOException("File unavilable in cache");
}
}
}
CodenameOneImplementation impl = Util.getImplementation();
Object connection = null;
input = null;
output = null;
redirecting = false;
try {
String actualUrl = createRequestURL();
if(timeout > 0) {
connection = impl.connect(actualUrl, isReadRequest(), isPost() || isWriteRequest(), timeout);
} else {
connection = impl.connect(actualUrl, isReadRequest(), isPost() || isWriteRequest());
}
_connection = connection;
if(shouldStop()) {
return true;
}
initConnection(connection);
if(httpMethod != null) {
impl.setHttpMethod(connection, httpMethod);
}
if (isCookiesEnabled()) {
Vector v = impl.getCookiesForURL(actualUrl);
if(v != null) {
int c = v.size();
if(c > 0) {
StringBuilder cookieStr = new StringBuilder();
Cookie first = (Cookie)v.elementAt(0);
cookieSent(first);
cookieStr.append(first.getName());
cookieStr.append("=");
cookieStr.append(first.getValue());
for(int iter = 1 ; iter < c ; iter++) {
Cookie current = (Cookie)v.elementAt(iter);
cookieStr.append(";");
cookieStr.append(current.getName());
cookieStr.append("=");
cookieStr.append(current.getValue());
cookieSent(current);
}
impl.setHeader(connection, cookieHeader, initCookieHeader(cookieStr.toString()));
} else {
String s = initCookieHeader(null);
if(s != null) {
impl.setHeader(connection, cookieHeader, s);
}
}
} else {
String s = initCookieHeader(null);
if(s != null) {
impl.setHeader(connection, cookieHeader, s);
}
}
}
if (checkSSLCertificates && canGetSSLCertificates() &&
// For iOS only... it needs to use a callback from native code
// for checking the SSL certificates - otherwise it will send
// empty POST bodies.
!Util.getImplementation().checkSSLCertificatesRequiresCallbackFromNative()) {
sslCertificates = getSSLCertificatesImpl(connection, url);
checkSSLCertificates(sslCertificates);
if(shouldStop()) {
return true;
}
}
if(isWriteRequest()) {
progress = NetworkEvent.PROGRESS_TYPE_OUTPUT;
output = impl.openOutputStream(connection);
if(shouldStop()) {
return true;
}
if(NetworkManager.getInstance().hasProgressListeners() && output instanceof BufferedOutputStream) {
((BufferedOutputStream)output).setProgressListener(this);
}
if(requestBody != null) {
if(shouldWriteUTFAsGetBytes()) {
output.write(requestBody.getBytes("UTF-8"));
} else {
OutputStreamWriter w = new OutputStreamWriter(output, "UTF-8");
w.write(requestBody);
}
} else if (requestBodyData != null) {
requestBodyData.appendTo(output);
} else {
buildRequestBody(output);
}
if(shouldStop()) {
return true;
}
if(output instanceof BufferedOutputStream) {
((BufferedOutputStream)output).flushBuffer();
if(shouldStop()) {
return true;
}
}
}
timeSinceLastUpdate = System.currentTimeMillis();
responseCode = impl.getResponseCode(connection);
if(isCookiesEnabled()) {
String[] cookies = impl.getHeaderFields("Set-Cookie", connection);
if(cookies != null && cookies.length > 0){
ArrayList cook = new ArrayList();
int clen = cookies.length;
for(int iter = 0 ; iter < clen ; iter++) {
Cookie coo = parseCookieHeader(cookies[iter]);
if(coo != null) {
cook.add(coo);
cookieReceived(coo);
}
}
impl.addCookie((Cookie[])cook.toArray(new Cookie[cook.size()]));
}
}
if(responseCode == 304 && cacheMode != CachingMode.OFF) {
cacheUnmodified();
return true;
}
if(responseCode - 200 < 0 || responseCode - 200 > 100) {
readErrorCodeHeaders(connection);
// redirect to new location
if(followRedirects && (responseCode == 301 || responseCode == 302
|| responseCode == 303 || responseCode == 307)) {
String uri = impl.getHeaderField("location", connection);
if(!(uri.startsWith("http://") || uri.startsWith("https://"))) {
// relative URI's in the location header are illegal but some sites mistakenly use them
url = Util.relativeToAbsolute(url, uri);
} else {
url = uri;
}
if(requestArguments != null && url.indexOf('?') > -1) {
requestArguments.clear();
}
if((responseCode == 302 || responseCode == 303)){
if(this.post && shouldConvertPostToGetOnRedirect()) {
this.post = false;
setWriteRequest(false);
}
}
impl.cleanup(output);
impl.cleanup(connection);
connection = null;
output = null;
if(!onRedirect(url)){
redirecting = true;
retry();
return false;
}
return true;
}
responseErrorMessge = impl.getResponseMessage(connection);
handleErrorResponseCode(responseCode, responseErrorMessge);
if(!isReadResponseForErrors()) {
return true;
}
}
responseContentType = getHeader(connection, "Content-Type");
if(cacheMode == CachingMode.SMART || cacheMode == CachingMode.MANUAL
|| cacheMode == CachingMode.OFFLINE_FIRST) {
String last = getHeader(connection, "Last-Modified");
String etag = getHeader(connection, "ETag");
Preferences.set("cn1MSince" + createRequestURL(), last);
Preferences.set("cn1Etag" + createRequestURL(), etag);
}
readHeaders(connection);
contentLength = impl.getContentLength(connection);
timeSinceLastUpdate = System.currentTimeMillis();
progress = NetworkEvent.PROGRESS_TYPE_INPUT;
if(isReadRequest()) {
input = impl.openInputStream(connection);
if(shouldStop()) {
return true;
}
if(input instanceof BufferedInputStream) {
if(NetworkManager.getInstance().hasProgressListeners()) {
((BufferedInputStream)input).setProgressListener(this);
}
((BufferedInputStream)input).setYield(getYield());
}
if(!post && (cacheMode == CachingMode.SMART || cacheMode == CachingMode.OFFLINE_FIRST)
&& destinationFile == null && destinationStorage == null) {
byte[] d = Util.readInputStream(input);
OutputStream os = FileSystemStorage.getInstance().openOutputStream(getCacheFileName());
os.write(d);
os.close();