Search in sources :

Example 11 with Document

use of com.ibm.cloud.cloudant.v1.model.Document 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 12 with Document

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

the class CloudantTest method testPostBulkDocsWOptions.

@Test
public void testPostBulkDocsWOptions() throws Throwable {
    // Schedule some responses.
    String mockResponseBody = "[{\"id\": \"id\", \"rev\": \"rev\", \"ok\": true, \"caused_by\": \"causedBy\", \"error\": \"error\", \"reason\": \"reason\"}]";
    String postBulkDocsPath = "/testString/_bulk_docs";
    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 BulkDocs model
    BulkDocs bulkDocsModel = new BulkDocs.Builder().docs(new java.util.ArrayList<Document>(java.util.Arrays.asList(documentModel))).newEdits(true).build();
    // Construct an instance of the PostBulkDocsOptions model
    PostBulkDocsOptions postBulkDocsOptionsModel = new PostBulkDocsOptions.Builder().db("testString").bulkDocs(bulkDocsModel).build();
    // Invoke operation with valid options model (positive test)
    Response<List<DocumentResult>> response = cloudantService.postBulkDocs(postBulkDocsOptionsModel).execute();
    assertNotNull(response);
    List<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);
    assertNull(query);
    // Check request path
    String parsedPath = TestUtilities.parseReqPath(request);
    assertEquals(parsedPath, postBulkDocsPath);
}
Also used : PostBulkDocsOptions(com.ibm.cloud.cloudant.v1.model.PostBulkDocsOptions) DocumentResult(com.ibm.cloud.cloudant.v1.model.DocumentResult) ArrayList(java.util.ArrayList) Attachment(com.ibm.cloud.cloudant.v1.model.Attachment) Revisions(com.ibm.cloud.cloudant.v1.model.Revisions) ReplicationDocument(com.ibm.cloud.cloudant.v1.model.ReplicationDocument) DesignDocument(com.ibm.cloud.cloudant.v1.model.DesignDocument) Document(com.ibm.cloud.cloudant.v1.model.Document) SchedulerDocument(com.ibm.cloud.cloudant.v1.model.SchedulerDocument) BulkGetResultDocument(com.ibm.cloud.cloudant.v1.model.BulkGetResultDocument) BulkGetQueryDocument(com.ibm.cloud.cloudant.v1.model.BulkGetQueryDocument) DocumentRevisionStatus(com.ibm.cloud.cloudant.v1.model.DocumentRevisionStatus) ArrayList(java.util.ArrayList) List(java.util.List) BulkDocs(com.ibm.cloud.cloudant.v1.model.BulkDocs) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MockResponse(okhttp3.mockwebserver.MockResponse) Test(org.testng.annotations.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 13 with Document

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

the class Cloudant method getDocumentShardsInfo.

/**
 * Retrieve shard information for a specific document.
 *
 * Retrieves information about a specific shard where a particular document is stored, along with information about
 * the nodes where that shard has a replica.
 *
 * @param getDocumentShardsInfoOptions the {@link GetDocumentShardsInfoOptions} containing the options for the call
 * @return a {@link ServiceCall} with a result of type {@link DocumentShardInfo}
 */
public ServiceCall<DocumentShardInfo> getDocumentShardsInfo(GetDocumentShardsInfoOptions getDocumentShardsInfoOptions) {
    com.ibm.cloud.sdk.core.util.Validator.notNull(getDocumentShardsInfoOptions, "getDocumentShardsInfoOptions cannot be null");
    Map<String, String> pathParamsMap = new HashMap<String, String>();
    pathParamsMap.put("db", getDocumentShardsInfoOptions.db());
    pathParamsMap.put("doc_id", getDocumentShardsInfoOptions.docId());
    RequestBuilder builder = RequestBuilder.get(RequestBuilder.resolveRequestUrl(getServiceUrl(), "/{db}/_shards/{doc_id}", pathParamsMap));
    Map<String, String> sdkHeaders = SdkCommon.getSdkHeaders("cloudant", "v1", "getDocumentShardsInfo");
    for (Entry<String, String> header : sdkHeaders.entrySet()) {
        builder.header(header.getKey(), header.getValue());
    }
    builder.header("Accept", "application/json");
    ResponseConverter<DocumentShardInfo> responseConverter = ResponseConverterUtils.getValue(new com.google.gson.reflect.TypeToken<DocumentShardInfo>() {
    }.getType());
    return createServiceCall(builder.build(), responseConverter);
}
Also used : RequestBuilder(com.ibm.cloud.sdk.core.http.RequestBuilder) HashMap(java.util.HashMap) DocumentShardInfo(com.ibm.cloud.cloudant.v1.model.DocumentShardInfo)

Example 14 with Document

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

the class Cloudant method getGeo.

/**
 * Query a geospatial index.
 *
 * Executes a query against the requested geospatial index from the specified design document.
 *
 * @param getGeoOptions the {@link GetGeoOptions} containing the options for the call
 * @return a {@link ServiceCall} with a result of type {@link GeoResult}
 */
public ServiceCall<GeoResult> getGeo(GetGeoOptions getGeoOptions) {
    com.ibm.cloud.sdk.core.util.Validator.notNull(getGeoOptions, "getGeoOptions cannot be null");
    Map<String, String> pathParamsMap = new HashMap<String, String>();
    pathParamsMap.put("db", getGeoOptions.db());
    pathParamsMap.put("ddoc", getGeoOptions.ddoc());
    pathParamsMap.put("index", getGeoOptions.index());
    RequestBuilder builder = RequestBuilder.get(RequestBuilder.resolveRequestUrl(getServiceUrl(), "/{db}/_design/{ddoc}/_geo/{index}", pathParamsMap));
    Map<String, String> sdkHeaders = SdkCommon.getSdkHeaders("cloudant", "v1", "getGeo");
    for (Entry<String, String> header : sdkHeaders.entrySet()) {
        builder.header(header.getKey(), header.getValue());
    }
    builder.header("Accept", "application/json");
    if (getGeoOptions.bbox() != null) {
        builder.query("bbox", String.valueOf(getGeoOptions.bbox()));
    }
    if (getGeoOptions.bookmark() != null) {
        builder.query("bookmark", String.valueOf(getGeoOptions.bookmark()));
    }
    if (getGeoOptions.format() != null) {
        builder.query("format", String.valueOf(getGeoOptions.format()));
    }
    if (getGeoOptions.g() != null) {
        builder.query("g", String.valueOf(getGeoOptions.g()));
    }
    if (getGeoOptions.includeDocs() != null) {
        builder.query("include_docs", String.valueOf(getGeoOptions.includeDocs()));
    }
    if (getGeoOptions.lat() != null) {
        builder.query("lat", String.valueOf(getGeoOptions.lat()));
    }
    if (getGeoOptions.limit() != null) {
        builder.query("limit", String.valueOf(getGeoOptions.limit()));
    }
    if (getGeoOptions.lon() != null) {
        builder.query("lon", String.valueOf(getGeoOptions.lon()));
    }
    if (getGeoOptions.nearest() != null) {
        builder.query("nearest", String.valueOf(getGeoOptions.nearest()));
    }
    if (getGeoOptions.radius() != null) {
        builder.query("radius", String.valueOf(getGeoOptions.radius()));
    }
    if (getGeoOptions.rangex() != null) {
        builder.query("rangex", String.valueOf(getGeoOptions.rangex()));
    }
    if (getGeoOptions.rangey() != null) {
        builder.query("rangey", String.valueOf(getGeoOptions.rangey()));
    }
    if (getGeoOptions.relation() != null) {
        builder.query("relation", String.valueOf(getGeoOptions.relation()));
    }
    if (getGeoOptions.skip() != null) {
        builder.query("skip", String.valueOf(getGeoOptions.skip()));
    }
    if (getGeoOptions.stale() != null) {
        builder.query("stale", String.valueOf(getGeoOptions.stale()));
    }
    ResponseConverter<GeoResult> responseConverter = ResponseConverterUtils.getValue(new com.google.gson.reflect.TypeToken<GeoResult>() {
    }.getType());
    return createServiceCall(builder.build(), responseConverter);
}
Also used : RequestBuilder(com.ibm.cloud.sdk.core.http.RequestBuilder) HashMap(java.util.HashMap) GeoResult(com.ibm.cloud.cloudant.v1.model.GeoResult)

Example 15 with Document

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

the class Cloudant method postView.

/**
 * Query a MapReduce view.
 *
 * This operation queries the specified MapReduce view of the specified design document. By default, the map and
 * reduce functions of the view are run to update the view before returning the response. The advantage of using the
 * HTTP `POST` method is that the query is submitted as a JSON object in the request body. This avoids the limitations
 * of passing query options as URL query parameters of a `GET` request.
 *
 * @param postViewOptions the {@link PostViewOptions} containing the options for the call
 * @return a {@link ServiceCall} with a result of type {@link ViewResult}
 */
public ServiceCall<ViewResult> postView(PostViewOptions postViewOptions) {
    com.ibm.cloud.sdk.core.util.Validator.notNull(postViewOptions, "postViewOptions cannot be null");
    Map<String, String> pathParamsMap = new HashMap<String, String>();
    pathParamsMap.put("db", postViewOptions.db());
    pathParamsMap.put("ddoc", postViewOptions.ddoc());
    pathParamsMap.put("view", postViewOptions.view());
    RequestBuilder builder = RequestBuilder.post(RequestBuilder.resolveRequestUrl(getServiceUrl(), "/{db}/_design/{ddoc}/_view/{view}", pathParamsMap));
    Map<String, String> sdkHeaders = SdkCommon.getSdkHeaders("cloudant", "v1", "postView");
    for (Entry<String, String> header : sdkHeaders.entrySet()) {
        builder.header(header.getKey(), header.getValue());
    }
    builder.header("Accept", "application/json");
    final JsonObject contentJson = new JsonObject();
    if (postViewOptions.attEncodingInfo() != null) {
        contentJson.addProperty("att_encoding_info", postViewOptions.attEncodingInfo());
    }
    if (postViewOptions.attachments() != null) {
        contentJson.addProperty("attachments", postViewOptions.attachments());
    }
    if (postViewOptions.conflicts() != null) {
        contentJson.addProperty("conflicts", postViewOptions.conflicts());
    }
    if (postViewOptions.descending() != null) {
        contentJson.addProperty("descending", postViewOptions.descending());
    }
    if (postViewOptions.includeDocs() != null) {
        contentJson.addProperty("include_docs", postViewOptions.includeDocs());
    }
    if (postViewOptions.inclusiveEnd() != null) {
        contentJson.addProperty("inclusive_end", postViewOptions.inclusiveEnd());
    }
    if (postViewOptions.limit() != null) {
        contentJson.addProperty("limit", postViewOptions.limit());
    }
    if (postViewOptions.skip() != null) {
        contentJson.addProperty("skip", postViewOptions.skip());
    }
    if (postViewOptions.updateSeq() != null) {
        contentJson.addProperty("update_seq", postViewOptions.updateSeq());
    }
    if (postViewOptions.endkey() != null) {
        contentJson.add("endkey", com.ibm.cloud.sdk.core.util.GsonSingleton.getGson().toJsonTree(postViewOptions.endkey()));
    }
    if (postViewOptions.endkeyDocid() != null) {
        contentJson.addProperty("endkey_docid", postViewOptions.endkeyDocid());
    }
    if (postViewOptions.group() != null) {
        contentJson.addProperty("group", postViewOptions.group());
    }
    if (postViewOptions.groupLevel() != null) {
        contentJson.addProperty("group_level", postViewOptions.groupLevel());
    }
    if (postViewOptions.key() != null) {
        contentJson.add("key", com.ibm.cloud.sdk.core.util.GsonSingleton.getGson().toJsonTree(postViewOptions.key()));
    }
    if (postViewOptions.keys() != null) {
        contentJson.add("keys", com.ibm.cloud.sdk.core.util.GsonSingleton.getGson().toJsonTree(postViewOptions.keys()));
    }
    if (postViewOptions.reduce() != null) {
        contentJson.addProperty("reduce", postViewOptions.reduce());
    }
    if (postViewOptions.stable() != null) {
        contentJson.addProperty("stable", postViewOptions.stable());
    }
    if (postViewOptions.startkey() != null) {
        contentJson.add("startkey", com.ibm.cloud.sdk.core.util.GsonSingleton.getGson().toJsonTree(postViewOptions.startkey()));
    }
    if (postViewOptions.startkeyDocid() != null) {
        contentJson.addProperty("startkey_docid", postViewOptions.startkeyDocid());
    }
    if (postViewOptions.update() != null) {
        contentJson.addProperty("update", postViewOptions.update());
    }
    builder.bodyJson(contentJson);
    ResponseConverter<ViewResult> responseConverter = ResponseConverterUtils.getValue(new com.google.gson.reflect.TypeToken<ViewResult>() {
    }.getType());
    return createServiceCall(builder.build(), responseConverter);
}
Also used : RequestBuilder(com.ibm.cloud.sdk.core.http.RequestBuilder) HashMap(java.util.HashMap) JsonObject(com.google.gson.JsonObject) ViewResult(com.ibm.cloud.cloudant.v1.model.ViewResult)

Aggregations

HashMap (java.util.HashMap)32 RequestBuilder (com.ibm.cloud.sdk.core.http.RequestBuilder)30 Document (com.ibm.cloud.cloudant.v1.model.Document)22 DocumentResult (com.ibm.cloud.cloudant.v1.model.DocumentResult)20 ArrayList (java.util.ArrayList)16 Test (org.testng.annotations.Test)12 Attachment (com.ibm.cloud.cloudant.v1.model.Attachment)10 DocumentRevisionStatus (com.ibm.cloud.cloudant.v1.model.DocumentRevisionStatus)10 Revisions (com.ibm.cloud.cloudant.v1.model.Revisions)10 DesignDocument (com.ibm.cloud.cloudant.v1.model.DesignDocument)9 ReplicationDocument (com.ibm.cloud.cloudant.v1.model.ReplicationDocument)9 SchedulerDocument (com.ibm.cloud.cloudant.v1.model.SchedulerDocument)9 JsonObject (com.google.gson.JsonObject)8 AllDocsResult (com.ibm.cloud.cloudant.v1.model.AllDocsResult)6 BulkGetQueryDocument (com.ibm.cloud.cloudant.v1.model.BulkGetQueryDocument)6 BulkGetResultDocument (com.ibm.cloud.cloudant.v1.model.BulkGetResultDocument)6 MockResponse (okhttp3.mockwebserver.MockResponse)6 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)6 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)6 PostDocumentOptions (com.ibm.cloud.cloudant.v1.model.PostDocumentOptions)5