public class Database
extends java.lang.Object
NoDocumentException
if the database does not exist.Modifier | Constructor and Description |
---|---|
protected |
Database(Database db)
Constructor for subclasses that want to override Database methods.
|
Modifier and Type | Method and Description |
---|---|
java.util.List<Response> |
bulk(java.util.List<?> objects)
Uses the
_bulk_docs endpoint to insert multiple documents into the database in a
single HTTP request. |
Changes |
changes()
Provides access for interacting with the changes feed.
|
boolean |
contains(java.lang.String id)
Checks if a document exists in the database.
|
void |
createIndex(java.lang.String indexDefinition)
Create a new index from a JSON string
|
void |
createIndex(java.lang.String indexName,
java.lang.String designDocName,
java.lang.String indexType,
IndexField[] fields)
Create a new index
|
void |
deleteIndex(java.lang.String indexName,
java.lang.String designDocId)
Delete an index
|
void |
ensureFullCommit()
Requests the database commits any recent changes to disk.
|
<T> T |
find(java.lang.Class<T> classType,
java.lang.String id)
Retrieve the document with the specified ID from the database and deserialize to an
instance of the POJO of type T.
|
<T> T |
find(java.lang.Class<T> classType,
java.lang.String id,
Params params)
Retrieve the document with the specified ID from the database and deserialize to an
instance of the POJO of type T.
|
<T> T |
find(java.lang.Class<T> classType,
java.lang.String id,
java.lang.String rev)
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.
|
java.io.InputStream |
find(java.lang.String id)
Finds the document with the specified document ID and returns it as an
InputStream . |
java.io.InputStream |
find(java.lang.String id,
java.lang.String rev)
Finds the document with the specified document ID and revision and returns it as
InputStream . |
<T> T |
findAny(java.lang.Class<T> classType,
java.lang.String uri)
This method finds any document given a URI.
|
<T> java.util.List<T> |
findByIndex(java.lang.String selectorJson,
java.lang.Class<T> classOfT)
Find documents using an index
|
<T> java.util.List<T> |
findByIndex(java.lang.String selectorJson,
java.lang.Class<T> classOfT,
FindByIndexOptions options)
Find documents using an index
|
AllDocsRequestBuilder |
getAllDocsRequestBuilder()
Build a request for the _all_docs endpoint.
|
java.io.InputStream |
getAttachment(java.lang.String docId,
java.lang.String attachmentName)
Reads an attachment from the database.
|
java.io.InputStream |
getAttachment(java.lang.String docId,
java.lang.String attachmentName,
java.lang.String revId)
Reads an attachment from the database.
|
java.net.URI |
getDBUri() |
DesignDocumentManager |
getDesignDocumentManager()
Get a manager that has convenience methods for managing design documents.
|
java.util.Map<java.lang.String,java.util.EnumSet<Permissions>> |
getPermissions()
Returns the Permissions of this database.
|
Shard |
getShard(java.lang.String docId)
Get info about the shard a document belongs to.
|
java.util.List<Shard> |
getShards()
Get info about the shards in the database.
|
ViewRequestBuilder |
getViewRequestBuilder(java.lang.String designDoc,
java.lang.String viewName) |
DbInfo |
info()
Get information about this database.
|
java.lang.String |
invokeUpdateHandler(java.lang.String updateHandlerUri,
java.lang.String docId,
Params params)
Invokes an Update Handler.
|
java.util.List<Index> |
listIndices()
List all indices
|
Response |
post(java.lang.Object object)
Creates a document in the database using a HTTP
POST request. |
Response |
post(java.lang.Object object,
int writeQuorum)
Creates a document in the database similarly to
post(Object) but using a
specific write quorum. |
Response |
remove(java.lang.Object object)
Removes a document from the database.
|
Response |
remove(java.lang.String id,
java.lang.String rev)
Removes the document from the database with the specified
_id and _rev
values. |
Response |
removeAttachment(java.lang.Object object,
java.lang.String attachmentName)
Removes an attachment from the specified document.
|
Response |
removeAttachment(java.lang.String id,
java.lang.String rev,
java.lang.String attachmentName)
Removes the attachment from a document the specified
_id and _rev and attachmentName
values. |
Response |
save(java.lang.Object object)
Saves a document in the database.
|
Response |
save(java.lang.Object object,
int writeQuorum)
Saves a document in the database similarly to
save(Object) but using a
specific write quorum. |
Response |
saveAttachment(java.io.InputStream in,
java.lang.String name,
java.lang.String contentType)
Creates an attachment from the specified InputStream and a new document with a generated
document ID.
|
Response |
saveAttachment(java.io.InputStream in,
java.lang.String name,
java.lang.String contentType,
java.lang.String docId,
java.lang.String docRev)
Creates or updates an attachment on the given document ID and revision.
|
Search |
search(java.lang.String searchIndexId)
Provides access to Cloudant Search APIs.
|
void |
setPermissions(java.lang.String userNameorApikey,
java.util.EnumSet<Permissions> permissions)
Set permissions for a user/apiKey on this database.
|
Response |
update(java.lang.Object object)
Updates an object in the database, the object must have the correct
_id and
_rev values. |
Response |
update(java.lang.Object object,
int writeQuorum)
Updates an object in the database similarly to
update(Object) , but specifying the
write quorum. |
protected Database(Database db)
public class ExtendedDatabase extends Database {
public ExtendedDatabase(Database database) {
super(database);
}
}
db
- existing Database instancepublic void setPermissions(java.lang.String userNameorApikey, java.util.EnumSet<Permissions> permissions)
Note this method is only applicable to databases that support the Cloudant authorization API such as Cloudant DBaaS. For unsupported databases consider using the /db/_security endpoint.
Example usage to set read-only access for a new key on the "example" database:
// 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));
userNameorApikey
- the user or key to apply permissions topermissions
- permissions to grantjava.lang.UnsupportedOperationException
- if called on a database that does not provide the
Cloudant authorization APICloudantClient.generateApiKey()
,
Roles,
Modifying permissionspublic java.util.Map<java.lang.String,java.util.EnumSet<Permissions>> getPermissions()
Note this method is only applicable to databases that support the Cloudant authorization API such as Cloudant DBaaS. For unsupported databases consider using the /db/_security endpoint.
java.lang.UnsupportedOperationException
- if called on a database that does not provide the
Cloudant authorization APIpublic java.util.List<Shard> getShards()
public Shard getShard(java.lang.String docId)
docId
- document IDpublic void createIndex(java.lang.String indexName, java.lang.String designDocName, java.lang.String indexType, IndexField[] fields)
Example usage creating an index that sorts ascending on name, then by year.
db.createIndex("Person_name", "Person_name", null, new IndexField[]{
new IndexField("Person_name",SortOrder.asc),
new IndexField("Movie_year",SortOrder.asc)});
Example usage creating an index that sorts ascending by year.
db.createIndex("Movie_year", "Movie_year", null, new IndexField[]{
new IndexField("Movie_year",SortOrder.asc)});
indexName
- optional name of the index (if not provided one will be generated)designDocName
- optional name of the design doc in which the index will be createdindexType
- optional, type of index (only "json" as of now)fields
- array of fields in the indexpublic void createIndex(java.lang.String indexDefinition)
indexDefinition
- String representation of the index definition JSONcreateIndex(String, String, String, IndexField[])
,
index definitionpublic <T> java.util.List<T> findByIndex(java.lang.String selectorJson, java.lang.Class<T> classOfT)
T
- the type of the Java object to be returnedselectorJson
- String representation of a JSON object describing criteria used to
select documents. For example:
"{ \"selector\": {<your data here>} }"
.classOfT
- The class of Java objects to be returnedfindByIndex(String, Class, FindByIndexOptions)
,
selector syntaxpublic <T> java.util.List<T> findByIndex(java.lang.String selectorJson, java.lang.Class<T> classOfT, FindByIndexOptions options)
Example usage to return the name and year of movies starring Alec Guinness since 1960 with the results sorted by year descending:
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"));
T
- the type of the Java object to be returnedselectorJson
- String representation of a JSON object describing criteria used to
select documents. For example:
"{ \"selector\": {<your data here>} }"
.options
- query Index options
classOfT
- The class of Java objects to be returnedpublic java.util.List<Index> listIndices()
Example usage:
List <Index> indices = db.listIndices();
public void deleteIndex(java.lang.String indexName, java.lang.String designDocId)
indexName
- name of the indexdesignDocId
- ID of the design docpublic Search search(java.lang.String searchIndexId)
Example usage:
// 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);
searchIndexId
- the design document with the name of the index to searchpublic DesignDocumentManager getDesignDocumentManager()
DesignDocumentManager
for this databaseDesignDocumentManager
public ViewRequestBuilder getViewRequestBuilder(java.lang.String designDoc, java.lang.String viewName)
designDoc
- containing the viewviewName
- the view namepublic AllDocsRequestBuilder getAllDocsRequestBuilder()
Example usage:
getAllDocsRequestBuilder().build().getResponse();
public Changes changes()
See the Changes
API for examples.
Changes
,
Databases - get changespublic <T> T find(java.lang.Class<T> classType, java.lang.String id)
T
- object typeclassType
- the class of type Tid
- the document idNoDocumentException
- if the document is not found in the databasefind(Class, String, String)
,
Documents - readpublic <T> T find(java.lang.Class<T> classType, java.lang.String id, Params params)
GET
request.
Example usage to get inline attachments:
Foo foo = db.find(Foo.class, "exampleId", new Params().attachments());
String attachmentData = foo.getAttachments().get("attachment.txt").getData();
T
- object typeclassType
- the class of type Tid
- the document idparams
- extra parameters to appendNoDocumentException
- if the document is not found in the database.Params
,
Documents - readpublic <T> T find(java.lang.Class<T> classType, java.lang.String id, java.lang.String rev)
Example usage:
Foo foo = db.find(Foo.class, "exampleId", "1-12345exampleRev");
T
- object typeclassType
- the class of type Tid
- the document _id fieldrev
- the document _rev fieldNoDocumentException
- if the document is not found in the database.public <T> T findAny(java.lang.Class<T> classType, java.lang.String uri)
The URI must be URI-encoded.
Example usage retrieving the Foo POJO with document ID "exampleId" from the database "exampleDb" in the "example" Cloudant account.
Foo foo = db.findAny(Foo.class, "https://example.cloudant.com/exampleDb/exampleId");
T
- the type of Java object to returnclassType
- the class of type Turi
- the URI as stringpublic java.io.InputStream find(java.lang.String id)
InputStream
.
Note: The stream must be closed after use to release the connection.
id
- the document _id fieldInputStream
NoDocumentException
- If the document is not found in the database.find(String, String)
public java.io.InputStream find(java.lang.String id, java.lang.String rev)
InputStream
.
Note: The stream must be closed after use to release the connection.
Example usage:
InputStream inputStream = null;
try{
inputStream = db.find("exampleId", "1-12345exampleRev");
//do stuff with the stream
} finally {
//close the input stream
inputStream.close();
}
id
- the document _id fieldrev
- the document _rev fieldInputStream
NoDocumentException
- if the document is not found in the database at the specified
revisionpublic boolean contains(java.lang.String id)
id
- the document _id fieldtrue
if the document is found, false
otherwisepublic Response save(java.lang.Object object)
If the serialized object's JSON does not contain an _id
field, then a UUID will
be generated for the document ID.
Example of inserting a JsonObject into the database:
JsonObject json = new JsonObject();
json.addProperty("_id", "test-doc-id-2");
json.add("json-array", new JsonArray());
Response response = db.save(json);
Example of inserting a POJO into the database:
Foo foo = new Foo();
Response response = db.save(foo);
Example of inserting a Map into the database:
Map<String, Object> map = new HashMap<>();
map.put("_id", "test-doc-id-1");
map.put("title", "test-doc");
Response response = db.save(map);
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:
Foo foo = new Foo();
Response response = db.save(foo);
foo.setRevision(response.getRevision());
object
- the object to saveResponse
DocumentConflictException
- If a conflict is detected during the save.public Response save(java.lang.Object object, int writeQuorum)
save(Object)
but using a
specific write quorum.object
- the object to savewriteQuorum
- the write quorumResponse
DocumentConflictException
- If a conflict is detected during the save.save(Object)
,
Documents - quorumpublic Response post(java.lang.Object object)
POST
request.
If the serialized object's JSON does not contain an _id
field, then the server
will generate a document ID.
Example of creating a document in the database for a POJO:
Foo foo = new Foo();
Response response = db.post(foo);
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:
Foo foo = new Foo();
Response response = db.post(foo);
foo.setRevision(response.getRevision());
object
- The object to saveResponse
public Response post(java.lang.Object object, int writeQuorum)
post(Object)
but using a
specific write quorum.object
- The object to savewriteQuorum
- the write QuorumResponse
post(Object)
,
Documents - quorumpublic Response update(java.lang.Object object)
_id
and
_rev
values.
Example usage:
//get a Bar object from the database
Bar bar = db.find(Bar.class, "exampleId");
//change something about bar
bar.setSomeProperty(true);
//now update the remote Bar
Response responseUpdate = db.update(bar);
Note that the Java object is not modified by the update 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:
Foo foo = new Foo();
Response response = db.update(foo);
foo.setRevision(response.getRevision());
object
- the object to updateResponse
DocumentConflictException
- if a conflict is detected during the update.public Response update(java.lang.Object object, int writeQuorum)
update(Object)
, but specifying the
write quorum.object
- the object to updatewriteQuorum
- the write quorumResponse
DocumentConflictException
- if a conflict is detected during the update.update(Object)
,
Documents - quorumpublic Response remove(java.lang.Object object)
The object must have the correct _id
and _rev
values.
Example usage:
//get a Bar object from the database
Bar bar = db.find(Bar.class, "exampleId");
//now remove the remote Bar
Response response = db.remove(bar);
object
- the document to remove as an objectResponse
NoDocumentException
- If the document is not found in the database.public Response remove(java.lang.String id, java.lang.String rev)
_id
and _rev
values.
Example usage:
Response response = db.remove("exampleId", "1-12345exampleRev");
id
- the document _id fieldrev
- the document _rev fieldResponse
NoDocumentException
- If the document is not found in the database.public java.util.List<Response> bulk(java.util.List<?> objects)
_bulk_docs
endpoint to insert multiple documents into the database in a
single HTTP request.
Example usage:
//create a list
List<Object> newDocs = new ArrayList<Object>();
//add some objects to the list
newDocs.add(new Foo());
newDocs.add(new JsonObject());
//use the bulk insert
List<Response> responses = db.bulk(newDocs);
objects
- the List
of objectsList<Response>
one per objectpublic java.io.InputStream getAttachment(java.lang.String docId, java.lang.String attachmentName)
docId
- the document idattachmentName
- the attachment nameInputStream
.public java.io.InputStream getAttachment(java.lang.String docId, java.lang.String attachmentName, java.lang.String revId)
docId
- the document idattachmentName
- the attachment namerevId
- the document revision id or null
InputStream
.public Response saveAttachment(java.io.InputStream in, java.lang.String name, java.lang.String contentType)
Example usage:
byte[] bytesToDB = "binary data".getBytes();
ByteArrayInputStream bytesIn = new ByteArrayInputStream(bytesToDB);
Response response = db.saveAttachment(bytesIn, "foo.txt", "text/plain");
To retrieve an attachment, see find(Class, String, Params)
in
- The InputStream
providing the binary data.name
- The attachment name.contentType
- The attachment "Content-Type".Response
public Response saveAttachment(java.io.InputStream in, java.lang.String name, java.lang.String contentType, java.lang.String docId, java.lang.String docRev)
If docId
and docRev
are null
a new document will be created.
Example usage:
byte[] bytesToDB = "binary data".getBytes();
ByteArrayInputStream bytesIn = new ByteArrayInputStream(bytesToDB);
Response response = db.saveAttachment(bytesIn, "foo.txt", "text/plain","exampleId","3-rev");
Saves an attachment to an existing document given both a document id
and revision, or save to a new document given only the id, and rev as null
.
To retrieve an attachment, see find(Class, String, Params)
in
- The InputStream
providing the binary data.name
- The attachment name.contentType
- The attachment "Content-Type".docId
- The document ID to save the attachment under, or null
to save
under a new document with a generated ID.docRev
- The document revision to save the attachment under, or null
when saving to a new document.Response
DocumentConflictException
- if the attachment cannot be saved because of a conflictpublic Response removeAttachment(java.lang.Object object, java.lang.String attachmentName)
The object must have the correct _id
and _rev
values.
Example usage:
//get a Bar object from the database
Bar bar = db.find(Bar.class, "exampleId");
String attachmentName = "example.jpg";
//now remove the remote Bar attachment
Response response = db.removeAttachment(bar, attachmentName);
object
- the document to remove as an objectattachmentName
- the attachment name to removeResponse
NoDocumentException
- If the document is not found in the database.DocumentConflictException
- If a conflict is detected during the removal.public Response removeAttachment(java.lang.String id, java.lang.String rev, java.lang.String attachmentName)
_id
and _rev
and attachmentName
values.
Example usage:
Response response = db.removeAttachment("exampleId", "1-12345exampleRev", "example.jpg");
id
- the document _id fieldrev
- the document _rev fieldattachmentName
- the attachment nameResponse
NoDocumentException
- If the document is not found in the database.DocumentConflictException
- if the attachment cannot be removed because of a conflictpublic java.lang.String invokeUpdateHandler(java.lang.String updateHandlerUri, java.lang.String docId, Params params)
Example usage:
final String newValue = "foo bar";
Params params = new Params()
.addParam("field", "title")
.addParam("value", newValue);
String output = db.invokeUpdateHandler("example/example_update", "exampleId", params);
Params params = new Params() .addParam("field", "foo") .addParam("value", "bar"); String output = dbClient.invokeUpdateHandler("designDoc/update1", "docId", params);
updateHandlerUri
- The Update Handler URI, in the format: designDoc/update1
docId
- The document id to update.
If no id is provided, then a document will be created.params
- The query parameters as Params
.public java.net.URI getDBUri()
public DbInfo info()
public void ensureFullCommit()