use of com.ibm.cloud.cloudant.v1.model.Document in project cloudant-java-sdk by IBM.
the class CreateDbAndDoc method main.
public static void main(String[] args) {
// 1. Create a client with `CLOUDANT` default service name ============
Cloudant client = Cloudant.newInstance();
// 2. Create a database ===============================================
// Create a database object with "orders" id
String exampleDbName = "orders";
PutDatabaseOptions putDbOptions = new PutDatabaseOptions.Builder().db(exampleDbName).build();
// Try to create database if it doesn't exist
try {
Ok putDatabaseResult = client.putDatabase(putDbOptions).execute().getResult();
if (putDatabaseResult.isOk()) {
System.out.println("\"" + exampleDbName + "\" database created.");
}
} catch (ServiceResponseException sre) {
if (sre.getStatusCode() == 412)
System.out.println("Cannot create \"" + exampleDbName + "\" database, it already exists.");
}
// 3. Create a document ===============================================
// Create a document object with "example" id
String exampleDocId = "example";
Document exampleDocument = new Document();
// Setting id for the document is optional when "postDocument" method is used for CREATE.
// When id is not provided the server will generate one for your document.
exampleDocument.setId(exampleDocId);
// Add "name" and "joined" fields to the document
exampleDocument.put("name", "Bob Smith");
exampleDocument.put("joined", "2019-01-24T10:42:59.000Z");
// Save the document in the database with "postDocument" method
PostDocumentOptions createDocumentOptions = new PostDocumentOptions.Builder().db(exampleDbName).document(exampleDocument).build();
DocumentResult createDocumentResponse = client.postDocument(createDocumentOptions).execute().getResult();
// ====================================================================
// Note: saving the document can also be done with the "putDocument"
// method. In this case `docId` is required for a CREATE operation:
/*
PutDocumentOptions createDocumentOptions =
new PutDocumentOptions.Builder()
.db(exampleDbName)
.docId(exampleDocId)
.document(exampleDocument)
.build();
DocumentResult createDocumentResponse = client
.putDocument(createDocumentOptions)
.execute()
.getResult();
*/
// ====================================================================
// Keeping track of the revision number of the document object
// is necessary for further UPDATE/DELETE operations:
exampleDocument.setRev(createDocumentResponse.getRev());
System.out.println("You have created the document:\n" + exampleDocument);
}
use of com.ibm.cloud.cloudant.v1.model.Document in project cloudant-java-sdk by IBM.
the class DeleteDoc method main.
public static void main(String[] args) {
// 1. Create a client with `CLOUDANT` default service name ============
Cloudant client = Cloudant.newInstance();
// 2. Delete the document =============================================
// Set the options to get the document out of the database if it exists
String exampleDbName = "orders";
String exampleDocId = "example";
GetDocumentOptions documentInfoOptions = new GetDocumentOptions.Builder().db(exampleDbName).docId(exampleDocId).build();
try {
// Try to get the document if it previously existed in the database
Document document = client.getDocument(documentInfoOptions).execute().getResult();
// Delete the document from the database
DeleteDocumentOptions deleteDocumentOptions = new DeleteDocumentOptions.Builder().db(exampleDbName).docId(// docId is required for DELETE
exampleDocId).rev(// rev is required for DELETE
document.getRev()).build();
DocumentResult deleteDocumentResponse = client.deleteDocument(deleteDocumentOptions).execute().getResult();
if (deleteDocumentResponse.isOk()) {
System.out.println("You have deleted the document.");
}
} catch (NotFoundException nfe) {
System.out.println("Cannot delete document because " + "either \"orders\" database or the \"example\" " + "document was not found.");
}
}
use of com.ibm.cloud.cloudant.v1.model.Document in project cloudant-java-sdk by IBM.
the class CloudantTest method testPostDocumentWOptions.
@Test
public void testPostDocumentWOptions() throws Throwable {
// Schedule some responses.
String mockResponseBody = "{\"id\": \"id\", \"rev\": \"rev\", \"ok\": true, \"caused_by\": \"causedBy\", \"error\": \"error\", \"reason\": \"reason\"}";
String postDocumentPath = "/testString";
server.enqueue(new MockResponse().setHeader("Content-type", "application/json").setResponseCode(201).setBody(mockResponseBody));
constructClientService();
// Construct an instance of the Attachment model
Attachment attachmentModel = new Attachment.Builder().contentType("testString").data(TestUtilities.createMockByteArray("This is a mock byte array value.")).digest("testString").encodedLength(Long.valueOf("0")).encoding("testString").follows(true).length(Long.valueOf("0")).revpos(Long.valueOf("1")).stub(true).build();
// Construct an instance of the Revisions model
Revisions revisionsModel = new Revisions.Builder().ids(new java.util.ArrayList<String>(java.util.Arrays.asList("testString"))).start(Long.valueOf("1")).build();
// Construct an instance of the DocumentRevisionStatus model
DocumentRevisionStatus documentRevisionStatusModel = new DocumentRevisionStatus.Builder().rev("testString").status("available").build();
// Construct an instance of the Document model
Document documentModel = new Document.Builder().attachments(new java.util.HashMap<String, Attachment>() {
{
put("foo", attachmentModel);
}
}).conflicts(new java.util.ArrayList<String>(java.util.Arrays.asList("testString"))).deleted(true).deletedConflicts(new java.util.ArrayList<String>(java.util.Arrays.asList("testString"))).id("testString").localSeq("testString").rev("testString").revisions(revisionsModel).revsInfo(new java.util.ArrayList<DocumentRevisionStatus>(java.util.Arrays.asList(documentRevisionStatusModel))).add("foo", "testString").build();
// Construct an instance of the PostDocumentOptions model
PostDocumentOptions postDocumentOptionsModel = new PostDocumentOptions.Builder().db("testString").document(documentModel).contentType("application/json").batch("ok").build();
// Invoke operation with valid options model (positive test)
Response<DocumentResult> response = cloudantService.postDocument(postDocumentOptionsModel).execute();
assertNotNull(response);
DocumentResult responseObj = response.getResult();
assertNotNull(responseObj);
// Verify the contents of the request
RecordedRequest request = server.takeRequest();
assertNotNull(request);
assertEquals(request.getMethod(), "POST");
// Check query
Map<String, String> query = TestUtilities.parseQueryString(request);
assertNotNull(query);
// Get query params
assertEquals(query.get("batch"), "ok");
// Check request path
String parsedPath = TestUtilities.parseReqPath(request);
assertEquals(parsedPath, postDocumentPath);
}
use of com.ibm.cloud.cloudant.v1.model.Document in project cloudant-java-sdk by IBM.
the class CloudantTest method testPutLocalDocumentWOptions.
@Test
public void testPutLocalDocumentWOptions() throws Throwable {
// Schedule some responses.
String mockResponseBody = "{\"id\": \"id\", \"rev\": \"rev\", \"ok\": true, \"caused_by\": \"causedBy\", \"error\": \"error\", \"reason\": \"reason\"}";
String putLocalDocumentPath = "/testString/_local/testString";
server.enqueue(new MockResponse().setHeader("Content-type", "application/json").setResponseCode(201).setBody(mockResponseBody));
constructClientService();
// Construct an instance of the Attachment model
Attachment attachmentModel = new Attachment.Builder().contentType("testString").data(TestUtilities.createMockByteArray("This is a mock byte array value.")).digest("testString").encodedLength(Long.valueOf("0")).encoding("testString").follows(true).length(Long.valueOf("0")).revpos(Long.valueOf("1")).stub(true).build();
// Construct an instance of the Revisions model
Revisions revisionsModel = new Revisions.Builder().ids(new java.util.ArrayList<String>(java.util.Arrays.asList("testString"))).start(Long.valueOf("1")).build();
// Construct an instance of the DocumentRevisionStatus model
DocumentRevisionStatus documentRevisionStatusModel = new DocumentRevisionStatus.Builder().rev("testString").status("available").build();
// Construct an instance of the Document model
Document documentModel = new Document.Builder().attachments(new java.util.HashMap<String, Attachment>() {
{
put("foo", attachmentModel);
}
}).conflicts(new java.util.ArrayList<String>(java.util.Arrays.asList("testString"))).deleted(true).deletedConflicts(new java.util.ArrayList<String>(java.util.Arrays.asList("testString"))).id("exampleid").localSeq("testString").rev("testString").revisions(revisionsModel).revsInfo(new java.util.ArrayList<DocumentRevisionStatus>(java.util.Arrays.asList(documentRevisionStatusModel))).add("brand", "Foo").add("colours", "[\"red\",\"green\",\"black\",\"blue\"]").add("description", "Slim Colourful Design Electronic Cooking Appliance for ...").add("image", "assets/img/0gmsnghhew.jpg").add("keywords", "[\"Foo\",\"Scales\",\"Weight\",\"Digital\",\"Kitchen\"]").add("name", "Digital Kitchen Scales").add("price", "14.99").add("productid", "1000042").add("taxonomy", "[\"Home\",\"Kitchen\",\"Small Appliances\"]").add("type", "product").build();
// Construct an instance of the PutLocalDocumentOptions model
PutLocalDocumentOptions putLocalDocumentOptionsModel = new PutLocalDocumentOptions.Builder().db("testString").docId("testString").document(documentModel).contentType("application/json").batch("ok").build();
// Invoke operation with valid options model (positive test)
Response<DocumentResult> response = cloudantService.putLocalDocument(putLocalDocumentOptionsModel).execute();
assertNotNull(response);
DocumentResult responseObj = response.getResult();
assertNotNull(responseObj);
// Verify the contents of the request
RecordedRequest request = server.takeRequest();
assertNotNull(request);
assertEquals(request.getMethod(), "PUT");
// Check query
Map<String, String> query = TestUtilities.parseQueryString(request);
assertNotNull(query);
// Get query params
assertEquals(query.get("batch"), "ok");
// Check request path
String parsedPath = TestUtilities.parseReqPath(request);
assertEquals(parsedPath, putLocalDocumentPath);
}
use of com.ibm.cloud.cloudant.v1.model.Document in project cloudant-java-sdk by IBM.
the class CloudantTest method testGetLocalDocumentWOptions.
@Test
public void testGetLocalDocumentWOptions() throws Throwable {
// Schedule some responses.
String mockResponseBody = "{\"_attachments\": {\"mapKey\": {\"content_type\": \"contentType\", \"data\": \"VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku\", \"digest\": \"digest\", \"encoded_length\": 0, \"encoding\": \"encoding\", \"follows\": false, \"length\": 0, \"revpos\": 1, \"stub\": true}}, \"_conflicts\": [\"conflicts\"], \"_deleted\": false, \"_deleted_conflicts\": [\"deletedConflicts\"], \"_id\": \"id\", \"_local_seq\": \"localSeq\", \"_rev\": \"rev\", \"_revisions\": {\"ids\": [\"ids\"], \"start\": 1}, \"_revs_info\": [{\"rev\": \"rev\", \"status\": \"available\"}]}";
String getLocalDocumentPath = "/testString/_local/testString";
server.enqueue(new MockResponse().setHeader("Content-type", "application/json").setResponseCode(200).setBody(mockResponseBody));
constructClientService();
// Construct an instance of the GetLocalDocumentOptions model
GetLocalDocumentOptions getLocalDocumentOptionsModel = new GetLocalDocumentOptions.Builder().db("testString").docId("testString").accept("application/json").ifNoneMatch("testString").attachments(false).attEncodingInfo(false).localSeq(false).build();
// Invoke operation with valid options model (positive test)
Response<Document> response = cloudantService.getLocalDocument(getLocalDocumentOptionsModel).execute();
assertNotNull(response);
Document responseObj = response.getResult();
assertNotNull(responseObj);
// Verify the contents of the request
RecordedRequest request = server.takeRequest();
assertNotNull(request);
assertEquals(request.getMethod(), "GET");
// Check query
Map<String, String> query = TestUtilities.parseQueryString(request);
assertNotNull(query);
// Get query params
assertEquals(Boolean.valueOf(query.get("attachments")), Boolean.valueOf(false));
assertEquals(Boolean.valueOf(query.get("att_encoding_info")), Boolean.valueOf(false));
assertEquals(Boolean.valueOf(query.get("local_seq")), Boolean.valueOf(false));
// Check request path
String parsedPath = TestUtilities.parseReqPath(request);
assertEquals(parsedPath, getLocalDocumentPath);
}
Aggregations