-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCBHelper.java
More file actions
1405 lines (1228 loc) · 62 KB
/
CBHelper.java
File metadata and controls
1405 lines (1228 loc) · 62 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
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) 2013 Cloudbase.io Limited
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License
is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
or implied. See the License for the specific language governing permissions and limitations under
the License.
*/
package com.cloudbase;
import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.cloudbase.datacommands.CBDataAggregationCommand;
import com.cloudbase.datacommands.CBSearchCondition;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
/*! \mainpage cloudbase.io Java Helper Class Reference
*
* \section intro_sec Introduction
*
* Copyright (c) 2013 Cloudbase.io Limited
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.<br/><br/>
*
* \section install_sec Getting Started
*
* The cloudbase.io Java helper class compiles to .jar library.<br/><br/>
* Make sure the library is included in your project. There are two places where we need to call it from the
* project properties<br/>
*/
/**
* The main CBHelper class. All of the methods interacting with the cloudbase.io APIs are part of this class.
* <br/>
* This class requires the <strong>appCode</strong>, <strong>appSecret</strong> and <strong>password</strong>
* properties set. appCode and appSecret are handed to the class in the constructor and the password can be
* set using the <strong>setPassword</strong> setter.
* <br/>
* This library depends on the Gson library by google. This is used to serialise and de-serialise objects to be
* sent to the APIs. This library was built on top of the Gson 2.2.1. Make sure the jar file is available in your
* classpath
* @author Stefano Buliani
*/
public class CBHelper implements CBHelperResponder {
// application settings to connect to cloudbase.io
private String appCode;
private String appSecret;
private String password;
// whether to use the https apis. This should be set to "true" by default.
private boolean https;
// whether the APIs require user authentication. and the current application
// username and password
private boolean userAuthentication;
private String authUsername;
private String authPassword;
// The current location variable to be attached to requests to the CloudBase apis
private boolean useLocation;
private CBLocation currentLocation;
private String sessionId;
private CBDeviceInfo deviceInfo;
// this is used when downloading attachments from the CloudBase - temporary files
// are saved in the application files folder and handed back to the application
private String temporaryFilesPath;
private CBHelperResponder defaultQueueResponder;
private boolean debugMode;
private String apiURL = "api.cloudbase.io";
private static final String defaultLogCategory = "DEFAULT";
public static final String logTag = "CBHELPER";
private boolean deviceRegistered;
private static Gson jsonParser = new GsonBuilder().disableHtmlEscaping().create();//new Gson();
/**
* Creates a new instance of CBHelper and initializes the main properties to their default values.
* @param code The application code generated by cloudbase.io when the application is registered (test-application)
* @param uniq The unique code generated by cloudbase.io when the application is registered (8a159fe6e4493d4b9a56d4aa580953a2)
* @param activity The main activity from the application. This is used to get Context variables, specifically the Cache directory
* @throws Exception
*/
public CBHelper(String code, String uniq, CBDeviceInfo info)
{
this.appCode = code;
this.appSecret = uniq;
this.userAuthentication = false;
this.https = true;
this.debugMode = false;
this.deviceInfo = info;
this.deviceRegistered = false;
this.temporaryFilesPath = info.getTemporaryFilesPath();
//Log.d(logTag, "CBHelper initialized");
}
/**
* Logs an event to the cloudbase.io application log
* @param logLine The content of the line to be logged
*/
public void logEvent(String logLine) {
this.log(logLine, CBLogLevel.EVENT, null, null, false);
}
/**
* Logs an event to the cloudbase.io application log
* @param logLine The content of the line to be Logged
* @param category The category of the log line. This is a free text string and can be used to separate different
* sections of the application and events
*/
public void logEvent(String logLine, String category) {
this.log(logLine, CBLogLevel.EVENT, category, null, false);
}
/**
* Logs an event to the cloudbase.io application log
* @param logLine The content of the line to be Logged
* @param category The category of the log line. This is a free text string and can be used to separate different
* sections of the application and events
* @param responder A responder to handle the return value from the cloudbase.io APIs. This is an optional parameter
* and can be sent as null
*/
public void logEvent(String logLine, String category, CBHelperResponder responder) {
this.log(logLine, CBLogLevel.EVENT, category, responder, false);
}
/**
* Logs a fatal exception to the cloudbase.io application log
* @param logLine The content of the line to be logged
*/
public void logFatal(String logLine) {
this.log(logLine, CBLogLevel.FATAL, null, null, false);
}
/**
* Logs a fatal exception to the cloudbase.io application log
* @param logLine The content of the line to be logged
* @param category The category of the log line. This is a free text string and can be used to separate different
* sections of the application and events
*/
public void logFatal(String logLine, String category) {
this.log(logLine, CBLogLevel.FATAL, category, null, false);
}
/**
* Logs a fatal exception to the cloudbase.io application log
* @param logLine The content of the line to be logged
* @param category The category of the log line. This is a free text string and can be used to separate different
* sections of the application and events
* @param responder A responder to handle the return value from the cloudbase.io APIs. This is an optional parameter
* and can be sent as null
*/
public void logFatal(String logLine, String category, CBHelperResponder responder) {
this.log(logLine, CBLogLevel.FATAL, category, responder, false);
}
/**
* Logs an error to the cloudbase.io application log
* @param logLine The content of the line to be logged
*/
public void logError(String logLine) {
this.log(logLine, CBLogLevel.ERROR, null, null, false);
}
/**
* Logs an error to the cloudbase.io application log
* @param logLine The content of the line to be logged
* @param category The category of the log line. This is a free text string and can be used to separate different
* sections of the application and events
*/
public void logError(String logLine, String category) {
this.log(logLine, CBLogLevel.ERROR, category, null, false);
}
/**
* Logs an error to the cloudbase.io application log
* @param logLine The content of the line to be logged
* @param category The category of the log line. This is a free text string and can be used to separate different
* sections of the application and events
* @param responder A responder to handle the return value from the cloudbase.io APIs. This is an optional parameter
* and can be sent as null
*/
public void logError(String logLine, String category, CBHelperResponder responder) {
this.log(logLine, CBLogLevel.ERROR, category, responder, false);
}
/**
* Logs a warning to the cloudbase.io application log
* @param logLine The content of the line to be logged
*/
public void logWarning(String logLine) {
this.log(logLine, CBLogLevel.WARNING, null, null, false);
}
/**
* Logs a warning to the cloudbase.io application log
* @param logLine The content of the line to be logged
* @param category The category of the log line. This is a free text string and can be used to separate different
* sections of the application and events
*/
public void logWarning(String logLine, String category) {
this.log(logLine, CBLogLevel.WARNING, category, null, false);
}
/**
* Logs a warning to the cloudbase.io application log
* @param logLine The content of the line to be logged
* @param category The category of the log line. This is a free text string and can be used to separate different
* sections of the application and events
* @param responder A responder to handle the return value from the cloudbase.io APIs. This is an optional parameter
* and can be sent as null
*/
public void logWarning(String logLine, String category, CBHelperResponder responder) {
this.log(logLine, CBLogLevel.WARNING, category, responder, false);
}
/**
* Logs an information message to the cloudbase.io application log
* @param logLine The content of the line to be logged
*/
public void logInfo(String logLine) {
this.log(logLine, CBLogLevel.INFO, null, null, false);
}
/**
* Logs an information message to the cloudbase.io application log
* @param logLine The content of the line to be logged
* @param category The category of the log line. This is a free text string and can be used to separate different
* sections of the application and events
*/
public void logInfo(String logLine, String category) {
this.log(logLine, CBLogLevel.INFO, category, null, false);
}
/**
* Logs an information message to the cloudbase.io application log
* @param logLine The content of the line to be logged
* @param category The category of the log line. This is a free text string and can be used to separate different
* sections of the application and events
* @param responder A responder to handle the return value from the cloudbase.io APIs. This is an optional parameter
* and can be sent as null
*/
public void logInfo(String logLine, String category, CBHelperResponder responder) {
this.log(logLine, CBLogLevel.INFO, category, responder, false);
}
/**
* Logs a debug message to the cloudbase.io application log
* @param logLine The content of the line to be logged
*/
public void logDebug(String logLine) {
this.log(logLine, CBLogLevel.DEBUG, null, null, false);
}
/**
* Logs a debug message to the cloudbase.io application log
* @param logLine The content of the line to be logged
* @param category The category of the log line. This is a free text string and can be used to separate different
* sections of the application and events
*/
public void logDebug(String logLine, String category) {
this.log(logLine, CBLogLevel.DEBUG, category, null, false);
}
/**
* Logs a debug message to the cloudbase.io application log
* @param logLine The content of the line to be logged
* @param category The category of the log line. This is a free text string and can be used to separate different
* sections of the application and events
* @param responder A responder to handle the return value from the cloudbase.io APIs. This is an optional parameter
* and can be sent as null
*/
public void logDebug(String logLine, String category, CBHelperResponder responder) {
this.log(logLine, CBLogLevel.DEBUG, category, responder, false);
}
/**
* Send a line to the log on the cloudbase.io application log.
*
* @param logLine The content of the log line
* @param level The severity of the log line, a <strong>CBLogLevel</strong> value
* @param category The category of the log line. This is a free text string and can be used to separate different
* sections of the application and events
*/
public void log(String logLine, CBLogLevel level, String category) {
this.log(logLine, level, category, null, false);
}
/**
* Send a line to the log on the cloudbase.io application log.
*
* @param logLine The content of the log line
* @param level The severity of the log line, a <strong>CBLogLevel</strong> value
* @param category The category of the log line. This is a free text string and can be used to separate different
* sections of the application and events
* @param responder A responder to handle the return value from the cloudbase.io APIs. This is an optional parameter
* and can be sent as null
* @param shouldQueue whether the request should be queued if connectivity is not available
*/
public void log(String logLine, CBLogLevel level, String category, CBHelperResponder responder, boolean shouldQueue) {
String url = this.getUrl() + this.appCode + "/log";
// Create the log object
Hashtable<String, String> logData = new Hashtable<String, String>();
logData.put("category", (category == null?CBHelper.defaultLogCategory:category));
logData.put("level", level.toString());
logData.put("device_name", this.deviceInfo.getDeviceName());
logData.put("device_model", this.deviceInfo.getDeviceModel());
logData.put("log_line", logLine);
Hashtable<String, String> preparedPost = this.preparePostParams(logData, null);
this.startRequest(url, "log", null, preparedPost, null, responder, shouldQueue);
}
/**
* Sends cloudbase.io the name of the newly opened screen. This data is used to then generate the usage
* flow analytics and show how people interact with your application
* This API request will always be queued
* @param screenName The unique name assigned to the opened view
*/
public void logNavigation(String screenName) {
String url = this.getUrl() + this.appCode + "/lognavigation";
Hashtable<String, String> logData = new Hashtable<String, String>();
logData.put("session_id", this.sessionId);
logData.put("screen_name", screenName);
Hashtable<String, String> preparedPost = this.preparePostParams(logData, null);
this.startRequest(url, "log", null, preparedPost, null, null, true);
}
/**
* Inserts the given object in a cloudbase.io collection. If the collection does not exist it is automatically created.
* Similarly if the data structure of the given object is different from documents already present in the collection
* the structure is automatically altered to accommodate the new object.
* The system will automatically try to serialize any object sent to this function. However, we recommend you use
* the simplest possible objects to hold data if not a Map or Array directly.
* Once the call to the APIs is completed the responder is called.
* This API request will not be queued
* @param document The object to be inserted
* @param collection The name of the collection the document should be inserted into
*/
public void insertDocument(Object document, String collection) {
insertDocument(document, collection, null, null);
}
/**
* Inserts the given object in a cloudbase.io collection. If the collection does not exist it is automatically created.
* Similarly if the data structure of the given object is different from documents already present in the collection
* the structure is automatically altered to accommodate the new object.
* The system will automatically try to serialize any object sent to this function. However, we recommend you use
* the simplest possible objects to hold data if not a Map or Array directly.
* Once the call to the APIs is completed the responder is called.
* @param document The object to be inserted
* @param collection The name of the collection the document should be inserted into
* @param shouldQueue whether the request should be queued if connectivity is not available
*/
public void insertDocument(Object document, String collection, boolean shouldQueue) {
insertDocument(document, collection, null, null, shouldQueue);
}
/**
* Inserts the given object in a cloudbase.io collection. If the collection does not exist it is automatically created.
* Similarly if the data structure of the given object is different from documents already present in the collection
* the structure is automatically altered to accommodate the new object.
* The system will automatically try to serialize any object sent to this function. However, we recommend you use
* the simplest possible objects to hold data if not a Map or Array directly.
* Once the call to the APIs is completed the responder is called.
* This API request will not be queued
* @param document The object to be inserted
* @param collection The name of the collection the document should be inserted into
* @param responder The CBHelperResponder object to handle the response from the cloudbase.io APIs
*/
public void insertDocument(Object document, String collection, CBHelperResponder responder) {
insertDocument(document, collection, null, responder);
}
/**
* Inserts the given object in a cloudbase.io collection. If the collection does not exist it is automatically created.
* Similarly if the data structure of the given object is different from documents already present in the collection
* the structure is automatically altered to accommodate the new object.
* The system will automatically try to serialize any object sent to this function. However, we recommend you use
* the simplest possible objects to hold data if not a Map or Array directly.
* Once the call to the APIs is completed the responder is called.
* @param document The object to be inserted
* @param collection The name of the collection the document should be inserted into
* @param responder The CBHelperResponder object to handle the response from the cloudbase.io APIs
* @param shouldQueue whether the request should be queued if connectivity is not available
*/
public void insertDocument(Object document, String collection, CBHelperResponder responder, boolean shouldQueue) {
insertDocument(document, collection, null, responder, shouldQueue);
}
/**
* Inserts the given object in a cloudbase.io collection. If the collection does not exist it is automatically created.
* Similarly if the data structure of the given object is different from documents already present in the collection
* the structure is automatically altered to accommodate the new object.
* The system will automatically try to serialize any object sent to this function. However, we recommend you use
* the simplest possible objects to hold data if not a Map or Array directly.
* Once the call to the APIs is completed the responder is called.
* This API request will not be queued
* @param document The object to be inserted
* @param collection The name of the collection the document should be inserted into
* @param attachments An ArrayList of of File objects to be attached to the record. File IDs will be stored in the additional column
* <strong>cb_files</strong>
* @param responder The CBHelperResponder object to handle the response from the cloudbase.io APIs
*/
public void insertDocument(Object document, String collection, ArrayList<File> attachments, CBHelperResponder responder) {
this.insertDocument(document, collection, attachments, responder, false);
}
@SuppressWarnings("unchecked")
/**
* Inserts the given object in a cloudbase.io collection. If the collection does not exist it is automatically created.
* Similarly if the data structure of the given object is different from documents already present in the collection
* the structure is automatically altered to accommodate the new object.
* The system will automatically try to serialize any object sent to this function. However, we recommend you use
* the simplest possible objects to hold data if not a Map or Array directly.
* Once the call to the APIs is completed the responder is called.
* @param document The object to be inserted
* @param collection The name of the collection the document should be inserted into
* @param attachments An ArrayList of of File objects to be attached to the record. File IDs will be stored in the additional column
* <strong>cb_files</strong>
* @param responder The CBHelperResponder object to handle the response from the cloudbase.io APIs
* @param shouldQueue whether the request should be queued if connectivity is not available
*/
public void insertDocument(Object document, String collection, ArrayList<File> attachments, CBHelperResponder responder, boolean shouldQueue) {
// We need to insert a List as the cloudbase.io APIs expect an array of objects to the
// insert APIs - this way we can insert multiple objects at the same time. If it is not a List
// then create a new List and insert the given object in it.
List<Object> finalDocument;
if (document instanceof List)
finalDocument = (List<Object>)document;
else {
finalDocument = new ArrayList<Object>();
finalDocument.add(document);
}
String url = this.getUrl() + this.appCode + "/" + collection + "/insert";
Hashtable<String, String> preparedPost = this.preparePostParams(finalDocument, null);
this.startRequest(url, "data", null, preparedPost, attachments, responder, shouldQueue);
}
/**
* Updates a document in a collection in the Cloud Database. The documents to update are identified using the CBSearchCondition
* parameter to the method.
* @param document The new object to update
* @param cond The search condition to match the documents to be updated in the Cloud Database
* @param collection The name of the collection containing the documents to update
* @param isUpsert Whether this is an upsert request (if the document doesn't exist then insert)
* @param attachments An ArrayList of File objects to be attached to the new document
* @param shouldQueue Whether the request should be queued
* @throws Exception
*/
public void updateDocument(Object document, CBSearchCondition cond, String collection, boolean isUpsert, ArrayList<File> attachments) throws Exception {
this.updateDocument(document, cond, collection, isUpsert, attachments, null, false);
}
/**
* Updates a document in a collection in the Cloud Database. The documents to update are identified using the CBSearchCondition
* parameter to the method.
* @param document The new object to update
* @param cond The search condition to match the documents to be updated in the Cloud Database
* @param collection The name of the collection containing the documents to update
* @param isUpsert Whether this is an upsert request (if the document doesn't exist then insert)
* @param attachments An ArrayList of File objects to be attached to the new document
* @param responder A reponder to receive the cloudbase.io response
* @param shouldQueue Whether the request should be queued
* @throws Exception
*/
public void updateDocument(Object document, CBSearchCondition cond, String collection, boolean isUpsert, ArrayList<File> attachments, CBHelperResponder responder, boolean shouldQueue) throws Exception {
JsonElement tmpElement = CBHelper.jsonParser.toJsonTree(document);
if ( !tmpElement.isJsonObject() ) {
throw new Exception("Update is allowed only on objects");
}
JsonObject tmpObject = (JsonObject)tmpElement;
tmpObject.add("cb_search_key", CBHelper.jsonParser.toJsonTree(cond.serializeConditions(cond)));
if ( isUpsert ) {
tmpObject.addProperty("cb_upsert", 1);
}
String url = this.getUrl() + this.appCode + "/" + collection + "/update";
Hashtable<String, String> preparedPost = this.preparePostParams(tmpObject, null);
this.startRequest(url, "data", null, preparedPost, attachments, responder, shouldQueue);
}
/**
* Returns all of the documents in the given collection
* This API request will not be queued
* @param collection The name of the collection to run the search over
* @param responder The CBHelperResponder object to manage the data returned from the cloudbase.io APIs
*/
public void searchDocument(String collection, CBHelperResponder responder) {
this.searchDocument(collection, null, responder);
}
/**
* Returns all of the documents in the given collection
* @param collection The name of the collection to run the search over
* @param responder The CBHelperResponder object to manage the data returned from the cloudbase.io APIs
* @param shouldQueue whether the request should be queued if connectivity is not available
*/
public void searchDocument(String collection, CBHelperResponder responder, boolean shouldQueue) {
this.searchDocument(collection, null, responder, shouldQueue);
}
/**
* Runs a search over a collection with the given criteria. The documents matching the search criteria are then
* returned to the given responder object
* This API request will not be queued
* @param collection The name of the collection to run the search over
* @param cond A CBSearchCondition object containing the criteria for this search. This object can be null, in which case
* all of the documents in the collection will be returned
* @param responder The CBHelperResponder object to manage the data returned from the cloudbase.io APIs
*/
public void searchDocument(String collection, CBSearchCondition cond, CBHelperResponder responder) {
this.searchDocument(collection, cond, responder, false);
}
/**
* Runs a search over a collection with the given criteria. The documents matching the search criteria are then
* returned to the given responder object
* @param collection The name of the collection to run the search over
* @param cond A CBSearchCondition object containing the criteria for this search. This object can be null, in which case
* all of the documents in the collection will be returned
* @param responder The CBHelperResponder object to manage the data returned from the cloudbase.io APIs
* @param shouldQueue whether the request should be queued if connectivity is not available
*/
@SuppressWarnings("rawtypes")
public void searchDocument(String collection, CBSearchCondition cond, CBHelperResponder responder, boolean shouldQueue) {
// if we have no conditions for the request then send an empty Map - the cloudbase.io APIs
// will then return all of the objects in the collection
Map serializedConditions = null;
if (cond != null)
serializedConditions = cond.serializeConditions();
else {
serializedConditions = new HashMap();
}
String url = this.getUrl() + this.appCode + "/" + collection + "/search";
Hashtable<String, String> preparedPost = this.preparePostParams(serializedConditions, null);
this.startRequest(url, "data", null, preparedPost, null, responder, shouldQueue);
}
/**
* Runs a search over a collection and applies the given list of aggregation commands to the output.
* This API request will not be queued
* @param collection The name of the collection to run the search over
* @param aggregateConditions A List of CBDataAggregationCommand objects
* @param handler a block of code to be executed once the request is completed
*/
public void searchDocumentAggregate(String collection, List<CBDataAggregationCommand> aggregateConditions, CBHelperResponder responder) {
this.searchDocumentAggregate(collection, aggregateConditions, responder, false);
}
/**
* Runs a search over a collection and applies the given list of aggregation commands to the output.
* @param collection The name of the collection to run the search over
* @param aggregateConditions A List of CBDataAggregationCommand objects
* @param handler a block of code to be executed once the request is completed
* @param shouldQueue whether the request should be queued if connectivity is not available
*/
public void searchDocumentAggregate(String collection, List<CBDataAggregationCommand> aggregateConditions, CBHelperResponder responder, boolean shouldQueue) {
List<Map<String, Object>> serializedAggregateConditions = new ArrayList<Map<String, Object>>();
for (CBDataAggregationCommand curComm : aggregateConditions) {
Map<String, Object> curSerializedCondition = new HashMap<String, Object>();
curSerializedCondition.put(curComm.getCommandType().toString(), curComm.serializeAggregateConditions());
serializedAggregateConditions.add(curSerializedCondition);
}
String url = this.getUrl() + this.appCode + "/" + collection + "/aggregate";
HashMap<String, Object> paramsToPrepare = new HashMap<String, Object>();
paramsToPrepare.put("cb_aggregate_key", serializedAggregateConditions);
Hashtable<String, String> preparedPost = this.preparePostParams(paramsToPrepare, null);
this.startRequest(url, "data", null, preparedPost, null, responder, shouldQueue);
}
/**
* Downloads a file matching the given file id. The file id comes from the cloudbase.io cb_files field on collections
* created when documents are inserted with file attachments.
* The data is downloaded and a java.io.File object is made available in the CBHelperResponse class called downloadedFile
* This API request will not be queued
* @param fileId the cloudbase.io generated file id
* @param responder The object to handle the response object
*/
public void downloadFile(String fileId, CBHelperResponder responder) {
this.downloadFile(fileId, responder, false);
}
/**
* Downloads a file matching the given file id. The file id comes from the cloudbase.io cb_files field on collections
* created when documents are inserted with file attachments.
* The data is downloaded and a java.io.File object is made available in the CBHelperResponse class called downloadedFile
* @param fileId the cloudbase.io generated file id
* @param responder The object to handle the response object
* @param shouldQueue whether the request should be queued if connectivity is not available
*/
public void downloadFile(String fileId, CBHelperResponder responder, boolean shouldQueue) {
String url = this.getUrl() + this.appCode + "/file/" + fileId;
Hashtable<String, String> preparedPost = this.preparePostParams(null, null);
this.startRequest(url, "download", fileId, preparedPost, null, responder, shouldQueue);
}
/**
* Subscribes the current device, with the Key received from Google's C2DM or GCM to a notification channel. By default all
* devices are automatically subscribed to the "All" channel.
* This API request will not be queued
* @param deviceKey The registration id received from the Google's C2DM/GCM
* @param channel The name of the channel to subscribe to. If the given channel does not exist then it is automatically
* created
* @param isC2DM Whether to use the C2DM or the GCM network to send the push notification
*/
public void notificationSubscribeDevice(String deviceKey, String channel, boolean isC2DM) {
notificationSubscribeDevice(deviceKey, channel, isC2DM, null);
}
/**
* Subscribes the current device, with the Key received from Google's C2DM or GCM to a notification channel. By default all
* devices are automatically subscribed to the "All" channel.
* This API request will not be queued
* @param deviceKey deviceKey The registration id received from the Google's C2DM/GCM
* @param channel The name of the channel to subscribe to. If the given channel does not exist then it is automatically
* @param isC2DM Whether to use the C2DM or the GCM network to send the push notification
* @param responder A CBHelperResponder object to handle the response from the cloudbase.io APIs
*/
public void notificationSubscribeDevice(String deviceKey, String channel, boolean isC2DM, CBHelperResponder responder) {
this.notificationSubscribeDevice(deviceKey, channel, responder, isC2DM, false);
}
/**
* Subscribes the current device, with the Key received from Google's C2DM or GCM to a notification channel. By default all
* devices are automatically subscribed to the "All" channel.
* @param deviceKey deviceKey The registration id received from the Google's C2DM/GCM
* @param channel The name of the channel to subscribe to. If the given channel does not exist then it is automatically
* @param responder A CBHelperResponder object to handle the response from the cloudbase.io APIs
* @param isC2DM Whether to use the C2DM or the GCM network to send the push notification
* @param shouldQueue whether the request should be queued if connectivity is not available
*/
public void notificationSubscribeDevice(String deviceKey, String channel, CBHelperResponder responder, boolean isC2DM, boolean shouldQueue) {
Map<String, String> subForm = new HashMap<String, String>();
subForm.put("action", "subscribe");
subForm.put("device_key", deviceKey);
subForm.put("device_network", "and");
subForm.put("android_network", (isC2DM?"c2dm":"gcm"));
subForm.put("channel", channel);
String url = this.getUrl() + this.appCode + "/notifications-register";
Hashtable<String, String> preparedPost = this.preparePostParams(subForm, null);
this.startRequest(url, "notifications-register", null, preparedPost, null, responder, shouldQueue);
}
/**
* Unsubscribes the current device from the given notification channel
* This API request will not be queued
* @param deviceKey deviceKey The registration id received from the Google's C2DM
* @param channel The name of the channel to subscribe to. If the given channel does not exist then it is automatically
*/
public void notificationUnsubscribeDevice(String deviceKey, String channel) {
notificationUnsubscribeDevice(deviceKey, channel, null);
}
/**
* Unsubscribes the current device from the given notification channel
* This API request will not be queued
* @param deviceKey deviceKey The registration id received from the Google's C2DM
* @param channel The name of the channel to subscribe to. If the given channel does not exist then it is automatically
* @param responder A CBHelperResponder object to handle the response from the cloudbase.io server
*/
public void notificationUnsubscribeDevice(String deviceKey, String channel, CBHelperResponder responder) {
this.notificationUnsubscribeDevice(deviceKey, channel, responder, false);
}
/**
* Unsubscribes the current device from the given notification channel
* @param deviceKey deviceKey The registration id received from the Google's C2DM
* @param channel The name of the channel to subscribe to. If the given channel does not exist then it is automatically
* @param responder A CBHelperResponder object to handle the response from the cloudbase.io server
* @param shouldQueue whether the request should be queued if connectivity is not available
*/
public void notificationUnsubscribeDevice(String deviceKey, String channel, CBHelperResponder responder, boolean shouldQueue) {
Map<String, String> subForm = new HashMap<String, String>();
subForm.put("action", "unsubscribe");
subForm.put("device_key", deviceKey);
subForm.put("device_network", "and");
subForm.put("channel", channel);
String url = this.getUrl() + this.appCode + "/notifications-register";
Hashtable<String, String> preparedPost = this.preparePostParams(subForm, null);
this.startRequest(url, "notifications-register", null, preparedPost, null, responder, shouldQueue);
}
/**
* Pushes a notification to the given channels<br/><br/>
* Device notifications must be enabled in the application configuration on cloudbase.io for this to work.
* @param notificationText The content of the notification text
* @param channels An ArrayList of channel names (String) to be notified
* @param shouldQueue whether the request should be queued if connectivity is not available
*/
public void sendNotification(String notificationText, ArrayList<String> channels, boolean shouldQueue) {
for (String channel : channels) {
sendNotification(notificationText, channel, shouldQueue);
}
}
/**
* Pushes a notification to the given channel. If channel is null then the default "All" channel will be used<br/><br/>
* Device notifications must be enabled in the application configuration on cloudbase.io for this to work.
* @param notificationText The full text for the notification
* @param channel The channel this notification should be sent to
* @param shouldQueue whether the request should be queued if connectivity is not available
*/
public void sendNotification(String notificationText, String channel, boolean shouldQueue) {
Map<String, String> subForm = new HashMap<String, String>();
subForm.put("channel", channel);
subForm.put("cert_type", "production");
subForm.put("alert", notificationText);
subForm.put("badge", "");
subForm.put("sound", "");
String url = this.getUrl() + this.appCode + "/notifications";
Hashtable<String, String> preparedPost = this.preparePostParams(subForm, null);
this.startRequest(url, "notifications", null, preparedPost, null, null, shouldQueue);
}
/**
* Pushes a notification to a list of channels using the Google Cloud Messaging system
* @param notificationText The text for the notification
* @param tickerText The ticker text for the GCM message
* @param contentTitle The content title for the GCM message
* @param contentText The text for the GCM message
* @param channel The channel this notification should be sent to
* @param shouldQueue whether the request should be queued if connectivity is not available
*/
public void sendGCMNotification(String notificationText, String tickerText, String contentTitle, String contentText, ArrayList<String> channels, boolean shouldQueue) {
for (String channel : channels) {
sendGCMNotification(notificationText, tickerText, contentTitle, contentText, channel, shouldQueue);
}
}
/**
* Pushes a notification using the Google Cloud Messaging system
* @param notificationText The text for the notification
* @param tickerText The ticker text for the GCM message
* @param contentTitle The content title for the GCM message
* @param contentText The text for the GCM message
* @param channel The channel this notification should be sent to
* @param shouldQueue whether the request should be queued if connectivity is not available
*/
public void sendGCMNotification(String notificationText, String tickerText, String contentTitle, String contentText, String channel, boolean shouldQueue) {
Map<String, String> subForm = new HashMap<String, String>();
subForm.put("channel", channel);
subForm.put("cert_type", "production");
subForm.put("alert", notificationText);
subForm.put("gcm_ticker_text", tickerText);
subForm.put("gcm_content_title", contentTitle);
subForm.put("gcm_content_text", contentText);
String url = this.getUrl() + this.appCode + "/notifications";
Hashtable<String, String> preparedPost = this.preparePostParams(subForm, null);
this.startRequest(url, "notifications", null, preparedPost, null, null, shouldQueue);
}
/**
* Sends an email to the specified recipient using the given template.
* This API request will not be queued
* @param templateCode The code of the template created in the control panel on cloudbase.io
* @param recipient The email address of the recipient of the email
* @param subject The subject of the email
* @param vars A Map of variables to fill the template.
*/
public void sendEmail(String templateCode, String recipient, String subject, Map<String, String> vars) {
this.sendEmail(templateCode, recipient, subject, vars, false);
}
/**
* Sends an email to the specified recipient using the given template.
* @param templateCode The code of the template created in the control panel on cloudbase.io
* @param recipient The email address of the recipient of the email
* @param subject The subject of the email
* @param vars A Map of variables to fill the template.
* @param shouldQueue whether the request should be queued if connectivity is not available
*/
public void sendEmail(String templateCode, String recipient, String subject, Map<String, String> vars, boolean shouldQueue) {
Map<String, String> subForm = new HashMap<String, String>();
subForm.put("template_code", templateCode);
subForm.put("recipient", recipient);
subForm.put("subject", subject);
subForm.put("variables", CBHelper.jsonParser.toJson(vars));
String url = this.getUrl() + this.appCode + "/email";
Hashtable<String, String> preparedPost = this.preparePostParams(subForm, null);
this.startRequest(url, "email", null, preparedPost, null, null, shouldQueue);
}
/**
* Executes a CloudFunction on the cloudbase.io servers on demand. Results will be ignored.
* This API request will not be queued
* @param functionCode The name of the function to be executed
*/
public void runCloudFunction(String functionCode) {
runCloudFunction(functionCode, null, null);
}
/**
* Executes a CloudFunction on the coudbase.io servers on demand. The additional parameters will be accessible
* to the function like standard HTTP POST parameters. Results will be ignored.
* This API request will not be queued
* @param functionCode The name of the function to be executed
* @param params The list of parameters to be passed to the function
*/
public void runCloudFunction(String functionCode, Map<String, String> params) {
runCloudFunction(functionCode, params, null);
}
/**
* Executes a CloudFunction on the coudbase.io servers on demand. The additional parameters will be accessible
* to the function like standard HTTP POST parameters. Results and output are parsed and handed to the responder.
* This API request will not be queued
* @param functionCode The name of the function to be executed
* @param params The list of parameters to be passed to the function
* @param responder The CBHelperResponder to handle the response value
*/
public void runCloudFunction(String functionCode, Map<String, String> params, CBHelperResponder responder) {
this.runCloudFunction(functionCode, params, responder, false);
}
/**
* Executes a CloudFunction on the coudbase.io servers on demand. The additional parameters will be accessible
* to the function like standard HTTP POST parameters. Results and output are parsed and handed to the responder.
* @param functionCode The name of the function to be executed
* @param params The list of parameters to be passed to the function
* @param responder The CBHelperResponder to handle the response value
* @param shouldQueue whether the request should be queued if connectivity is not available
*/
public void runCloudFunction(String functionCode, Map<String, String> params, CBHelperResponder responder, boolean shouldQueue) {
String url = this.getUrl() + this.appCode + "/cloudfunction/" + functionCode;
Hashtable<String, String> preparedPost = this.preparePostParams(Collections.EMPTY_MAP, params);
this.startRequest(url, "cloudfunction", null, preparedPost, null, responder, shouldQueue);
}
/**
* Executes a Shared API on the coudbase.io servers on demand. The additional parameters will be accessible
* to the function like standard HTTP POST parameters. Results and output are parsed and handed to the responder.
* @param apiCode The unique identifier for the Shared API
* @param password The password to access the Shared API if necessary
* @param params The list of parameters to be passed to the function
* @param responder The CBHelperResponder to handle the response value
*/
public void runSharedApi(String apiCode, String password, Map<String, String> params, CBHelperResponder responder) {
this.runSharedApi(apiCode, password, params, responder, false);
}
/**
* Executes a Shared API on the coudbase.io servers on demand. The additional parameters will be accessible
* to the function like standard HTTP POST parameters. Results and output are parsed and handed to the responder.
* @param apiCode The unique identifier for the Shared API
* @param password The password to access the Shared API if necessary
* @param params The list of parameters to be passed to the function
* @param responder The CBHelperResponder to handle the response value
* @param shouldQueue whether the request should be queued if connectivity is not available
*/
public void runSharedApi(String apiCode, String password, Map<String, String> params, CBHelperResponder responder, boolean shouldQueue) {
String url = this.getUrl() + this.appCode + "/shared/" + apiCode;
if ( password != null && !password.equals("") ) {
params.put("cb_shared_password", password);
}
Hashtable<String, String> preparedPost = this.preparePostParams(Collections.EMPTY_MAP, params);
this.startRequest(url, "shared-api", null, preparedPost, null, responder, shouldQueue);
}
/**
* Executes of the cloudbase.io applets on demand.
* Results and output are parsed and handed to the responder.
* This API request will not be queued
* @param appletCode The name of the applet to be executed
* @param params The list of parameters to be passed to the applet
* @param responder The CBHelperResponder to handle the response value
*/
public void runApplet(String appletCode, Map<String, String> params, CBHelperResponder responder) {
this.runApplet(appletCode, params, responder, false);
}
/**
* Executes of the cloudbase.io applets on demand.
* Results and output are parsed and handed to the responder.
* @param appletCode The name of the applet to be executed
* @param params The list of parameters to be passed to the applet
* @param responder The CBHelperResponder to handle the response value
* @param shouldQueue whether the request should be queued if connectivity is not available
*/
public void runApplet(String appletCode, Map<String, String> params, CBHelperResponder responder, boolean shouldQueue) {
String url = this.getUrl() + this.appCode + "/applet/" + appletCode;
Hashtable<String, String> preparedPost = this.preparePostParams(Collections.EMPTY_MAP, params);
this.startRequest(url, "applet", null, preparedPost, null, responder, shouldQueue);
}
/**
* Initiates a transaction with PayPal by sending the payment details and retrieving a token
* and an express checkout url. The url returned should be then opened in a browser window.
* This API request will not be queued
* @param purchaseDetails a populated CBPayPalBill object
* @param isLiveEnvironment whether we are using the production or sandbox paypal environments
* @param responder a responder to handle the returned PayPal token and submission url
*/
public void preparePayPalPurchase(CBPayPalBill purchaseDetails, boolean isLiveEnvironment, CBHelperResponder responder) {
this.preparePayPalPurchase(purchaseDetails, isLiveEnvironment, responder, false);
}
/**
* Initiates a transaction with PayPal by sending the payment details and retrieving a token
* and an express checkout url. The url returned should be then opened in a browser window.
* @param purchaseDetails a populated CBPayPalBill object
* @param isLiveEnvironment whether we are using the production or sandbox paypal environments
* @param responder a responder to handle the returned PayPal token and submission url
* @param shouldQueue whether the request should be queued if connectivity is not available
*/
public void preparePayPalPurchase(CBPayPalBill purchaseDetails, boolean isLiveEnvironment, CBHelperResponder responder, boolean shouldQueue) {
String url = this.getUrl() + this.appCode + "/paypal/prepare";
Hashtable<String, Object> postData = new Hashtable<String, Object>();
postData.put("environment", isLiveEnvironment?"live":"sandbox");
postData.put("currency", purchaseDetails.getCurrency());
postData.put("type", "purchase");
postData.put("completed_cloudfunction", purchaseDetails.getPaymentCompletedFunction());
postData.put("cancelled_cloudfunction", purchaseDetails.getPaymentCancelledFunction());
postData.put("purchase_details", purchaseDetails.serializePurchase());
if (purchaseDetails.getPaymentCompletedUrl() != null)
postData.put("payment_completed_url", purchaseDetails.getPaymentCompletedUrl());
if (purchaseDetails.getPaymentCancelledUrl() != null)
postData.put("payment_cancelled_url", purchaseDetails.getPaymentCancelledUrl());
Hashtable<String, String> preparedPost = this.preparePostParams(postData, null);
this.startRequest(url, "paypal", null, preparedPost, null, responder, shouldQueue);
}
/**
* Once the PayPal purchase is completed this method updates the record in the cloudbase.io database.
* The responder can then proceed to close the payment window using the output of the call.
* This API request will not be queued
* @param url The url returned by PayPal once the payment is completed
* @param responder The responder to complete the payment in the application
* @param shouldQueue whether the request should be queued if connectivity is not available
*/
public void completePayPalPurchase(String url, CBHelperResponder responder) {
this.completePayPalPurchase(url, responder, false);
}
/**
* Once the PayPal purchase is completed this method updates the record in the cloudbase.io database.
* The responder can then proceed to close the payment window using the output of the call
* @param url The url returned by PayPal once the payment is completed
* @param responder The responder to complete the payment in the application
* @param shouldQueue whether the request should be queued if connectivity is not available
*/
public void completePayPalPurchase(String url, CBHelperResponder responder, boolean shouldQueue) {
Hashtable<String, String> preparedPost = this.preparePostParams(new Hashtable<String, String>(), null);
this.startRequest(url, "paypal", null, preparedPost, null, responder, shouldQueue);
}
/**
* Returns all of the details of a payment which has been prepared.