forked from mongodb/mongo-java-driver
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDB.java
More file actions
1001 lines (899 loc) · 38.7 KB
/
Copy pathDB.java
File metadata and controls
1001 lines (899 loc) · 38.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
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-2014 MongoDB, Inc.
*
* 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.
*/
// DB.java
package com.mongodb;
import com.mongodb.util.Util;
import org.bson.BSONObject;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
/**
* A thread-safe client view of a logical database in a MongoDB cluster. A DB instance can be achieved from a {@link MongoClient} instance
* using code like:
* <pre>
* {@code
* MongoClient mongoClient = new MongoClient();
* DB db = mongoClient.getDB("<db name>");
* }</pre>
*
* @mongodb.driver.manual reference/glossary/#term-database Database
* @see MongoClient
*/
public abstract class DB {
private static final Set<String> _obedientCommands = new HashSet<String>();
static {
_obedientCommands.add("group");
_obedientCommands.add("aggregate");
_obedientCommands.add("collstats");
_obedientCommands.add("dbstats");
_obedientCommands.add("count");
_obedientCommands.add("distinct");
_obedientCommands.add("geonear");
_obedientCommands.add("geosearch");
_obedientCommands.add("geowalk");
_obedientCommands.add("text");
_obedientCommands.add("parallelcollectionscan");
}
/**
* Constructs a new instance of the {@code DB}.
*
* @param mongo the mongo instance
* @param name the database name
*/
public DB( Mongo mongo , String name ){
if(!isValidName(name))
throw new IllegalArgumentException("Invalid database name format. Database name is either empty or it contains spaces.");
_mongo = mongo;
_name = name;
_options = new Bytes.OptionHolder( _mongo._netOptions );
}
/**
* Determines the read preference that should be used for the given command.
*
* @param command the {@link DBObject} representing the command
* @param requestedPreference the preference requested by the client.
* @return the read preference to use for the given command. It will never return {@code null}.
* @see com.mongodb.ReadPreference
*/
ReadPreference getCommandReadPreference(DBObject command, ReadPreference requestedPreference){
if (_mongo.getReplicaSetStatus() == null) {
return requestedPreference;
}
String comString = command.keySet().iterator().next();
if (comString.equals("getnonce") || comString.equals("authenticate")) {
return ReadPreference.primaryPreferred();
}
boolean primaryRequired;
// explicitly check mapreduce commands are inline
if(comString.equals("mapreduce")) {
Object out = command.get("out");
if (out instanceof BSONObject ){
BSONObject outMap = (BSONObject) out;
primaryRequired = outMap.get("inline") == null;
} else {
primaryRequired = true;
}
} else if(comString.equals("aggregate")) {
@SuppressWarnings("unchecked")
List<DBObject> pipeline = (List<DBObject>) command.get("pipeline");
primaryRequired = pipeline.get(pipeline.size()-1).get("$out") != null;
} else {
primaryRequired = !_obedientCommands.contains(comString.toLowerCase());
}
if (primaryRequired) {
return ReadPreference.primary();
} else if (requestedPreference == null) {
return ReadPreference.primary();
} else {
return requestedPreference;
}
}
/**
* Starts a new 'consistent request'.
* <p/>
* Following this call and until {@link com.mongodb.DB#requestDone()} is called,
* all db operations will use the same underlying connection.
* <p/>
* This is useful to ensure that operations happen in a certain order with predictable results.
*/
public abstract void requestStart();
/**
* Ends the current 'consistent request'.
*/
public abstract void requestDone();
/**
* Ensure that a connection is assigned to the current 'consistent request'
* (from primary pool, if connected to a replica set)
*/
public abstract void requestEnsureConnection();
/**
* Gets a collection with a given name.
* If the collection does not exist, a new collection is created.
* <p/>
* This class is NOT part of the public API. Be prepared for non-binary compatible changes in minor releases.
*
* @param name the name of the collection
* @return the collection
*/
protected abstract DBCollection doGetCollection( String name );
/**
* Gets a collection with a given name.
* If the collection does not exist, a new collection is created.
*
* @param name the name of the collection to return
* @return the collection
*/
public DBCollection getCollection( String name ){
DBCollection c = doGetCollection( name );
return c;
}
/**
* Creates a collection with a given name and options.
* If the collection does not exist, a new collection is created.
* <p/>
* Possible options:
* <ul>
* <li>
* <b>capped</b> ({@code boolean}) - Enables a collection cap.
* False by default. If enabled, you must specify a size parameter.
* </li>
* <li>
* <b>size</b> ({@code int}) - If capped is true, size specifies a maximum size in bytes for the capped collection.
* When capped is false, you may use size to preallocate space.
* </li>
* <li>
* <b>max</b> ({@code int}) - Optional. Specifies a maximum "cap" in number of documents for capped collections.
* You must also specify size when specifying max.
* </li>
* <p/>
* </ul>
* <p/>
* Note that if the {@code options} parameter is {@code null},
* the creation will be deferred to when the collection is written to.
*
* @param name the name of the collection to return
* @param options options
* @return the collection
* @throws MongoException
*/
public DBCollection createCollection( String name, DBObject options ){
if ( options != null ){
DBObject createCmd = new BasicDBObject("create", name);
createCmd.putAll(options);
CommandResult result = command(createCmd);
result.throwOnError();
}
return getCollection(name);
}
/**
* Returns a collection matching a given string.
*
* @param s the name of the collection
* @return the collection
*/
public DBCollection getCollectionFromString( String s ){
DBCollection foo = null;
int idx = s.indexOf( "." );
while ( idx >= 0 ){
String b = s.substring( 0 , idx );
s = s.substring( idx + 1 );
if ( foo == null )
foo = getCollection( b );
else
foo = foo.getCollection( b );
idx = s.indexOf( "." );
}
if ( foo != null )
return foo.getCollection( s );
return getCollection( s );
}
/**
* Executes a database command.
* This method calls {@link DB#command(DBObject, int)} } with 0 as query option.
*
* @param cmd {@code DBObject} representation of the command to be executed
* @return result of the command execution
* @throws MongoException
* @mongodb.driver.manual tutorial/use-database-commands Commands
*/
public CommandResult command( DBObject cmd ){
return command( cmd, 0 );
}
/**
* Executes a database command.
* This method calls {@link DB#command(com.mongodb.DBObject, int, com.mongodb.DBEncoder) } with 0 as query option.
*
* @param cmd {@code DBObject} representation of the command to be executed
* @param encoder {@link DBEncoder} to be used for command encoding
* @return result of the command execution
* @throws MongoException
* @mongodb.driver.manual tutorial/use-database-commands Commands
*/
public CommandResult command( DBObject cmd, DBEncoder encoder ){
return command( cmd, 0, encoder );
}
/**
* Executes a database command. This method calls
* {@link DB#command(com.mongodb.DBObject, int, com.mongodb.ReadPreference, com.mongodb.DBEncoder) } with the database default read
* preference. The only option used by this method was "slave ok", therefore this method has been replaced with
* {@link com.mongodb.DB#command(DBObject, ReadPreference, DBEncoder)}.
*
* @param cmd {@code DBObject} representation the command to be executed
* @param options query options to use
* @param encoder {@link DBEncoder} to be used for command encoding
* @return result of the command execution
* @throws MongoException
* @mongodb.driver.manual tutorial/use-database-commands Commands
* @deprecated Use {@link com.mongodb.DB#command(DBObject, ReadPreference, DBEncoder)} instead. This method will be removed in 3.0.
*/
@Deprecated
public CommandResult command( DBObject cmd , int options, DBEncoder encoder ){
return command(cmd, options, getReadPreference(), encoder);
}
/**
* Executes a database command. This method calls
* {@link DB#command(com.mongodb.DBObject, int, com.mongodb.ReadPreference, com.mongodb.DBEncoder) } with a default encoder. The only
* option used by this method was "slave ok", therefore this method has been replaced
* with {@link com.mongodb.DB#command(DBObject, ReadPreference)}.
*
* @param cmd A {@code DBObject} representation the command to be executed
* @param options The query options to use
* @param readPreference The {@link ReadPreference} for this command (nodes selection is the biggest part of this)
* @return result of the command execution
* @throws MongoException
* @mongodb.driver.manual tutorial/use-database-commands Commands
* @deprecated Use {@link com.mongodb.DB#command(DBObject, ReadPreference)} instead. This method will be removed in 3.0.
*/
@Deprecated
public CommandResult command( DBObject cmd , int options, ReadPreference readPreference ){
return command(cmd, options, readPreference, DefaultDBEncoder.FACTORY.create());
}
/**
* Executes a database command. The only option used by this method was "slave ok", therefore this method has been replaced with {@link
* com.mongodb.DB#command(DBObject, ReadPreference, DBEncoder)}.
*
* @param cmd A {@code DBObject} representation the command to be executed
* @param options The query options to use
* @param readPreference The {@link ReadPreference} for this command (nodes selection is the biggest part of this)
* @param encoder A {@link DBEncoder} to be used for command encoding
* @return result of the command execution
* @throws MongoException
* @mongodb.driver.manual tutorial/use-database-commands Commands
* @deprecated Use {@link com.mongodb.DB#command(DBObject, ReadPreference, DBEncoder)} instead. This method will be removed in 3.0.
*/
@Deprecated
public CommandResult command( DBObject cmd , int options, ReadPreference readPreference, DBEncoder encoder ){
ReadPreference effectiveReadPrefs = getCommandReadPreference(cmd, readPreference);
cmd = wrapCommand(cmd, effectiveReadPrefs);
QueryResultIterator i = getCollection("$cmd").find(cmd, new BasicDBObject(), 0, -1, 0, options, effectiveReadPrefs,
DefaultDBDecoder.FACTORY.create(), encoder);
if (!i.hasNext()) {
return null;
}
CommandResult cr = new CommandResult(i.getServerAddress());
cr.putAll(i.next());
return cr;
}
/**
* Executes a database command with the selected readPreference, and encodes the command using the given encoder.
*
* @param cmd The {@code DBObject} representation the command to be executed
* @param readPreference Where to execute the command - this will only be applied for a subset of commands
* @param encoder The DBEncoder that knows how to serialise the cmd
* @return The result of executing the command, success or failure
* @mongodb.driver.manual tutorial/use-database-commands Commands
* @since 2.12
*/
public CommandResult command( final DBObject cmd , final ReadPreference readPreference, final DBEncoder encoder ){
return command(cmd, 0, readPreference, encoder);
}
// Only append $readPreference meta-operator if connected to a mongos, read preference is not primary
// or secondary preferred,
// and command is an instance of BasicDBObject. The last condition is unfortunate, but necessary in case
// the encoder is not capable of encoding a BasicDBObject
// Due to issues with compatibility between different versions of mongos, also wrap the command in a
// $query field, so that the $readPreference is not rejected
private DBObject wrapCommand(DBObject cmd, final ReadPreference readPreference) {
if (getMongo().isMongosConnection() &&
!(ReadPreference.primary().equals(readPreference) || ReadPreference.secondaryPreferred().equals(readPreference)) &&
cmd instanceof BasicDBObject) {
cmd = new BasicDBObject("$query", cmd)
.append(QueryOpBuilder.READ_PREFERENCE_META_OPERATOR, readPreference.toDBObject());
}
return cmd;
}
/**
* Executes a database command with the given query options. The only option used by this method was "slave ok", therefore this method
* has been replaced with {@link com.mongodb.DB#command(DBObject, ReadPreference)}.
*
* @param cmd The {@code DBObject} representation the command to be executed
* @param options The query options to use
* @return The result of the command execution
* @throws MongoException
* @mongodb.driver.manual tutorial/use-database-commands Commands
* @deprecated Use {@link com.mongodb.DB#command(DBObject, ReadPreference)} instead. This method will be removed in 3.0.
*/
@Deprecated
public CommandResult command(DBObject cmd, int options) {
return command(cmd, options, getReadPreference());
}
/**
* Executes the command against the database with the given read preference. This method is the preferred way of setting read
* preference, use this instead of {@link DB#command(com.mongodb.DBObject, int) }
*
* @param cmd The {@code DBObject} representation the command to be executed
* @param readPreference Where to execute the command - this will only be applied for a subset of commands
* @return The result of executing the command, success or failure
* @mongodb.driver.manual tutorial/use-database-commands Commands
* @since 2.12
*/
public CommandResult command(final DBObject cmd, final ReadPreference readPreference) {
return command(cmd, 0, readPreference);
}
/**
* Executes a database command. This method constructs a simple dbobject and calls {@link DB#command(com.mongodb.DBObject) }
*
* @param cmd name of the command to be executed
* @return result of the command execution
* @throws MongoException
* @mongodb.driver.manual tutorial/use-database-commands Commands
*/
public CommandResult command( String cmd ){
return command( new BasicDBObject( cmd , Boolean.TRUE ) );
}
/**
* Executes a database command. This method constructs a simple dbobject and calls {@link DB#command(com.mongodb.DBObject, int) }
*
* @param cmd name of the command to be executed
* @param options query options to use
* @return result of the command execution
* @throws MongoException
* @mongodb.driver.manual tutorial/use-database-commands Commands
* @deprecated Use {@link com.mongodb.DB#command(String, ReadPreference)} instead. This method will be removed in 3.0.
*/
@Deprecated
public CommandResult command( String cmd, int options ){
return command( new BasicDBObject( cmd , Boolean.TRUE ), options );
}
/**
* Executes a database command. This method constructs a simple dbobject and calls {@link DB#command(com.mongodb.DBObject, int,
* com.mongodb.ReadPreference) }. The only option used by this method was "slave ok", therefore this method has been replaced with
* {@link com.mongodb.DB#command(DBObject, ReadPreference)}.
*
* @param cmd The name of the command to be executed
* @param readPreference Where to execute the command - this will only be applied for a subset of commands
* @return The result of the command execution
* @throws MongoException
* @mongodb.driver.manual tutorial/use-database-commands Commands
* @since 2.12
*/
public CommandResult command(final String cmd, final ReadPreference readPreference) {
return command(new BasicDBObject(cmd, Boolean.TRUE), 0, readPreference);
}
/**
* Evaluates JavaScript functions on the database server.
* This is useful if you need to touch a lot of data lightly, in which case network transfer could be a bottleneck.
*
* @param code @{code String} representation of JavaScript function
* @param args arguments to pass to the JavaScript function
* @return result of the command execution
* @throws MongoException
*/
public CommandResult doEval( String code , Object ... args ){
return command( BasicDBObjectBuilder.start()
.add( "$eval" , code )
.add( "args" , args )
.get() );
}
/**
* Calls {@link DB#doEval(java.lang.String, java.lang.Object[]) }.
* If the command is successful, the "retval" field is extracted and returned.
* Otherwise an exception is thrown.
*
* @param code @{code String} representation of JavaScript function
* @param args arguments to pass to the JavaScript function
* @return result of the execution
* @throws MongoException
*/
public Object eval( String code , Object ... args ){
CommandResult res = doEval( code , args );
res.throwOnError();
return res.get( "retval" );
}
/**
* Helper method for calling a 'dbStats' command.
* It returns storage statistics for a given database.
*
* @return result of the execution
* @throws MongoException
*/
public CommandResult getStats() {
CommandResult result = command("dbstats");
result.throwOnError();
return result;
}
/**
* Returns the name of this database.
*
* @return the name
*/
public String getName(){
return _name;
}
/**
* Makes this database read-only.
* Important note: this is a convenience setting that is only known on the client side and not persisted.
*
* @param b if the database should be read-only
* @deprecated Avoid making database read-only via this method.
* Connect with a user credentials that has a read-only access to a server instead.
*/
@Deprecated
public void setReadOnly(Boolean b) {
_readOnly = b;
}
/**
* Returns a set containing all collections in the existing database.
*
* @return an set of names
* @throws MongoException
*/
public Set<String> getCollectionNames(){
DBCollection namespaces = getCollection("system.namespaces");
if (namespaces == null)
throw new RuntimeException("this is impossible");
Iterator<DBObject> i = namespaces.find(new BasicDBObject(), null, 0, 0, 0, getOptions(), getReadPreference(), null);
if (i == null)
return new HashSet<String>();
List<String> tables = new ArrayList<String>();
for (; i.hasNext();) {
DBObject o = i.next();
if ( o.get( "name" ) == null ){
throw new MongoException( "how is name null : " + o );
}
String n = o.get("name").toString();
int idx = n.indexOf(".");
String root = n.substring(0, idx);
if (!root.equals(_name))
continue;
if (n.indexOf("$") >= 0)
continue;
String table = n.substring(idx + 1);
tables.add(table);
}
Collections.sort(tables);
return new LinkedHashSet<String>(tables);
}
/**
* Checks to see if a collection with a given name exists on a server.
*
* @param collectionName a name of the collection to test for existence
* @return {@code false} if no collection by that name exists, {@code true} if a match to an existing collection was found
* @throws MongoException
*/
public boolean collectionExists(String collectionName)
{
if (collectionName == null || "".equals(collectionName))
return false;
Set<String> collections = getCollectionNames();
if (collections.isEmpty())
return false;
for (String collection : collections)
{
if (collectionName.equalsIgnoreCase(collection))
return true;
}
return false;
}
/**
* Returns the name of this database.
*
* @return the name
*/
@Override
public String toString(){
return _name;
}
/**
* Returns the error status of the last operation on the current connection. The result of this command will look like:
* <pre>
* {@code
* { "err" : errorMessage , "ok" : 1.0 }
* }</pre>
* The value for errorMessage will be null if no error occurred, or a description otherwise.
* <p> Important note: when calling this method directly, it is undefined which connection "getLastError" is called on. You may need
* to explicitly use a "consistent Request", see {@link DB#requestStart()} It is better not to call this method directly but instead
* use {@link WriteConcern} </p>
*
* @return {@code DBObject} with error and status information
* @throws MongoException
* @see WriteConcern#ACKNOWLEDGED
* @deprecated The getlasterror command will not be supported in future versions of MongoDB. Use acknowledged writes instead.
*/
@Deprecated
public CommandResult getLastError(){
return command(new BasicDBObject("getlasterror", 1));
}
/**
* Returns the error status of the last operation on the current connection.
*
* @param concern a {@link WriteConcern} to be used while checking for the error status.
* @return {@code DBObject} with error and status information
* @throws MongoException
* @deprecated The getlasterror command will not be supported in future versions of MongoDB. Use acknowledged writes instead.
* @see WriteConcern#ACKNOWLEDGED
*/
@Deprecated
public CommandResult getLastError( com.mongodb.WriteConcern concern ){
return command( concern.getCommand() );
}
/**
* Returns the error status of the last operation on the current connection.
*
* @param w when running with replication, this is the number of servers to replicate to before returning. A <b>w</b> value of <b>1</b> indicates the primary only. A <b>w</b> value of <b>2</b> includes the primary and at least one secondary, etc. In place of a number, you may also set <b>w</b> to majority to indicate that the command should wait until the latest write propagates to a majority of replica set members. If using <b>w</b>, you should also use <b>wtimeout</b>. Specifying a value for <b>w</b> without also providing a <b>wtimeout</b> may cause {@code getLastError} to block indefinitely.
* @param wtimeout a value in milliseconds that controls how long to wait for write propagation to complete. If replication does not complete in the given timeframe, the getLastError command will return with an error status.
* @param fsync if <b>true</b>, wait for {@code mongod} to write this data to disk before returning. Defaults to <b>false</b>.
* @return {@code DBObject} with error and status information
* @throws MongoException
* @deprecated The getlasterror command will not be supported in future versions of MongoDB. Use acknowledged writes instead.
* @see WriteConcern#ACKNOWLEDGED
*/
@Deprecated
public CommandResult getLastError( int w , int wtimeout , boolean fsync ){
return command( (new com.mongodb.WriteConcern( w, wtimeout , fsync )).getCommand() );
}
/**
* Sets the write concern for this database. It will be used for
* write operations to any collection in this database. See the
* documentation for {@link WriteConcern} for more information.
*
* @param concern {@code WriteConcern} to use
*/
public void setWriteConcern( com.mongodb.WriteConcern concern ){
if (concern == null) throw new IllegalArgumentException();
_concern = concern;
}
/**
* Gets the write concern for this database.
*
* @return {@code WriteConcern} to be used for write operations, if not specified explicitly
*/
public com.mongodb.WriteConcern getWriteConcern(){
if ( _concern != null )
return _concern;
return _mongo.getWriteConcern();
}
/**
* Sets the read preference for this database. Will be used as default for
* read operations from any collection in this database. See the
* documentation for {@link ReadPreference} for more information.
*
* @param preference {@code ReadPreference} to use
*/
public void setReadPreference( ReadPreference preference ){
_readPref = preference;
}
/**
* Gets the read preference for this database.
*
* @return {@code ReadPreference} to be used for read operations, if not specified explicitly
*/
public ReadPreference getReadPreference(){
if ( _readPref != null )
return _readPref;
return _mongo.getReadPreference();
}
/**
* Drops this database, deleting the associated data files. Use with caution.
*
* @throws MongoException
*/
public void dropDatabase(){
CommandResult res = command(new BasicDBObject("dropDatabase", 1));
res.throwOnError();
_mongo._dbs.remove(this.getName());
}
/**
* Returns {@code true} if a user has been authenticated on this database.
*
* @return {@code true} if authenticated, {@code false} otherwise
* @dochub authenticate
* @deprecated Please use {@link MongoClient#MongoClient(java.util.List, java.util.List)} to create a client, which
* will authenticate all connections to server
*/
@Deprecated
public boolean isAuthenticated() {
return getAuthenticationCredentials() != null;
}
/**
* Authenticates to db with the given credentials. If this method (or {@code authenticateCommand}) has already been
* called with the same credentials and the authentication test succeeded, this method will return {@code true}. If this method
* has already been called with different credentials and the authentication test succeeded,
* this method will throw an {@code IllegalStateException}. If this method has already been called with any credentials
* and the authentication test failed, this method will re-try the authentication test with the
* given credentials.
*
* @param username name of user for this database
* @param password password of user for this database
* @return true if authenticated, false otherwise
* @throws MongoException if authentication failed due to invalid user/pass, or other exceptions like I/O
* @throws IllegalStateException if authentication test has already succeeded with different credentials
* @dochub authenticate
* @see #authenticateCommand(String, char[])
* @deprecated Please use {@link MongoClient#MongoClient(java.util.List, java.util.List)} to create a client, which
* will authenticate all connections to server
*/
@Deprecated
public boolean authenticate(String username, char[] password) {
return authenticateCommandHelper(username, password).failure == null;
}
/**
* Authenticates to db with the given credentials. If this method (or {@code authenticate}) has already been
* called with the same credentials and the authentication test succeeded, this method will return true. If this method
* has already been called with different credentials and the authentication test succeeded,
* this method will throw an {@code IllegalStateException}. If this method has already been called with any credentials
* and the authentication test failed, this method will re-try the authentication test with the
* given credentials.
*
* @param username name of user for this database
* @param password password of user for this database
* @return the CommandResult from authenticate command
* @throws MongoException if authentication failed due to invalid user/pass, or other exceptions like I/O
* @throws IllegalStateException if authentication test has already succeeded with different credentials
* @dochub authenticate
* @see #authenticate(String, char[])
* @deprecated Please use {@link MongoClient#MongoClient(java.util.List, java.util.List)} to create a client, which
* will authenticate all connections to server
*/
@Deprecated
public synchronized CommandResult authenticateCommand(String username, char[] password) {
CommandResultPair commandResultPair = authenticateCommandHelper(username, password);
if (commandResultPair.failure != null) {
throw commandResultPair.failure;
}
return commandResultPair.result;
}
private CommandResultPair authenticateCommandHelper(String username, char[] password) {
MongoCredential credentials =
MongoCredential.createMongoCRCredential(username, getName(), password);
if (getAuthenticationCredentials() != null) {
if (getAuthenticationCredentials().equals(credentials)) {
if (authenticationTestCommandResult != null) {
return new CommandResultPair(authenticationTestCommandResult);
}
} else {
throw new IllegalStateException("can't authenticate twice on the same database");
}
}
try {
authenticationTestCommandResult = doAuthenticate(credentials);
return new CommandResultPair(authenticationTestCommandResult);
} catch (CommandFailureException commandFailureException) {
return new CommandResultPair(commandFailureException);
}
}
class CommandResultPair {
CommandResult result;
CommandFailureException failure;
public CommandResultPair(final CommandResult result) {
this.result = result;
}
public CommandResultPair(final CommandFailureException failure) {
this.failure = failure;
}
}
abstract CommandResult doAuthenticate(MongoCredential credentials);
/**
* Adds or updates a user for this database
*
* @param username the user name
* @param passwd the password
* @return the result of executing this operation
* @throws MongoException
* @mongodb.driver.manual administration/security-access-control/ Access Control
* @deprecated Use {@code DB.command} to call either the addUser or updateUser command
*/
@Deprecated
public WriteResult addUser( String username , char[] passwd ){
return addUser(username, passwd, false);
}
/**
* Adds or updates a user for this database
*
* @param username the user name
* @param passwd the password
* @param readOnly if true, user will only be able to read
* @return the result of executing this operation
* @throws MongoException
* @mongodb.driver.manual administration/security-access-control/ Access Control
* @deprecated Use {@code DB.command} to call either the addUser or updateUser command
*/
@Deprecated
public WriteResult addUser( String username , char[] passwd, boolean readOnly ){
DBCollection c = getCollection( "system.users" );
DBObject o = c.findOne( new BasicDBObject( "user" , username ) );
if ( o == null )
o = new BasicDBObject( "user" , username );
o.put( "pwd" , _hash( username , passwd ) );
o.put( "readOnly" , readOnly );
return c.save( o );
}
/**
* Removes the specified user from the database.
*
* @param username user to be removed
* @return the result of executing this operation
* @throws MongoException
* @mongodb.driver.manual administration/security-access-control/ Access Control
* @deprecated Use {@code DB.command} to call the dropUser command
*/
@Deprecated
public WriteResult removeUser( String username ){
DBCollection c = getCollection( "system.users" );
return c.remove(new BasicDBObject( "user" , username ));
}
String _hash( String username , char[] passwd ){
ByteArrayOutputStream bout = new ByteArrayOutputStream( username.length() + 20 + passwd.length );
try {
bout.write( username.getBytes() );
bout.write( ":mongo:".getBytes() );
for ( int i=0; i<passwd.length; i++ ){
if ( passwd[i] >= 128 )
throw new IllegalArgumentException( "can't handle non-ascii passwords yet" );
bout.write( (byte)passwd[i] );
}
}
catch ( IOException ioe ){
throw new RuntimeException( "impossible" , ioe );
}
return Util.hexMD5( bout.toByteArray() );
}
/**
* Returns the last error that occurred since start of database or a call to {@link com.mongodb.DB#resetError()} The return object
* will look like:
* <pre>
* {@code
* { err : errorMessage, nPrev : countOpsBack, ok : 1 }
* }</pre>
* The value for errorMessage will be null of no error has occurred, otherwise the error message.
* The value of countOpsBack will be the number of operations since the error occurred.
* <p> Care must be taken to ensure that calls to getPreviousError go to the same connection as that
* of the previous operation. See {@link DB#requestStart()} for more information.</p>
*
* @return {@code DBObject} with error and status information
* @throws MongoException
* @deprecated The getlasterror command will not be supported in future versions of MongoDB. Use acknowledged writes instead.
* @see WriteConcern#ACKNOWLEDGED
*/
@Deprecated
public CommandResult getPreviousError(){
return command(new BasicDBObject("getpreverror", 1));
}
/**
* Resets the error memory for this database.
* Used to clear all errors such that {@link DB#getPreviousError()} will return no error.
*
* @throws MongoException
* @deprecated The getlasterror command will not be supported in future versions of MongoDB. Use acknowledged writes instead.
* @see WriteConcern#ACKNOWLEDGED
*/
@Deprecated
public void resetError(){
command(new BasicDBObject("reseterror", 1));
}
/**
* For testing purposes only - this method forces an error to help test error handling
*
* @throws MongoException
* @deprecated The getlasterror command will not be supported in future versions of MongoDB. Use acknowledged writes instead.
* @see WriteConcern#ACKNOWLEDGED
*/
@Deprecated
public void forceError(){
command(new BasicDBObject("forceerror", 1));
}
/**
* Gets the {@link Mongo} instance
*
* @return the instance of {@link Mongo} this database belongs to
*/
public Mongo getMongo(){
return _mongo;
}
/**
* Gets another database on same server
*
* @param name name of the database
* @return the database
*/
public DB getSisterDB( String name ){
return _mongo.getDB( name );
}
/**
* Makes it possible to execute "read" queries on a slave node
*
* @see ReadPreference#secondaryPreferred()
* @deprecated Replaced with {@code ReadPreference.secondaryPreferred()}
*/
@Deprecated
public void slaveOk(){
addOption( Bytes.QUERYOPTION_SLAVEOK );
}
/**
* Adds the given flag to the default query options.
*
* @param option value to be added
*/
public void addOption( int option ){
_options.add( option );
}
/**
* Sets the default query options, overwriting previous value.
*
* @param options bit vector of query options
*/
public void setOptions( int options ){
_options.set( options );
}
/**
* Resets the query options.
*/
public void resetOptions(){
_options.reset();
}
/**
* Gets the default query options
*
* @return bit vector of query options
*/
public int getOptions(){
return _options.get();
}
private boolean isValidName(String dbname){
return dbname.length() != 0 && !dbname.contains(" ");
}
/**
* Forcefully kills any cursors leaked by neglecting to call {@code DBCursor.close}
*
* @param force true if should clean regardless of number of dead cursors
* @see com.mongodb.DBCursor#close()
* @deprecated Clients should ensure that {@link DBCursor#close()} is called.
*/
@Deprecated
public abstract void cleanCursors( boolean force );
MongoCredential getAuthenticationCredentials() {
return getMongo().getAuthority().getCredentialsStore().get(getName());
}
final Mongo _mongo;
final String _name;
/**
* @deprecated See {@link #setReadOnly(Boolean)}
*/
@Deprecated
protected boolean _readOnly = false;
private com.mongodb.WriteConcern _concern;
private com.mongodb.ReadPreference _readPref;
final Bytes.OptionHolder _options;
// cached authentication command result, to return in case of multiple calls to authenticateCommand with the
// same credentials
private volatile CommandResult authenticationTestCommandResult;