1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package com.allanbank.mongodb.client;
21
22 import java.util.ArrayList;
23 import java.util.Collection;
24 import java.util.List;
25
26 import com.allanbank.mongodb.AsyncMongoCollection;
27 import com.allanbank.mongodb.Callback;
28 import com.allanbank.mongodb.Durability;
29 import com.allanbank.mongodb.MongoCursorControl;
30 import com.allanbank.mongodb.MongoDatabase;
31 import com.allanbank.mongodb.MongoDbException;
32 import com.allanbank.mongodb.MongoIterator;
33 import com.allanbank.mongodb.ReadPreference;
34 import com.allanbank.mongodb.StreamCallback;
35 import com.allanbank.mongodb.Version;
36 import com.allanbank.mongodb.bson.Document;
37 import com.allanbank.mongodb.bson.DocumentAssignable;
38 import com.allanbank.mongodb.bson.Element;
39 import com.allanbank.mongodb.bson.builder.ArrayBuilder;
40 import com.allanbank.mongodb.bson.builder.BuilderFactory;
41 import com.allanbank.mongodb.bson.builder.DocumentBuilder;
42 import com.allanbank.mongodb.bson.impl.EmptyDocument;
43 import com.allanbank.mongodb.bson.impl.ImmutableDocument;
44 import com.allanbank.mongodb.bson.impl.RootDocument;
45 import com.allanbank.mongodb.builder.Aggregate;
46 import com.allanbank.mongodb.builder.BatchedWrite;
47 import com.allanbank.mongodb.builder.ConditionBuilder;
48 import com.allanbank.mongodb.builder.Count;
49 import com.allanbank.mongodb.builder.Distinct;
50 import com.allanbank.mongodb.builder.Find;
51 import com.allanbank.mongodb.builder.FindAndModify;
52 import com.allanbank.mongodb.builder.GroupBy;
53 import com.allanbank.mongodb.builder.MapReduce;
54 import com.allanbank.mongodb.builder.ParallelScan;
55 import com.allanbank.mongodb.builder.write.WriteOperation;
56 import com.allanbank.mongodb.client.callback.BatchedNativeWriteCallback;
57 import com.allanbank.mongodb.client.callback.BatchedWriteCallback;
58 import com.allanbank.mongodb.client.callback.CursorCallback;
59 import com.allanbank.mongodb.client.callback.CursorStreamingCallback;
60 import com.allanbank.mongodb.client.callback.LongToIntCallback;
61 import com.allanbank.mongodb.client.callback.MultipleCursorCallback;
62 import com.allanbank.mongodb.client.callback.ReplyArrayCallback;
63 import com.allanbank.mongodb.client.callback.ReplyDocumentCallback;
64 import com.allanbank.mongodb.client.callback.ReplyIntegerCallback;
65 import com.allanbank.mongodb.client.callback.ReplyLongCallback;
66 import com.allanbank.mongodb.client.callback.ReplyResultCallback;
67 import com.allanbank.mongodb.client.callback.SingleDocumentCallback;
68 import com.allanbank.mongodb.client.message.AggregateCommand;
69 import com.allanbank.mongodb.client.message.Command;
70 import com.allanbank.mongodb.client.message.Delete;
71 import com.allanbank.mongodb.client.message.GetLastError;
72 import com.allanbank.mongodb.client.message.Insert;
73 import com.allanbank.mongodb.client.message.ParallelScanCommand;
74 import com.allanbank.mongodb.client.message.Query;
75 import com.allanbank.mongodb.client.message.Update;
76
77
78
79
80
81
82
83
84
85 public abstract class AbstractMongoOperations {
86
87
88
89
90
91 public static final boolean DELETE_SINGLE_DELETE_DEFAULT = false;
92
93
94 public static final Document EMPTY_INDEX_OPTIONS = EmptyDocument.INSTANCE;
95
96
97 public static final String ID_FIELD_NAME = "_id";
98
99
100 public static final boolean INSERT_CONTINUE_ON_ERROR_DEFAULT = false;
101
102
103 public static final Document UNIQUE_INDEX_OPTIONS = new ImmutableDocument(
104 BuilderFactory.start().add("unique", true));
105
106
107 public static final boolean UPDATE_MULTIUPDATE_DEFAULT = false;
108
109
110 public static final boolean UPDATE_UPSERT_DEFAULT = false;
111
112
113 protected final Client myClient;
114
115
116 protected final MongoDatabase myDatabase;
117
118
119 protected final String myName;
120
121
122 private Durability myDurability;
123
124
125 private ReadPreference myReadPreference;
126
127
128
129
130
131
132
133
134
135
136
137 public AbstractMongoOperations(final Client client,
138 final MongoDatabase database, final String name) {
139 super();
140
141 myClient = client;
142 myDatabase = database;
143 myName = name;
144 myDurability = null;
145 myReadPreference = null;
146 }
147
148
149
150
151
152
153
154
155
156
157
158
159
160 public void aggregateAsync(final Callback<MongoIterator<Document>> results,
161 final Aggregate command) throws MongoDbException {
162
163 final AggregateCommand commandMsg = toCommand(command, false);
164
165 final CursorCallback callback = new CursorCallback(myClient,
166 commandMsg, true, results);
167
168 myClient.send(commandMsg, callback);
169 }
170
171
172
173
174
175
176
177
178
179
180
181
182
183 public void countAsync(final Callback<Long> results, final Count count)
184 throws MongoDbException {
185 Version minVersion = null;
186 final DocumentBuilder builder = BuilderFactory.start();
187
188 builder.addString("count", getName());
189 builder.addDocument("query", count.getQuery());
190 if (count.getMaximumTimeMilliseconds() > 0) {
191 minVersion = Count.MAX_TIMEOUT_VERSION;
192 builder.add("maxTimeMS", count.getMaximumTimeMilliseconds());
193 }
194
195
196 final ReadPreference finalPreference = updateReadPreference(builder,
197 count.getReadPreference(), true);
198
199 final Command commandMsg = new Command(getDatabaseName(), getName(),
200 builder.build(), count.getQuery(), finalPreference,
201 VersionRange.minimum(minVersion));
202
203 myClient.send(commandMsg, new ReplyLongCallback(results));
204 }
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226 public void deleteAsync(final Callback<Long> results,
227 final DocumentAssignable query, final boolean singleDelete,
228 final Durability durability) throws MongoDbException {
229
230 if ((durability != Durability.NONE) && useWriteCommand()
231 && isWriteCommandsSupported(null)) {
232
233 final BatchedWrite write = BatchedWrite.delete(query, singleDelete,
234 durability);
235
236 writeAsync(results, write);
237 }
238 else {
239 final Delete deleteMessage = new Delete(getDatabaseName(), myName,
240 query.asDocument(), singleDelete);
241
242 if (Durability.NONE.equals(durability)) {
243 myClient.send(deleteMessage, null);
244 results.callback(Long.valueOf(-1));
245 }
246 else {
247 myClient.send(deleteMessage, asGetLastError(durability),
248 new ReplyLongCallback(results));
249 }
250 }
251 }
252
253
254
255
256
257
258
259
260
261
262
263
264
265 public void distinctAsync(final Callback<MongoIterator<Element>> results,
266 final Distinct command) throws MongoDbException {
267
268 Version minVersion = null;
269
270 final DocumentBuilder builder = BuilderFactory.start();
271
272 builder.addString("distinct", getName());
273 builder.addString("key", command.getKey());
274 if (command.getQuery() != null) {
275 builder.addDocument("query", command.getQuery());
276 }
277 if (command.getMaximumTimeMilliseconds() > 0) {
278 minVersion = Distinct.MAX_TIMEOUT_VERSION;
279 builder.add("maxTimeMS", command.getMaximumTimeMilliseconds());
280 }
281
282
283 final ReadPreference readPreference = updateReadPreference(builder,
284 command.getReadPreference(), true);
285
286 final Command commandMsg = new Command(getDatabaseName(), getName(),
287 builder.build(), readPreference,
288 VersionRange.minimum(minVersion));
289
290 myClient.send(commandMsg, new ReplyArrayCallback(results));
291
292 }
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307 public void explainAsync(final Callback<Document> results,
308 final Aggregate aggregation) throws MongoDbException {
309 final AggregateCommand commandMsg = toCommand(aggregation, true);
310
311 myClient.send(commandMsg, new SingleDocumentCallback(results));
312 }
313
314
315
316
317
318
319
320
321
322
323
324
325
326 public void explainAsync(final Callback<Document> results, final Find query)
327 throws MongoDbException {
328
329 ReadPreference readPreference = query.getReadPreference();
330 if (readPreference == null) {
331 readPreference = getReadPreference();
332 }
333
334 Document queryDoc;
335 if (!readPreference.isLegacy()
336 && (myClient.getClusterType() == ClusterType.SHARDED)) {
337 queryDoc = query.toQueryRequest(true, readPreference);
338 }
339 else {
340 queryDoc = query.toQueryRequest(true);
341 }
342
343 final Query queryMessage = new Query(getDatabaseName(), myName,
344 queryDoc, query.getProjection(), query.getBatchSize(),
345 query.getLimit(), query.getNumberToSkip(),
346 false , readPreference,
347 false , false ,
348 false , query.isPartialOk());
349
350 myClient.send(queryMessage, new SingleDocumentCallback(results));
351 }
352
353
354
355
356
357
358
359
360
361
362
363
364
365 public void findAndModifyAsync(final Callback<Document> results,
366 final FindAndModify command) throws MongoDbException {
367 Version minVersion = null;
368
369 final DocumentBuilder builder = BuilderFactory.start();
370
371 builder.addString("findAndModify", getName());
372 builder.addDocument("query", command.getQuery());
373 if (command.getUpdate() != null) {
374 builder.addDocument("update", command.getUpdate());
375 }
376 if (command.getSort() != null) {
377 builder.addDocument("sort", command.getSort());
378 }
379 if (command.getFields() != null) {
380 builder.addDocument("fields", command.getFields());
381 }
382 if (command.isRemove()) {
383 builder.addBoolean("remove", true);
384 }
385 if (command.isReturnNew()) {
386 builder.addBoolean("new", true);
387 }
388 if (command.isUpsert()) {
389 builder.addBoolean("upsert", true);
390 }
391 if (command.getMaximumTimeMilliseconds() > 0) {
392 minVersion = FindAndModify.MAX_TIMEOUT_VERSION;
393 builder.add("maxTimeMS", command.getMaximumTimeMilliseconds());
394 }
395
396
397 final Command commandMsg = new Command(getDatabaseName(), getName(),
398 builder.build(), command.getQuery(), ReadPreference.PRIMARY,
399 VersionRange.minimum(minVersion));
400 myClient.send(commandMsg, new ReplyDocumentCallback(results));
401 }
402
403
404
405
406
407
408
409
410
411
412
413
414
415 public void findAsync(final Callback<MongoIterator<Document>> results,
416 final Find query) throws MongoDbException {
417
418 final Query queryMessage = createQuery(query, query.getLimit(),
419 query.getBatchSize(), query.isTailable(), query.isAwaitData(),
420 query.isImmortalCursor());
421
422 final CursorCallback callback = new CursorCallback(myClient,
423 queryMessage, false, results);
424
425 myClient.send(queryMessage, callback);
426 }
427
428
429
430
431
432
433
434
435
436
437
438
439
440 public void findOneAsync(final Callback<Document> results, final Find query)
441 throws MongoDbException {
442 final Query queryMessage = createQuery(query, 1, 1, false, false, false);
443
444 myClient.send(queryMessage, new SingleDocumentCallback(results));
445 }
446
447
448
449
450
451
452 public String getDatabaseName() {
453 return myDatabase.getName();
454 }
455
456
457
458
459
460
461
462
463 public Durability getDurability() {
464 Durability result = myDurability;
465 if (result == null) {
466 result = myDatabase.getDurability();
467 }
468 return result;
469 }
470
471
472
473
474
475
476 public String getName() {
477 return myName;
478 }
479
480
481
482
483
484
485
486
487 public ReadPreference getReadPreference() {
488 ReadPreference result = myReadPreference;
489 if (result == null) {
490 result = myDatabase.getReadPreference();
491 }
492 return result;
493 }
494
495
496
497
498
499
500
501
502
503
504
505
506
507 public void groupByAsync(final Callback<MongoIterator<Element>> results,
508 final GroupBy command) throws MongoDbException {
509 Version minVersion = null;
510
511 final DocumentBuilder builder = BuilderFactory.start();
512
513 final DocumentBuilder groupDocBuilder = builder.push("group");
514
515 groupDocBuilder.addString("ns", getName());
516 if (!command.getKeys().isEmpty()) {
517 final DocumentBuilder keysBuilder = groupDocBuilder.push("key");
518 for (final String key : command.getKeys()) {
519 keysBuilder.addBoolean(key, true);
520 }
521 }
522 if (command.getKeyFunction() != null) {
523 groupDocBuilder.addJavaScript("$keyf", command.getKeyFunction());
524 }
525 if (command.getInitialValue() != null) {
526 groupDocBuilder.addDocument("initial", command.getInitialValue());
527 }
528 if (command.getReduceFunction() != null) {
529 groupDocBuilder.addJavaScript("$reduce",
530 command.getReduceFunction());
531 }
532 if (command.getFinalizeFunction() != null) {
533 groupDocBuilder.addJavaScript("finalize",
534 command.getFinalizeFunction());
535 }
536 if (command.getQuery() != null) {
537 groupDocBuilder.addDocument("cond", command.getQuery());
538 }
539 if (command.getMaximumTimeMilliseconds() > 0) {
540 minVersion = GroupBy.MAX_TIMEOUT_VERSION;
541
542
543 builder.add("maxTimeMS", command.getMaximumTimeMilliseconds());
544 }
545
546
547 final ReadPreference readPreference = updateReadPreference(
548 groupDocBuilder, command.getReadPreference(), false);
549
550 final Command commandMsg = new Command(getDatabaseName(), getName(),
551 builder.build(), readPreference,
552 VersionRange.minimum(minVersion));
553 myClient.send(commandMsg, new ReplyArrayCallback("retval", results));
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 public void insertAsync(final Callback<Integer> results,
580 final boolean continueOnError, final Durability durability,
581 final DocumentAssignable... documents) throws MongoDbException {
582
583 doInsertAsync(results, continueOnError, durability, null, documents);
584 }
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599 public void mapReduceAsync(final Callback<MongoIterator<Document>> results,
600 final MapReduce command) throws MongoDbException {
601 Version minVersion = null;
602
603 final DocumentBuilder builder = BuilderFactory.start();
604
605 builder.addString("mapreduce", getName());
606 builder.addJavaScript("map", command.getMapFunction());
607 builder.addJavaScript("reduce", command.getReduceFunction());
608 if (command.getFinalizeFunction() != null) {
609 builder.addJavaScript("finalize", command.getFinalizeFunction());
610 }
611 if (command.getQuery() != null) {
612 builder.addDocument("query", command.getQuery());
613 }
614 if (command.getSort() != null) {
615 builder.addDocument("sort", command.getSort());
616 }
617 if (command.getScope() != null) {
618 builder.addDocument("scope", command.getScope());
619 }
620 if (command.getLimit() != 0) {
621 builder.addInteger("limit", command.getLimit());
622 }
623 if (command.isKeepTemp()) {
624 builder.addBoolean("keeptemp", true);
625 }
626 if (command.isJsMode()) {
627 builder.addBoolean("jsMode", true);
628 }
629 if (command.isVerbose()) {
630 builder.addBoolean("verbose", true);
631 }
632 if (command.getMaximumTimeMilliseconds() > 0) {
633 minVersion = MapReduce.MAX_TIMEOUT_VERSION;
634 builder.add("maxTimeMS", command.getMaximumTimeMilliseconds());
635 }
636
637 final DocumentBuilder outputBuilder = builder.push("out");
638 switch (command.getOutputType()) {
639 case INLINE: {
640 outputBuilder.addInteger("inline", 1);
641 break;
642 }
643 case REPLACE: {
644 outputBuilder.addString("replace", command.getOutputName());
645 if (command.getOutputDatabase() != null) {
646 outputBuilder.addString("db", command.getOutputDatabase());
647 }
648 break;
649 }
650 case MERGE: {
651 outputBuilder.addString("merge", command.getOutputName());
652 if (command.getOutputDatabase() != null) {
653 outputBuilder.addString("db", command.getOutputDatabase());
654 }
655 break;
656 }
657 case REDUCE: {
658 outputBuilder.addString("reduce", command.getOutputName());
659 if (command.getOutputDatabase() != null) {
660 outputBuilder.addString("db", command.getOutputDatabase());
661 }
662 break;
663 }
664 }
665
666
667 final ReadPreference readPreference = updateReadPreference(builder,
668 command.getReadPreference(), true);
669
670 final Command commandMsg = new Command(getDatabaseName(), getName(),
671 builder.build(), readPreference,
672 VersionRange.minimum(minVersion));
673 myClient.send(commandMsg, new ReplyResultCallback(results));
674 }
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691 public void parallelScanAsync(
692 final Callback<Collection<MongoIterator<Document>>> results,
693 final ParallelScan parallelScan) throws MongoDbException {
694 final DocumentBuilder builder = BuilderFactory.start();
695
696 builder.add("parallelCollectionScan", getName());
697 builder.add("numCursors", parallelScan.getRequestedIteratorCount());
698
699
700 final ReadPreference readPreference = updateReadPreference(builder,
701 parallelScan.getReadPreference(), true);
702
703 final ParallelScanCommand commandMsg = new ParallelScanCommand(
704 parallelScan, getDatabaseName(), getName(), builder.build(),
705 readPreference);
706
707 myClient.send(commandMsg, new MultipleCursorCallback(myClient,
708 commandMsg, results));
709
710 }
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730 public void saveAsync(final Callback<Integer> results,
731 final DocumentAssignable document, final Durability durability)
732 throws MongoDbException {
733 final Document doc = document.asDocument();
734
735 if (doc.contains(ID_FIELD_NAME)) {
736 updateAsync(new LongToIntCallback(results), BuilderFactory.start()
737 .add(doc.get(ID_FIELD_NAME)), doc, false, true, durability);
738 }
739 else {
740 insertAsync(results, INSERT_CONTINUE_ON_ERROR_DEFAULT, durability,
741 doc);
742 }
743 }
744
745
746
747
748
749
750
751
752
753 public void setDurability(final Durability durability) {
754 myDurability = durability;
755 }
756
757
758
759
760
761
762
763
764
765 public void setReadPreference(final ReadPreference readPreference) {
766 myReadPreference = readPreference;
767 }
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784 public MongoCursorControl stream(final StreamCallback<Document> results,
785 final Aggregate aggregation) throws MongoDbException {
786 final AggregateCommand commandMsg = toCommand(aggregation, false);
787
788 final CursorStreamingCallback callback = new CursorStreamingCallback(
789 myClient, commandMsg, true, results);
790
791 myClient.send(commandMsg, callback);
792
793 return callback;
794 }
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811 public MongoCursorControl stream(final StreamCallback<Document> results,
812 final Find query) throws MongoDbException {
813 final Query queryMessage = createQuery(query, query.getLimit(),
814 query.getBatchSize(), query.isTailable(), query.isAwaitData(),
815 query.isImmortalCursor());
816
817 final CursorStreamingCallback callback = new CursorStreamingCallback(
818 myClient, queryMessage, false, results);
819
820 myClient.send(queryMessage, callback);
821
822 return callback;
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 @Deprecated
849 public void textSearchAsync(
850 final Callback<MongoIterator<com.allanbank.mongodb.builder.TextResult>> results,
851 final com.allanbank.mongodb.builder.Text command)
852 throws MongoDbException {
853 final Version minVersion = com.allanbank.mongodb.builder.Text.REQUIRED_VERSION;
854 final DocumentBuilder builder = BuilderFactory.start();
855
856 builder.addString("text", getName());
857 builder.addString("search", command.getSearchTerm());
858 if (command.getQuery() != null) {
859 builder.add("filter", command.getQuery());
860 }
861 if (command.getLimit() > 0) {
862 builder.add("limit", command.getLimit());
863 }
864 if (command.getReturnFields() != null) {
865 builder.add("project", command.getReturnFields());
866 }
867 if (command.getLanguage() != null) {
868 builder.add("language", command.getLanguage());
869 }
870
871
872 final ReadPreference readPreference = updateReadPreference(builder,
873 command.getReadPreference(), true);
874
875 final Command commandMsg = new Command(getDatabaseName(), getName(),
876 builder.build(), readPreference,
877 VersionRange.minimum(minVersion));
878 myClient.send(commandMsg,
879 new ReplyResultCallback(
880 new com.allanbank.mongodb.client.callback.TextCallback(
881 results)));
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 public void updateAsync(final Callback<Long> results,
910 final DocumentAssignable query, final DocumentAssignable update,
911 final boolean multiUpdate, final boolean upsert,
912 final Durability durability) throws MongoDbException {
913
914 final ClusterStats stats = myClient.getClusterStats();
915 if ((durability != Durability.NONE) && useWriteCommand()
916 && isWriteCommandsSupported(stats)) {
917 final BatchedWrite write = BatchedWrite.update(query, update,
918 multiUpdate, upsert, durability);
919
920 doWriteAsync(stats, results, write);
921 }
922 else {
923 final Update updateMessage = new Update(getDatabaseName(), myName,
924 query.asDocument(), update.asDocument(), multiUpdate,
925 upsert);
926
927 if (Durability.NONE == durability) {
928 myClient.send(updateMessage, null);
929 results.callback(Long.valueOf(-1));
930 }
931 else {
932 myClient.send(updateMessage, asGetLastError(durability),
933 new ReplyLongCallback(results));
934 }
935 }
936 }
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953 public void writeAsync(final Callback<Long> results,
954 final BatchedWrite write) throws MongoDbException {
955 final ClusterStats stats = myClient.getClusterStats();
956
957 doWriteAsync(stats, results, write);
958 }
959
960
961
962
963
964
965
966
967 protected GetLastError asGetLastError(final Durability durability) {
968 return new GetLastError(getDatabaseName(), durability);
969 }
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989 protected Query createQuery(final Find query, final int limit,
990 final int batchSize, final boolean tailable,
991 final boolean awaitData, final boolean immortal) {
992 ReadPreference readPreference = query.getReadPreference();
993 if (readPreference == null) {
994 readPreference = getReadPreference();
995 }
996
997 Document queryDoc;
998 if (!readPreference.isLegacy()
999 && (myClient.getClusterType() == ClusterType.SHARDED)) {
1000 queryDoc = query.toQueryRequest(false, readPreference);
1001 }
1002 else {
1003 queryDoc = query.toQueryRequest(false);
1004 }
1005
1006 return new Query(getDatabaseName(), myName, queryDoc,
1007 query.getProjection(), batchSize, limit,
1008 query.getNumberToSkip(), tailable, readPreference, immortal,
1009 awaitData, false , query.isPartialOk());
1010 }
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032 protected void doInsertAsync(final Callback<Integer> results,
1033 final boolean continueOnError, final Durability durability,
1034 final Version requiredServerVersion,
1035 final DocumentAssignable... documents) throws MongoDbException {
1036
1037 final ClusterStats stats = myClient.getClusterStats();
1038 if ((durability != Durability.NONE) && useWriteCommand()
1039 && isWriteCommandsSupported(stats)) {
1040 final BatchedWrite write = BatchedWrite.insert(continueOnError,
1041 durability, documents);
1042
1043 doWriteAsync(stats, new LongToIntCallback(results), write);
1044 }
1045 else {
1046
1047 final List<Document> docs = new ArrayList<Document>(
1048 documents.length);
1049 for (final DocumentAssignable docAssignable : documents) {
1050 final Document doc = docAssignable.asDocument();
1051 if (!doc.contains(ID_FIELD_NAME)
1052 && (doc instanceof RootDocument)) {
1053 ((RootDocument) doc).injectId();
1054 }
1055 docs.add(doc);
1056 }
1057
1058 final Insert insertMessage = new Insert(getDatabaseName(), myName,
1059 docs, continueOnError,
1060 VersionRange.minimum(requiredServerVersion));
1061 if (Durability.NONE == durability) {
1062 myClient.send(insertMessage, null);
1063 results.callback(Integer.valueOf(-1));
1064 }
1065 else {
1066 myClient.send(insertMessage, asGetLastError(durability),
1067 new ReplyIntegerCallback(results));
1068 }
1069 }
1070 }
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082 protected void doWriteAsync(final ClusterStats stats,
1083 final Callback<Long> results, final BatchedWrite write) {
1084 if (isWriteCommandsSupported(stats)) {
1085
1086 final List<BatchedWrite.Bundle> bundles = write.toBundles(
1087 getName(), stats.getSmallestMaxBsonObjectSize(),
1088 stats.getSmallestMaxBatchedWriteOperations());
1089 if (bundles.isEmpty()) {
1090 results.callback(Long.valueOf(0));
1091 return;
1092 }
1093
1094 final BatchedWriteCallback callback = new BatchedWriteCallback(
1095 getDatabaseName(), getName(), results, write, myClient,
1096 bundles);
1097
1098
1099 callback.send();
1100 }
1101 else {
1102 final List<WriteOperation> operations = write.getWrites();
1103 if (operations.isEmpty()) {
1104 results.callback(Long.valueOf(0));
1105 return;
1106 }
1107
1108 final BatchedNativeWriteCallback callback = new BatchedNativeWriteCallback(
1109 results, write, this, operations);
1110
1111
1112 callback.send();
1113 }
1114 }
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125 protected boolean isWriteCommandsSupported(final ClusterStats stats) {
1126 final ClusterStats clusterStats = (stats == null) ? myClient
1127 .getClusterStats() : stats;
1128 final VersionRange serverVersionRange = clusterStats
1129 .getServerVersionRange();
1130 final Version minServerVersion = serverVersionRange.getLowerBounds();
1131
1132 return (BatchedWrite.REQUIRED_VERSION.compareTo(minServerVersion) <= 0);
1133 }
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145 protected AggregateCommand toCommand(final Aggregate command,
1146 final boolean explain) {
1147 Version minVersion = command.getRequiredVersion();
1148
1149 final DocumentBuilder builder = BuilderFactory.start();
1150
1151 builder.addString("aggregate", getName());
1152
1153
1154 final ArrayBuilder pipeline = builder.pushArray("pipeline");
1155 for (final Element e : command.getPipeline()) {
1156 pipeline.add(e);
1157 }
1158
1159
1160 if (command.isAllowDiskUsage()) {
1161 builder.add("allowDiskUsage", true);
1162 }
1163 if (command.isUseCursor()) {
1164 final DocumentBuilder cursor = builder.push("cursor");
1165 if (command.getBatchSize() > 0) {
1166 cursor.add("batchSize", command.getBatchSize());
1167 }
1168 }
1169 if (explain) {
1170 minVersion = Version.later(minVersion, Aggregate.EXPLAIN_VERSION);
1171 builder.add("explain", true);
1172 }
1173 if (command.getMaximumTimeMilliseconds() > 0) {
1174 builder.add("maxTimeMS", command.getMaximumTimeMilliseconds());
1175 }
1176
1177
1178 final ReadPreference readPreference = updateReadPreference(builder,
1179 command.getReadPreference(), true);
1180
1181 final AggregateCommand commandMsg = new AggregateCommand(command,
1182 getDatabaseName(), getName(), builder.build(), readPreference,
1183 VersionRange.minimum(minVersion));
1184 return commandMsg;
1185 }
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207 protected ReadPreference updateReadPreference(
1208 final DocumentBuilder builder,
1209 final ReadPreference commandReadPreference,
1210 final boolean createQueryElement) {
1211
1212 ReadPreference readPreference = commandReadPreference;
1213 if (readPreference == null) {
1214 readPreference = getReadPreference();
1215 }
1216
1217 if (!readPreference.isLegacy()
1218 && (myClient.getClusterType() == ClusterType.SHARDED)) {
1219 if (createQueryElement) {
1220 final Document query = builder.asDocument();
1221 builder.reset();
1222 builder.add("$query", query);
1223 }
1224 builder.add(ReadPreference.FIELD_NAME, readPreference);
1225 }
1226
1227 return readPreference;
1228 }
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247 protected boolean useWriteCommand() {
1248 return true;
1249 }
1250 }