Search in sources :

Example 1 with PostDocumentOptions

use of com.ibm.cloud.cloudant.v1.model.PostDocumentOptions in project cloudant-java-sdk by IBM.

the class Cloudant method postDocument.

/**
 * Create or modify a document in a database.
 *
 * Creates or modifies a document in the specified database by using the supplied JSON document. If the JSON document
 * doesn't specify an `_id` field, then the document is created with a new unique ID generated by the UUID algorithm
 * that is configured for the server. If the document includes the `_id` field, then it is created with that `_id` or
 * updated if the `_id` already exists, and an appropriate `_rev` is included in the JSON document. If the `_id`
 * includes the `_local` or `_design` prefix, then this operation is used to create or modify local or design
 * documents respectively.
 *
 * @param postDocumentOptions the {@link PostDocumentOptions} containing the options for the call
 * @return a {@link ServiceCall} with a result of type {@link DocumentResult}
 */
public ServiceCall<DocumentResult> postDocument(PostDocumentOptions postDocumentOptions) {
    com.ibm.cloud.sdk.core.util.Validator.notNull(postDocumentOptions, "postDocumentOptions cannot be null");
    if (postDocumentOptions.document() != null && postDocumentOptions.contentType() == null) {
        postDocumentOptions = postDocumentOptions.newBuilder().contentType("application/json").build();
    }
    Map<String, String> pathParamsMap = new HashMap<String, String>();
    pathParamsMap.put("db", postDocumentOptions.db());
    RequestBuilder builder = RequestBuilder.post(RequestBuilder.resolveRequestUrl(getServiceUrl(), "/{db}", pathParamsMap));
    Map<String, String> sdkHeaders = SdkCommon.getSdkHeaders("cloudant", "v1", "postDocument");
    for (Entry<String, String> header : sdkHeaders.entrySet()) {
        builder.header(header.getKey(), header.getValue());
    }
    builder.header("Accept", "application/json");
    if (postDocumentOptions.contentType() != null) {
        builder.header("Content-Type", postDocumentOptions.contentType());
    }
    if (postDocumentOptions.batch() != null) {
        builder.query("batch", String.valueOf(postDocumentOptions.batch()));
    }
    builder.bodyContent(postDocumentOptions.contentType(), postDocumentOptions.document(), null, postDocumentOptions.body());
    ResponseConverter<DocumentResult> responseConverter = ResponseConverterUtils.getValue(new com.google.gson.reflect.TypeToken<DocumentResult>() {
    }.getType());
    return createServiceCall(builder.build(), responseConverter);
}
Also used : RequestBuilder(com.ibm.cloud.sdk.core.http.RequestBuilder) HashMap(java.util.HashMap) DocumentResult(com.ibm.cloud.cloudant.v1.model.DocumentResult)

Example 2 with PostDocumentOptions

use of com.ibm.cloud.cloudant.v1.model.PostDocumentOptions in project cloudant-java-sdk by IBM.

the class UpdateDoc method main.

public static void main(String[] args) {
    // 1. Create a client with `CLOUDANT` default service name ============
    Cloudant client = Cloudant.newInstance();
    // 2. Update the document =============================================
    // Set the options to get the document out of the database if it exists
    String exampleDbName = "orders";
    GetDocumentOptions documentInfoOptions = new GetDocumentOptions.Builder().db(exampleDbName).docId("example").build();
    try {
        // Try to get the document if it previously existed in the database
        Document document = client.getDocument(documentInfoOptions).execute().getResult();
        // Note: for response byte stream use:
        /*
            InputStream documentAsByteStream =
                client.getDocumentAsStream(documentInfoOptions)
                    .execute()
                    .getResult();
            */
        // Add Bob Smith's address to the document
        document.put("address", "19 Front Street, Darlington, DL5 1TY");
        // Remove the joined property from document object
        document.removeProperty("joined");
        // Update the document in the database
        PostDocumentOptions updateDocumentOptions = new PostDocumentOptions.Builder().db(exampleDbName).document(document).build();
        // ================================================================
        // Note: for request byte stream use:
        /*
            PostDocumentOptions updateDocumentOptions =
                new PostDocumentOptions.Builder()
                    .db(exampleDbName)
                    .contentType("application/json")
                    .body(documentAsByteStream)
                    .build();
            */
        // ================================================================
        DocumentResult updateDocumentResponse = client.postDocument(updateDocumentOptions).execute().getResult();
        // ====================================================================
        // Note: updating the document can also be done with the "putDocument"
        // method. docId and rev are required for an UPDATE operation,
        // but rev can be provided in the document object too:
        /*
            PutDocumentOptions updateDocumentOptions =
                new PutDocumentOptions.Builder()
                    .db(exampleDbName)
                    .docId(document.getId()) // docId is a required parameter
                    .rev(document.getRev())
                    .document(document) // rev in the document object CAN replace above `rev` parameter
                    .build();
            DocumentResult updateDocumentResponse = client
                .putDocument(updateDocumentOptions)
                .execute()
                .getResult();
            */
        // ====================================================================
        // Keeping track of the latest revision number of the document object
        // is necessary for further UPDATE/DELETE operations:
        document.setRev(updateDocumentResponse.getRev());
        System.out.println("You have updated the document:\n" + document);
    } catch (NotFoundException nfe) {
        System.out.println("Cannot update document because " + "either \"orders\" database or the \"example\" " + "document was not found.");
    }
}
Also used : DocumentResult(com.ibm.cloud.cloudant.v1.model.DocumentResult) GetDocumentOptions(com.ibm.cloud.cloudant.v1.model.GetDocumentOptions) NotFoundException(com.ibm.cloud.sdk.core.service.exception.NotFoundException) Cloudant(com.ibm.cloud.cloudant.v1.Cloudant) Document(com.ibm.cloud.cloudant.v1.model.Document) PostDocumentOptions(com.ibm.cloud.cloudant.v1.model.PostDocumentOptions)

Example 3 with PostDocumentOptions

use of com.ibm.cloud.cloudant.v1.model.PostDocumentOptions in project knative-eventing-java-app by IBM.

the class CloudEventStoreCloudant method addEvent.

@Override
public void addEvent(CloudEvent<?, ?> event) throws Exception {
    // Convert event into document object
    Document document = new Document();
    // https://github.com/cloudant/java-cloudant/blob/master/MIGRATION.md
    document.setProperties(this.gson.fromJson(this.gson.toJson(event), Map.class));
    // Post document and get response
    PostDocumentOptions postDocumentOptions = new PostDocumentOptions.Builder().db(this.dbName).document(document).build();
    DocumentResult response = this.client.postDocument(postDocumentOptions).execute().getResult();
    // Check for errors
    String error = response.getError();
    if (error != null) {
        logger.error("Error adding event to Cloudant: " + error);
        throw new Exception(error);
    }
}
Also used : DocumentResult(com.ibm.cloud.cloudant.v1.model.DocumentResult) Document(com.ibm.cloud.cloudant.v1.model.Document) Map(java.util.Map) PostDocumentOptions(com.ibm.cloud.cloudant.v1.model.PostDocumentOptions) NotFoundException(com.ibm.cloud.sdk.core.service.exception.NotFoundException)

Example 4 with PostDocumentOptions

use of com.ibm.cloud.cloudant.v1.model.PostDocumentOptions in project cloudant-java-sdk by IBM.

the class PostDocumentOptionsTest method testPostDocumentOptions.

@Test
public void testPostDocumentOptions() throws Throwable {
    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();
    assertEquals(attachmentModel.contentType(), "testString");
    assertEquals(attachmentModel.data(), TestUtilities.createMockByteArray("This is a mock byte array value."));
    assertEquals(attachmentModel.digest(), "testString");
    assertEquals(attachmentModel.encodedLength(), Long.valueOf("0"));
    assertEquals(attachmentModel.encoding(), "testString");
    assertEquals(attachmentModel.follows(), Boolean.valueOf(true));
    assertEquals(attachmentModel.length(), Long.valueOf("0"));
    assertEquals(attachmentModel.revpos(), Long.valueOf("1"));
    assertEquals(attachmentModel.stub(), Boolean.valueOf(true));
    Revisions revisionsModel = new Revisions.Builder().ids(new java.util.ArrayList<String>(java.util.Arrays.asList("testString"))).start(Long.valueOf("1")).build();
    assertEquals(revisionsModel.ids(), new java.util.ArrayList<String>(java.util.Arrays.asList("testString")));
    assertEquals(revisionsModel.start(), Long.valueOf("1"));
    DocumentRevisionStatus documentRevisionStatusModel = new DocumentRevisionStatus.Builder().rev("testString").status("available").build();
    assertEquals(documentRevisionStatusModel.rev(), "testString");
    assertEquals(documentRevisionStatusModel.status(), "available");
    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();
    assertEquals(documentModel.getAttachments(), new java.util.HashMap<String, Attachment>() {

        {
            put("foo", attachmentModel);
        }
    });
    assertEquals(documentModel.getConflicts(), new java.util.ArrayList<String>(java.util.Arrays.asList("testString")));
    assertEquals(documentModel.isDeleted(), Boolean.valueOf(true));
    assertEquals(documentModel.getDeletedConflicts(), new java.util.ArrayList<String>(java.util.Arrays.asList("testString")));
    assertEquals(documentModel.getId(), "testString");
    assertEquals(documentModel.getLocalSeq(), "testString");
    assertEquals(documentModel.getRev(), "testString");
    assertEquals(documentModel.getRevisions(), revisionsModel);
    assertEquals(documentModel.getRevsInfo(), new java.util.ArrayList<DocumentRevisionStatus>(java.util.Arrays.asList(documentRevisionStatusModel)));
    assertEquals(documentModel.get("foo"), "testString");
    PostDocumentOptions postDocumentOptionsModel = new PostDocumentOptions.Builder().db("testString").document(documentModel).body(TestUtilities.createMockStream("This is a mock file.")).contentType("application/json").batch("ok").build();
    assertEquals(postDocumentOptionsModel.db(), "testString");
    assertEquals(postDocumentOptionsModel.document(), documentModel);
    assertEquals(IOUtils.toString(postDocumentOptionsModel.body()), IOUtils.toString(TestUtilities.createMockStream("This is a mock file.")));
    assertEquals(postDocumentOptionsModel.contentType(), "application/json");
    assertEquals(postDocumentOptionsModel.batch(), "ok");
}
Also used : ArrayList(java.util.ArrayList) Attachment(com.ibm.cloud.cloudant.v1.model.Attachment) Revisions(com.ibm.cloud.cloudant.v1.model.Revisions) Document(com.ibm.cloud.cloudant.v1.model.Document) DocumentRevisionStatus(com.ibm.cloud.cloudant.v1.model.DocumentRevisionStatus) PostDocumentOptions(com.ibm.cloud.cloudant.v1.model.PostDocumentOptions) Test(org.testng.annotations.Test)

Example 5 with PostDocumentOptions

use of com.ibm.cloud.cloudant.v1.model.PostDocumentOptions 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);
}
Also used : PutDatabaseOptions(com.ibm.cloud.cloudant.v1.model.PutDatabaseOptions) DocumentResult(com.ibm.cloud.cloudant.v1.model.DocumentResult) ServiceResponseException(com.ibm.cloud.sdk.core.service.exception.ServiceResponseException) Cloudant(com.ibm.cloud.cloudant.v1.Cloudant) Ok(com.ibm.cloud.cloudant.v1.model.Ok) Document(com.ibm.cloud.cloudant.v1.model.Document) PostDocumentOptions(com.ibm.cloud.cloudant.v1.model.PostDocumentOptions)

Aggregations

Document (com.ibm.cloud.cloudant.v1.model.Document)5 DocumentResult (com.ibm.cloud.cloudant.v1.model.DocumentResult)5 PostDocumentOptions (com.ibm.cloud.cloudant.v1.model.PostDocumentOptions)5 Cloudant (com.ibm.cloud.cloudant.v1.Cloudant)2 Attachment (com.ibm.cloud.cloudant.v1.model.Attachment)2 DocumentRevisionStatus (com.ibm.cloud.cloudant.v1.model.DocumentRevisionStatus)2 Revisions (com.ibm.cloud.cloudant.v1.model.Revisions)2 NotFoundException (com.ibm.cloud.sdk.core.service.exception.NotFoundException)2 ArrayList (java.util.ArrayList)2 Test (org.testng.annotations.Test)2 BulkGetQueryDocument (com.ibm.cloud.cloudant.v1.model.BulkGetQueryDocument)1 BulkGetResultDocument (com.ibm.cloud.cloudant.v1.model.BulkGetResultDocument)1 DesignDocument (com.ibm.cloud.cloudant.v1.model.DesignDocument)1 GetDocumentOptions (com.ibm.cloud.cloudant.v1.model.GetDocumentOptions)1 Ok (com.ibm.cloud.cloudant.v1.model.Ok)1 PutDatabaseOptions (com.ibm.cloud.cloudant.v1.model.PutDatabaseOptions)1 ReplicationDocument (com.ibm.cloud.cloudant.v1.model.ReplicationDocument)1 SchedulerDocument (com.ibm.cloud.cloudant.v1.model.SchedulerDocument)1 RequestBuilder (com.ibm.cloud.sdk.core.http.RequestBuilder)1 ServiceResponseException (com.ibm.cloud.sdk.core.service.exception.ServiceResponseException)1