This repository has been archived by the owner on Mar 11, 2022. It is now read-only.
/
Database.java
1494 lines (1422 loc) · 57.7 KB
/
Database.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright © 2016, 2021 IBM Corp. All rights reserved.
*
* 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.cloudant.client.api;
import static com.cloudant.client.org.lightcouch.internal.CouchDbUtil.assertNotEmpty;
import static com.cloudant.client.org.lightcouch.internal.CouchDbUtil.assertNotNull;
import static com.cloudant.client.org.lightcouch.internal.CouchDbUtil.close;
import static com.cloudant.client.org.lightcouch.internal.CouchDbUtil.createPost;
import static com.cloudant.client.org.lightcouch.internal.CouchDbUtil.getAsString;
import static com.cloudant.client.org.lightcouch.internal.CouchDbUtil.getResponse;
import static com.cloudant.client.org.lightcouch.internal.CouchDbUtil.getResponseList;
import com.cloudant.client.api.model.DbInfo;
import com.cloudant.client.api.model.FindByIndexOptions;
import com.cloudant.client.api.model.Index;
import com.cloudant.client.api.model.IndexField;
import com.cloudant.client.api.model.Params;
import com.cloudant.client.api.model.PartitionInfo;
import com.cloudant.client.api.model.Permissions;
import com.cloudant.client.api.query.QueryResult;
import com.cloudant.client.api.model.Shard;
import com.cloudant.client.api.query.Indexes;
import com.cloudant.client.api.query.JsonIndex;
import com.cloudant.client.api.views.AllDocsRequestBuilder;
import com.cloudant.client.api.views.ViewRequestBuilder;
import com.cloudant.client.internal.DatabaseURIHelper;
import com.cloudant.client.internal.URIBase;
import com.cloudant.client.internal.query.Helpers;
import com.cloudant.client.internal.util.DeserializationTypes;
import com.cloudant.client.internal.views.AllDocsRequestBuilderImpl;
import com.cloudant.client.internal.views.AllDocsRequestResponse;
import com.cloudant.client.internal.views.ViewQueryParameters;
import com.cloudant.client.org.lightcouch.CouchDatabase;
import com.cloudant.client.org.lightcouch.CouchDbException;
import com.cloudant.client.org.lightcouch.DocumentConflictException;
import com.cloudant.client.org.lightcouch.NoDocumentException;
import com.cloudant.client.org.lightcouch.Response;
import com.cloudant.client.org.lightcouch.internal.CouchDbUtil;
import com.cloudant.http.Http;
import com.cloudant.http.HttpConnection;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import com.google.gson.reflect.TypeToken;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.URI;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.logging.Logger;
/**
* Contains a Database Public API implementation.
*
* Methods may throw a {@link NoDocumentException} if the database does not exist.
*
* @author Mario Briggs
* @since 0.0.1
*/
public class Database {
static final Logger log = Logger.getLogger(Database.class.getCanonicalName());
private CouchDatabase db;
private CloudantClient client;
private final URI apiV2DBSecurityURI;
/**
* Internal constructor for creating a new Database instance.
*
* @param client the CloudantClient instance to connect with
* @param db the CouchDatabase for executing operations
*/
Database(CloudantClient client, CouchDatabase db) {
super();
this.client = client;
this.db = db;
apiV2DBSecurityURI = new URIBase(client.getBaseUri()).path("_api").path("v2").path("db")
.path(db.getDbName()).path("_security").build();
}
/**
* Constructor for subclasses that want to override Database methods. The supplied Database
* instance is used to instantiate the super class. As such for non-overridden methods the
* implementation of the extending class will be identical to the original Database instance.
*
* Usage example:
* <pre>
* {@code
* public class ExtendedDatabase extends Database {
* public ExtendedDatabase(Database database) {
* super(database);
* }
* }
* }
* </pre>
*
* @param db existing Database instance
* @since 2.3.0
*/
protected Database(Database db) {
this(db.client, db.db);
}
/**
* Set permissions for a user/apiKey on this database.
* <p>
* Note this method is only applicable to databases that support the
* <a target="_blank"
* href="https://console.bluemix.net/docs/services/Cloudant/api/authorization.html#authorization">
* Cloudant authorization API
* </a> such as Cloudant DBaaS. For unsupported databases consider using the /db/_security
* endpoint.
* </p>
* <p>Example usage to set read-only access for a new key on the "example" database:</p>
* <pre>
* {@code
* // generate an API key
* ApiKey key = client.generateApiKey();
*
* // get the "example" database
* Database db = client.database("example", false);
*
* // set read-only permissions
* db.setPermissions(key.getKey(), EnumSet.<Permissions>of(Permissions._reader));
* }
* </pre>
*
* @param userNameorApikey the user or key to apply permissions to
* @param permissions permissions to grant
* @throws UnsupportedOperationException if called on a database that does not provide the
* Cloudant authorization API
* @see CloudantClient#generateApiKey()
* @see <a
* href="https://console.bluemix.net/docs/services/Cloudant/api/authorization.html#roles"
* target="_blank">Roles</a>
* @see <a
* href="https://console.bluemix.net/docs/services/Cloudant/api/authorization.html#modifying-permissions"
* target="_blank">Modifying permissions</a>
*/
public void setPermissions(String userNameorApikey, EnumSet<Permissions> permissions) {
assertNotEmpty(userNameorApikey, "userNameorApikey");
assertNotEmpty(permissions, "permissions");
final JsonArray jsonPermissions = new JsonArray();
for (Permissions s : permissions) {
final JsonPrimitive permission = new JsonPrimitive(s.toString());
jsonPermissions.add(permission);
}
// get existing permissions
JsonObject perms = getPermissionsObject();
// now set back
JsonElement elem = perms.get("cloudant");
if (elem == null) {
perms.addProperty("_id", "_security");
elem = new JsonObject();
perms.add("cloudant", elem);
}
elem.getAsJsonObject().add(userNameorApikey, jsonPermissions);
HttpConnection put = Http.PUT(apiV2DBSecurityURI, "application/json");
put.setRequestBody(client.getGson().toJson(perms));
// CouchDbExceptions will be thrown for non-2XX cases
client.couchDbClient.executeToResponse(put);
}
/**
* @return /api/v2/db/$dbname/_security JSON data
* @throws UnsupportedOperationException if called on a database that does not provide the
* Cloudant authorization API
*/
private JsonObject getPermissionsObject() {
try {
return client.couchDbClient.get(apiV2DBSecurityURI, JsonObject.class);
} catch (CouchDbException exception) {
//currently we can't inspect the HttpResponse code
//being in this catch block means it was not a 20x code
//look for the "bad request" that implies the endpoint is not supported
if (exception.getMessage().toLowerCase(Locale.ENGLISH).contains("bad request")) {
throw new UnsupportedOperationException("The methods getPermissions and " +
"setPermissions are not supported for this database, consider using the " +
"/db/_security endpoint.");
} else {
throw exception;
}
}
}
/**
* Returns the Permissions of this database.
* <p>
* Note this method is only applicable to databases that support the
* <a target="_blank"
* href="https://console.bluemix.net/docs/services/Cloudant/api/authorization.html#authorization">
* Cloudant authorization API
* </a> such as Cloudant DBaaS. For unsupported databases consider using the /db/_security
* endpoint.
* </p>
*
* @return the map of userNames to their Permissions
* @throws UnsupportedOperationException if called on a database that does not provide the
* Cloudant authorization API
* @see <a
* href="https://console.bluemix.net/docs/services/Cloudant/api/authorization.html#roles"
* target="_blank">Roles</a>
* @see <a
* href="https://console.bluemix.net/docs/services/Cloudant/api/authorization.html#viewing-permissions"
* target="_blank">Viewing permissions</a>
*/
public Map<String, EnumSet<Permissions>> getPermissions() {
JsonObject perms = getPermissionsObject();
return client.getGson().getAdapter(DeserializationTypes.PERMISSIONS_MAP_TOKEN).fromJsonTree
(perms);
}
/**
* Get info about the shards in the database.
*
* @return List of shards
* @see <a
* href="https://console.bluemix.net/docs/services/Cloudant/api/advanced.html#-get-database-_shards-"
* target="_blank">_shards</a>
*/
public List<Shard> getShards() {
InputStream response = null;
try {
response = client.couchDbClient.get(new DatabaseURIHelper(db.getDBUri()).path("_shards")
.build());
return getResponseList(response, client.getGson(), DeserializationTypes.SHARDS);
} finally {
close(response);
}
}
/**
* Get info about the shard a document belongs to.
*
* @param docId document ID
* @return Shard info
* @see <a
* href="https://console.bluemix.net/docs/services/Cloudant/api/advanced.html#-get-database-_shards-"
* target="_blank">_shards</a>
*/
public Shard getShard(String docId) {
assertNotEmpty(docId, "docId");
return client.couchDbClient.get(new DatabaseURIHelper(db.getDBUri()).path("_shards")
.path(docId).build(),
Shard.class);
}
/**
* Create a new JSON index
* <P>
* Example usage creating an index that sorts ascending on name, then by year:
* </P>
* <pre>
* {@code
* db.createIndex("Person_name", "Person_name", null, new IndexField[]{
* new IndexField("Person_name",SortOrder.asc),
* new IndexField("Movie_year",SortOrder.asc)});
* }
* </pre>
* <P>
* Example usage creating an index that sorts ascending by year:
* </P>
* <pre>
* {@code
* db.createIndex("Movie_year", "Movie_year", null, new IndexField[]{
* new IndexField("Movie_year",SortOrder.asc)});
* }
* </pre>
*
* @param indexName optional name of the index (if not provided one will be generated)
* @param designDocName optional name of the design doc in which the index will be created
* @param indexType optional, type of index (only "json" for this method)
* @param fields array of fields in the index
* @see Database#createIndex(String)
*/
@Deprecated
public void createIndex(String indexName, String designDocName, String indexType,
IndexField[] fields) {
if (indexType == null || "json".equalsIgnoreCase(indexType)) {
JsonIndex.Builder b = JsonIndex.builder().name(indexName).designDocument(designDocName);
for (IndexField f : fields) {
switch (f.getOrder()) {
case desc:
b.desc(f.getName());
break;
case asc:
default:
b.asc(f.getName());
break;
}
}
createIndex(b.definition());
} else {
throw new CouchDbException("Unsupported index type " + indexType);
}
}
/**
* <p>
* Create a new index from a string of JSON representing the index definition
* </p>
* <p>
* Helpers are available to construct the index definition string for JSON and text indexes.
* </p>
* <p>
* Example usage creating a JSON index with a generated name for the field named "Movie_year"
* with ascending sort order:
* </p>
* <pre>
* {@code
* db.createIndex(JsonIndex.builder().asc("Movie_year").definition());
* }
* </pre>
* <p>
* Example usage creating a partial JSON index named "movies-after-2010-json" which will
* index all movies with "Movie_year" greater than 2010, returning the field "Movie_year" in
* descending order:
* </p>
* <pre>
* {@code
* Selector selector = gt("Movie_year", 2010);
* String indexDefinition = JsonIndex.builder().
* name("movies-after-2010-json").
* desc("Movie_year").
* partialFilterSelector(selector).
* definition();
* db.createIndex(indexDefinition);
* }
* </pre>
* <p>
* Example usage creating a text index with a generated name for the string field named
* "Movie_title":
* </p>
* <pre>
* {@code
* db.createIndex(TextIndex.builder().string("Movie_title").definition());
* }
* </pre>
* <p>
* Example usage creating a partial text index named "movies-after-2010-text" for the string field
* named "Movie_title" which will index all movies titles for movies with "Movie_year" greater
* than 2010:
* </p>
* <pre>
* {@code
* Selector selector = gt("Movie_year", 2010);
* String indexDefinition = TextIndex.builder().
* string("Movie_title").
* name("movies-after-2010-text").
* partialFilterSelector(selector).
* definition();
* db.createIndex(indexDefinition);
* }
* </pre>
*
* @param indexDefinition String representation of the index definition JSON
* @see com.cloudant.client.api.query.JsonIndex.Builder
* @see com.cloudant.client.api.query.TextIndex.Builder
* @see <a
* href="https://console.bluemix.net/docs/services/Cloudant/api/cloudant_query.html#creating-an-index"
* target="_blank">index definition</a>
*/
public void createIndex(String indexDefinition) {
assertNotEmpty(indexDefinition, "indexDefinition");
InputStream putresp = null;
URI uri = new DatabaseURIHelper(db.getDBUri()).path("_index").build();
try {
putresp = client.couchDbClient.executeToInputStream(createPost(uri, indexDefinition,
"application/json"));
String result = getAsString(putresp, "result");
if (result.equalsIgnoreCase("created")) {
log.info(String.format("Created Index: '%s'", indexDefinition));
} else {
log.warning(String.format("Index already exists : '%s'", indexDefinition));
}
} finally {
close(putresp);
}
}
/**
* Find documents using an index
*
* @param selectorJson String representation of a JSON object describing criteria used to
* select documents. For example:
* {@code "{ \"selector\": {<your data here>} }"}.
* @param classOfT The class of Java objects to be returned
* @param <T> the type of the Java object to be returned
* @return List of classOfT objects
* @see #findByIndex(String, Class, FindByIndexOptions)
* @see <a
* href="https://console.bluemix.net/docs/services/Cloudant/api/cloudant_query.html#selector-syntax"
* target="_blank">selector syntax</a>
* @deprecated Use {@link #query(String, Class)} instead
*/
@Deprecated
public <T> List<T> findByIndex(String selectorJson, Class<T> classOfT) {
return findByIndex(selectorJson, classOfT, new FindByIndexOptions());
}
/**
* Find documents using an index
* <P>
* Example usage to return the name and year of movies starring
* Alec Guinness since 1960 with the results sorted by year descending:
* </P>
* <pre>
* {@code
* List <Movie> movies = db.findByIndex("\"selector\": {
* \"Movie_year\": {\"$gt\": 1960}, \"Person_name\": \"Alec Guinness\"
* }",
* Movie.class,
* new FindByIndexOptions()
* .sort(new IndexField("Movie_year", SortOrder.desc))
* .fields("Movie_name").fields("Movie_year"));
* }
* </pre>
*
* @param selectorJson String representation of a JSON object describing criteria used to
* select documents. For example:
* {@code "{ \"selector\": {<your data here>} }"}.
* @param options {@link FindByIndexOptions query Index options}
* @param classOfT The class of Java objects to be returned
* @param <T> the type of the Java object to be returned
* @return List of classOfT objects
* @see <a
* href="https://console.bluemix.net/docs/services/Cloudant/api/cloudant_query.html#selector-syntax"
* target="_blank">selector syntax</a>
* @deprecated Use {@link #query(String, Class)} instead
*/
@Deprecated
public <T> List<T> findByIndex(String selectorJson, Class<T> classOfT, FindByIndexOptions
options) {
JsonObject selector = Helpers.getSelectorFromString(selectorJson);
assertNotEmpty(options, "options");
JsonObject body = getFindByIndexBody(selector, options);
return query(body.toString(), classOfT).getDocs();
}
/**
* <p>
* Query documents using an index and a query selector.
* </p>
* <p>
* Note: the most convenient way to generate query selectors is using a
* {@link com.cloudant.client.api.query.QueryBuilder}.
* </p>
* <p>
* Example usage to return the name and year of movies starring Alec Guinness since 1960
* with the results sorted by year descending:
* </p>
* <pre>
* {@code
* QueryResult<Movie> movies = db.query(new QueryBuilder(and(
* gt("Movie_year", 1960),
* eq("Person_name", "Alec Guinness"))).
* sort(Sort.desc("Movie_year")).
* fields("Movie_name", "Movie_year").
* build(), Movie.class);
* }
* </pre>
* @param query String representation of a JSON object describing criteria used to
* select documents.
* @param classOfT The class of Java objects to be returned in the {@code docs} field of result.
* @param <T> The type of the Java object to be returned in the {@code docs} field of result.
* @return A {@link QueryResult} object, containing the documents matching the query
* in the {@code docs} field.
* @see com.cloudant.client.api.query.QueryBuilder
* @see <a
* href="https://console.bluemix.net/docs/services/Cloudant/api/cloudant_query.html#selector-syntax"
* target="_blank">selector syntax</a>
*/
public <T> QueryResult<T> query(String query, final Class<T> classOfT) {
URI uri = new DatabaseURIHelper(db.getDBUri()).path("_find").build();
return this.query(uri, query, classOfT);
}
/**
* Execute a partitioned query using an index and a query selector.
*
* Only available in partitioned databases. To verify a database is partitioned call
* {@link Database#info()} and check that {@link DbInfo.Props#getPartitioned()} returns
* {@code true}.
*
* <p>Example usage:</p>
* <pre>
* {@code
* // Query database partition 'Coppola'.
* QueryResult<Movie> movies = db.query("Coppola", new QueryBuilder(and(
* gt("Movie_year", 1960),
* eq("Person_name", "Al Pacino"))).
* fields("Movie_name", "Movie_year").
* build(), Movie.class);
* }
* </pre>
*
* @param partitionKey Database partition to query.
* @param query String representation of a JSON object describing criteria used to
* select documents.
* @param classOfT The class of Java objects to be returned in the {@code docs} field of
* result.
* @param <T> The type of the Java object to be returned in the {@code docs} field of
* result.
* @return A {@link QueryResult} object, containing the documents matching the query
* in the {@code docs} field.
* @see com.cloudant.client.api.Database#query(String, Class)
*/
public <T> QueryResult<T> query(String partitionKey, String query, final Class<T> classOfT) {
URI uri = new DatabaseURIHelper(db.getDBUri()).partition(partitionKey).path("_find").build();
return this.query(uri, query, classOfT);
}
private <T> QueryResult<T> query(URI uri, String query, final Class<T> classOfT) {
InputStream stream = null;
try {
stream = client.couchDbClient.executeToInputStream(createPost(uri, query,
"application/json"));
Reader reader = new InputStreamReader(stream, "UTF-8");
Type type = TypeToken.getParameterized(QueryResult.class, classOfT).getType();
return client.getGson().fromJson(reader, type);
} catch (UnsupportedEncodingException e) {
// This should never happen as every implementation of the java platform is required
// to support UTF-8.
throw new RuntimeException(e);
} finally {
close(stream);
}
}
/**
* List all indices
* <P>Example usage:</P>
* <pre>
* {@code
* List <Index> indices = db.listIndices();
* }
* </pre>
*
* @return List of Index objects
* @see Database#listIndexes()
*/
@Deprecated
public List<Index> listIndices() {
InputStream response = null;
try {
URI uri = new DatabaseURIHelper(db.getDBUri()).path("_index").build();
response = client.couchDbClient.get(uri);
return getResponseList(response, client.getGson(), DeserializationTypes.INDICES);
} finally {
close(response);
}
}
/**
* List the indexes in the database. The returned object allows for listing indexes by type.
*
* @return indexes object with methods for getting indexes of a particular type
*/
public Indexes listIndexes() {
URI uri = new DatabaseURIHelper(db.getDBUri()).path("_index").build();
return client.couchDbClient.get(uri, Indexes.class);
}
/**
* Delete a JSON index
*
* @param indexName name of the index
* @param designDocId ID of the design doc
*/
public void deleteIndex(String indexName, String designDocId) {
deleteIndex(indexName, designDocId, "json");
}
/**
* Delete an index with the specified name and type in the given design document.
*
* @param indexName name of the index
* @param designDocId ID of the design doc (the _design prefix will be added if not present)
* @param type type of the index, valid values or "text" or "json"
*/
public void deleteIndex(String indexName, String designDocId, String type) {
assertNotEmpty(indexName, "indexName");
assertNotEmpty(designDocId, "designDocId");
assertNotNull(type, "type");
if (!designDocId.startsWith(CouchDbUtil.DESIGN_PREFIX)) {
designDocId = CouchDbUtil.DESIGN_PREFIX + designDocId;
}
URI uri = new DatabaseURIHelper(db.getDBUri()).path("_index").path(designDocId)
.path(type).path(indexName).build();
InputStream response = null;
try {
HttpConnection connection = Http.DELETE(uri);
response = client.couchDbClient.executeToInputStream(connection);
getResponse(response, Response.class, client.getGson());
} finally {
close(response);
}
}
/**
* Provides access to Cloudant <tt>Search</tt> APIs.
*
* <p>Example usage:</p>
* <pre>
* {@code
* // Search query using design document _id '_design/views101' and search index 'animals'
* List<Bird> birds = db.search("views101/animals")
* .limit(10)
* .includeDocs(true)
* .query("class:bird", Bird.class);
* }
* </pre>
*
* @param searchIndexId the design document with the name of the index to search
* @return Search object for searching the index
* @see <a
* href="https://console.bluemix.net/docs/services/Cloudant/api/search.html#search"
* target="_blank">Search</a>
*/
public Search search(String searchIndexId) {
return new Search(client, this, null, searchIndexId);
}
/**
* Provides access to partitioned Cloudant <tt>Search</tt> APIs.
*
* Only available in partitioned databases. To verify a database is partitioned call
* {@link Database#info()} and check that {@link DbInfo.Props#getProps()} returns
* {@code true}.
*
* <p>Example usage:</p>
* <pre>
* {@code
* // Search query over partition 'aves' using design document _id '_design/views101' and
* // search index 'partitioned_animals'.
* List<Bird> birds = db.search("aves", "views101/partitioned_animals")
* .query("name:puffin", Bird.class);
* }
* </pre>
*
* @param partitionKey database partition key
* @param searchIndexId the design document with the name of the index to search
* @return Search object for searching the index
* @see <a
* href="https://console.bluemix.net/docs/services/Cloudant/api/search.html#search"
* target="_blank">Search</a>
*/
public Search search(String partitionKey, String searchIndexId) {
return new Search(client, this, partitionKey, searchIndexId);
}
/**
* Get a manager that has convenience methods for managing design documents.
*
* @return a {@link DesignDocumentManager} for this database
* @see DesignDocumentManager
*/
public DesignDocumentManager getDesignDocumentManager() {
return new DesignDocumentManager(client, this);
}
/**
* @param designDoc containing the view
* @param viewName the view name
* @return a builder to build view requests for the specified design document and view of
* this database
* @see <a
* href="https://console.bluemix.net/docs/services/Cloudant/api/using_views.html#using-views"
* target="_blank">Using views</a>
*/
public ViewRequestBuilder getViewRequestBuilder(String designDoc, String viewName) {
return new ViewRequestBuilder(client, this, designDoc, viewName);
}
/**
* Build a request for the _all_docs endpoint.
* <P>
* Example usage:
* </P>
* <pre>
* {@code
* getAllDocsRequestBuilder().build().getResponse();
* }
* </pre>
*
* @return a request builder for the _all_docs endpoint of this database
*/
public AllDocsRequestBuilder getAllDocsRequestBuilder() {
return new AllDocsRequestBuilderImpl(new ViewQueryParameters<String,
AllDocsRequestResponse.AllDocsValue>(client, this, "", "", String.class,
AllDocsRequestResponse.AllDocsValue.class) {
protected DatabaseURIHelper getViewURIBuilder() {
return new DatabaseURIHelper(db.getDBUri()).partition(partition).path("_all_docs");
}
});
}
/**
* Provides access for interacting with the changes feed.
* <P>
* See the {@link com.cloudant.client.api.Changes} API for examples.
* </P>
*
* @return a Changes object for using the changes feed
* @see com.cloudant.client.api.Changes
* @see <a
* href="https://console.bluemix.net/docs/services/Cloudant/api/database.html#get-changes"
* target="_blank">Databases - get changes</a>
*/
public Changes changes() {
return new Changes(client, this);
}
/**
* Retrieve the document with the specified ID from the database and deserialize to an
* instance of the POJO of type T.
*
* @param <T> object type
* @param classType the class of type T
* @param id the document id
* @return an object of type T
* @throws NoDocumentException if the document is not found in the database
* @see #find(Class, String, String)
* @see <a
* href="https://console.bluemix.net/docs/services/Cloudant/api/document.html#read"
* target="_blank">Documents - read</a>
*/
public <T> T find(Class<T> classType, String id) {
return db.find(classType, id);
}
/**
* Retrieve the document with the specified ID from the database and deserialize to an
* instance of the POJO of type T. Uses the additional parameters specified when making the
* {@code GET} request.
* <P>Example usage to get inline attachments:</P>
* <pre>
* {@code
* Foo foo = db.find(Foo.class, "exampleId", new Params().attachments());
* String attachmentData = foo.getAttachments().get("attachment.txt").getData();
* }
* </pre>
*
* @param <T> object type
* @param classType the class of type T
* @param id the document id
* @param params extra parameters to append
* @return An object of type T
* @throws NoDocumentException if the document is not found in the database.
* @see Params
* @see <a
* href="https://console.bluemix.net/docs/services/Cloudant/api/document.html#read"
* target="_blank">Documents - read</a>
*/
public <T> T find(Class<T> classType, String id, Params params) {
assertNotEmpty(params, "params");
return db.find(classType, id, params.getInternalParams());
}
/**
* Retrieve the document with the specified ID at the specified revision from the database
* and deserialize to an instance of the POJO of type T.
* <P>Example usage:</P>
* <pre>
* {@code
* Foo foo = db.find(Foo.class, "exampleId", "1-12345exampleRev");
* }
* </pre>
*
* @param <T> object type
* @param classType the class of type T
* @param id the document _id field
* @param rev the document _rev field
* @return an object of type T
* @throws NoDocumentException if the document is not found in the database.
* @see <a
* href="https://console.bluemix.net/docs/services/Cloudant/api/document.html#read"
* target="_blank">Documents - read</a>
*/
public <T> T find(Class<T> classType, String id, String rev) {
return db.find(classType, id, rev);
}
/**
* This method finds any document given a URI.
* <p>The URI must be URI-encoded.</p>
* <P>
* Example usage retrieving the Foo POJO with document ID "exampleId" from the database
* "exampleDb" in the "example" Cloudant account.
* </P>
* <pre>
* {@code
* Foo foo = db.findAny(Foo.class, "https://example.cloudant.com/exampleDb/exampleId");
* }
* </pre>
*
* @param classType the class of type T
* @param uri the URI as string
* @param <T> the type of Java object to return
* @return an object of type T
*/
public <T> T findAny(Class<T> classType, String uri) {
return db.findAny(classType, uri);
}
/**
* Finds the document with the specified document ID and returns it as an {@link InputStream}.
* <p><b>Note</b>: The stream must be closed after use to release the connection.</p>
*
* @param id the document _id field
* @return the result as {@link InputStream}
* @throws NoDocumentException If the document is not found in the database.
* @see #find(String, String)
*/
public InputStream find(String id) {
return db.find(id);
}
/**
* Finds the document with the specified document ID and revision and returns it as {@link
* InputStream}.
* <p><b>Note</b>: The stream must be closed after use to release the connection.</p>
* <P>Example usage:</P>
* <pre>
* {@code
* InputStream inputStream = null;
* try{
* inputStream = db.find("exampleId", "1-12345exampleRev");
* //do stuff with the stream
* } finally {
* //close the input stream
* inputStream.close();
* }
* }
* </pre>
*
* @param id the document _id field
* @param rev the document _rev field
* @return the result as {@link InputStream}
* @throws NoDocumentException if the document is not found in the database at the specified
* revision
* @see <a
* href="https://console.bluemix.net/docs/services/Cloudant/api/document.html#read"
* target="_blank">Documents - read</a>
*/
public InputStream find(String id, String rev) {
return db.find(id, rev);
}
/**
* Checks if a document exists in the database.
*
* @param id the document _id field
* @return {@code true} if the document is found, {@code false} otherwise
*/
public boolean contains(String id) {
return db.contains(id);
}
/**
* Saves a document in the database.
* <p>If the serialized object's JSON does not contain an {@code _id} field, then a UUID will
* be generated for the document ID.
* </p>
* <P>
* Example of inserting a JsonObject into the database:
* </P>
* <pre>
* {@code
* JsonObject json = new JsonObject();
* json.addProperty("_id", "test-doc-id-2");
* json.add("json-array", new JsonArray());
* Response response = db.save(json);
* }
* </pre>
* <P>
* Example of inserting a POJO into the database:
* </P>
* <pre>
* {@code
* Foo foo = new Foo();
* Response response = db.save(foo);
* }
* </pre>
* <P>
* Example of inserting a Map into the database:
* </P>
* <pre>
* {@code
* Map<String, Object> map = new HashMap<>();
* map.put("_id", "test-doc-id-1");
* map.put("title", "test-doc");
* Response response = db.save(map);
* }
* </pre>
*
* <P>
* Note that the Java object is not modified by the save operation and so will not include the
* revision generated by the database server. You can obtain the server revision for this write
* from the response, for example:
* </P>
* <pre>
* {@code
* Foo foo = new Foo();
* Response response = db.save(foo);
* foo.setRevision(response.getRevision());
* }
* </pre>
*
* @param object the object to save
* @return {@link com.cloudant.client.api.model.Response}
* @throws DocumentConflictException If a conflict is detected during the save.
*/
public com.cloudant.client.api.model.Response save(Object object) {
Response couchDbResponse = db.save(object);
com.cloudant.client.api.model.Response response = new com.cloudant.client.api.model
.Response(couchDbResponse);
return response;
}
/**
* Saves a document in the database similarly to {@link Database#save(Object)} but using a
* specific write quorum.
*
* @param object the object to save
* @param writeQuorum the write quorum
* @return {@link com.cloudant.client.api.model.Response}
* @throws DocumentConflictException If a conflict is detected during the save.
* @see Database#save(Object)
* @see <a
* href="https://console.bluemix.net/docs/services/Cloudant/api/document.html#quorum-writing-and-reading-data"
* target="_blank">Documents - quorum</a>
*/
public com.cloudant.client.api.model.Response save(Object object, int writeQuorum) {
Response couchDbResponse = client.couchDbClient.put(getDBUri(), object, true, writeQuorum);
com.cloudant.client.api.model.Response response = new com.cloudant.client.api.model
.Response(couchDbResponse);
return response;
}
/**
* Creates a document in the database using a HTTP {@code POST} request.
* <p>If the serialized object's JSON does not contain an {@code _id} field, then the server
* will generate a document ID.</p>
* <P>
* Example of creating a document in the database for a POJO:
* </P>
* <pre>
* {@code
* Foo foo = new Foo();
* Response response = db.post(foo);
* }
* </pre>
* <P>
* Note that the Java object is not modified by the create operation and so will not include the
* revision generated by the database server. You can obtain the server revision for this write
* from the response, for example:
* </P>
* <pre>
* {@code
* Foo foo = new Foo();
* Response response = db.post(foo);
* foo.setRevision(response.getRevision());
* }
* </pre>
*
* @param object The object to save
* @return {@link com.cloudant.client.api.model.Response}
* @see <a
* href="https://console.bluemix.net/docs/services/Cloudant/api/document.html#create"
* target="_blank">Documents - create</a>
*/
public com.cloudant.client.api.model.Response post(Object object) {
Response couchDbResponse = db.post(object);
com.cloudant.client.api.model.Response response = new com.cloudant.client.api.model
.Response(couchDbResponse);