Android Open Source - couchbase-lite-android Mock Document Get






From Project

Back to project page couchbase-lite-android.

License

The source code is released under:

Apache License

If you think the Android project couchbase-lite-android listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package com.couchbase.lite.mockserver;
//w  w w .  ja va2  s .  c  o m
import com.couchbase.lite.BlobKey;
import com.couchbase.lite.BlobStore;
import com.couchbase.lite.Manager;
import com.couchbase.lite.support.Base64;
import com.squareup.okhttp.mockwebserver.MockResponse;

import org.apache.commons.io.IOUtils;
import com.couchbase.org.apache.http.entity.mime.MultipartEntity;
import com.couchbase.org.apache.http.entity.mime.content.InputStreamBody;
import com.couchbase.org.apache.http.entity.mime.content.StringBody;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/*

    Generate mock document GET response, eg

    {
       "_id":"doc1-1402588904847",
       "_rev":"1-d57b1bc60eb9273c3349d932e15f9949",
       "_revisions":{
          "ids":[
             "d57b1bc60eb9273c3349d932e15f9949"
          ],
          "start":1
       },
       "bar":false,
       "foo":1
    }

    Limitations: it cannot represent docs with revision histories longer
    than one rev.

 */
public class MockDocumentGet {

    private String docId;
    private String rev;
    private Map<String, Object> jsonMap;
    private boolean includeAttachmentPart;

    // you can optionally supply a revHistoryMap, otherwise
    // a simple default rev history will be generated.
    private Map<String, Object> revHistoryMap;

    // a corresponding file must be in the /assets/ directory
    private List<String> attachmentFileNames;

    public MockDocumentGet() {
        attachmentFileNames = new ArrayList<String>();
        this.revHistoryMap = new HashMap<String, Object>();
        this.includeAttachmentPart = true;
    }

    public MockDocumentGet(MockDocument mockDocument) {
        this();
        this.docId = mockDocument.getDocId();
        this.rev = mockDocument.getDocRev();
        this.jsonMap = mockDocument.getJsonMap();
    }

    public Map<String, Object> getRevHistoryMap() {
        return revHistoryMap;
    }

    public void setRevHistoryMap(Map<String, Object> revHistoryMap) {
        this.revHistoryMap = revHistoryMap;
    }

    public String getDocId() {
        return docId;
    }

    public MockDocumentGet setDocId(String docId) {
        this.docId = docId;
        return this;
    }

    public String getRev() {
        return rev;
    }

    public MockDocumentGet setRev(String rev) {
        this.rev = rev;
        return this;
    }

    public void addAttachmentFilename(String attachmentFilename) {
        attachmentFileNames.add(attachmentFilename);
    }

    public Map<String, Object> getJsonMap() {
        return jsonMap;
    }

    public MockDocumentGet setJsonMap(Map<String, Object> jsonMap) {
        this.jsonMap = jsonMap;
        return this;
    }

    private Map<String, Object> generateRevHistoryMap() {
        if (revHistoryMap.isEmpty()) {
            Map<String, Object> simpleRevHIstoryMap = new HashMap<String, Object>();
            // parse rev into components, eg
            String[] revComponents = rev.split("-");
            String numericPrefixStr = revComponents[0];  // eg, "1"
            String digest = revComponents[1]; // eg, "d57b1bc60eb9273c3349d932e15f9949"
            int numericPrefix = Integer.parseInt(numericPrefixStr);
            List<String> revHistoryDigestIds = new ArrayList<String>();
            revHistoryDigestIds.add(digest);
            simpleRevHIstoryMap.put("ids", revHistoryDigestIds);
            simpleRevHIstoryMap.put("start", numericPrefix);
            return simpleRevHIstoryMap;
        } else {
            return revHistoryMap;
        }
    }

    private Map<String, Object> generateDocumentMap() {
        Map<String, Object> docMap = new HashMap<String, Object>();
        docMap.put("_id", getDocId());
        docMap.put("_rev", getRev());
        docMap.put("_revisions", generateRevHistoryMap());
        if (!attachmentFileNames.isEmpty()) {
            docMap.put("_attachments", generateAttachmentsMap());
        }
        docMap.putAll(jsonMap);
        return docMap;
    }

    /*
       {
           "_attachments":{
              "attachment3.png":{
                 "content_type":"image/png",
                 "digest":"sha1-nKikeP2tQRpJCHOpS4w7G+Kc12Y=",
                 "follows":true,
                 "length":19693,
                 "revpos":1
              }
           },
           "_id":"...",
           ...
       }
     */
    private Map<String, Object> generateAttachmentsMap() {
        Map<String, Object> attachmentsMap = new HashMap<String, Object>();
        for (String attachmentName : attachmentFileNames) {
            Map<String, Object> attachmentMap = new HashMap<String, Object>();
            if (attachmentName.endsWith("png")) {
                attachmentMap.put("content_type", "image/png");
            } else {
                throw new RuntimeException("Only png files are supported as test attachemnts");
            }
            attachmentMap.put("digest", calculateSha1Digest(attachmentName));
            if (this.isIncludeAttachmentPart()) {
                attachmentMap.put("follows", true);
            } else {
                attachmentMap.put("stub", true);
            }
            attachmentMap.put("length", MockDocumentGet.getAssetByteArray(attachmentName).length);
            attachmentMap.put("revpos", 1);

            attachmentsMap.put(attachmentName, attachmentMap);

        }
        return attachmentsMap;
    }

    public static String calculateSha1Digest(String attachmentAssetName) {
        byte[] attachmentBytes = MockDocumentGet.getAssetByteArray(attachmentAssetName);
        BlobKey blobKey = BlobStore.keyForBlob(attachmentBytes);
        String base64Sha1Digest = Base64.encodeBytes(blobKey.getBytes());
        String sha1 = String.format("sha1-%s", base64Sha1Digest);
        return sha1;
    }

    private String generateDocumentBody() {
        Map documentMap = generateDocumentMap();
        try {
            return Manager.getObjectMapper().writeValueAsString(documentMap);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public MockResponse generateMockResponse() {

        MockResponse mockResponse = new MockResponse();
        if (attachmentFileNames.isEmpty()) {
            mockResponse.setBody(generateDocumentBody());
            mockResponse.setHeader("Content-Type", "application/json");

        } else {
            createMultipartResponse(mockResponse);
        }

        mockResponse.setStatus("HTTP/1.1 200 OK");

        return mockResponse;
    }

    private void createMultipartResponse(MockResponse mockResponse) {

        InputStream stream;
        ByteArrayOutputStream baos;

        try {

            MultipartEntity multiPart = new MultipartEntity();
            String partNameIgnored = "part";  // this never seems to appear anywhere in response
            multiPart.addPart(partNameIgnored, new StringBody(generateDocumentBody(), "application/json", Charset.forName("UTF-8")));



            for (String attachmentName : attachmentFileNames) {

                byte[] attachmentBytes = getAssetByteArray(attachmentName);

                int contentLength = attachmentBytes.length;

                if (this.isIncludeAttachmentPart()) {
                    multiPart.addPart(attachmentName, new InputStreamBody(new ByteArrayInputStream(attachmentBytes), "image/png", attachmentName, contentLength));
                }

                baos = new ByteArrayOutputStream();
                multiPart.writeTo(baos);

                mockResponse.setHeader(multiPart.getContentType().getName(), multiPart.getContentType().getValue());

                byte[] body = baos.toByteArray();
                mockResponse.setBody(body);

                String bodyString = new String(body);

                baos.close();

            }




        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static InputStream getAsset(String name) {
        MockDocumentGet o = new MockDocumentGet();
        return o.getClass().getResourceAsStream("/assets/" + name);
    }

    public static byte[] getAssetByteArray(String name) {
        try {
            InputStream attachmentStream = getAsset(name);
            ByteArrayOutputStream attachmentBaos = new ByteArrayOutputStream();
            IOUtils.copy(attachmentStream, attachmentBaos);
            byte[] attachmentBytes = attachmentBaos.toByteArray();
            attachmentStream.close();
            attachmentBaos.close();
            return attachmentBytes;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    public boolean isIncludeAttachmentPart() {
        return includeAttachmentPart;
    }

    public void setIncludeAttachmentPart(boolean includeAttachmentPart) {  // TOO: rename to isStubbed()
        this.includeAttachmentPart = includeAttachmentPart;
    }

    public static class MockDocument {

        private String docId;
        private String docRev;
        private int docSeq;
        private String attachmentName;
        private Map<String, Object> jsonMap;

        public MockDocument(String docId, String docRev, int docSeq) {
            this.docId = docId;
            this.docRev = docRev;
            this.docSeq = docSeq;
        }

        /**
         * TODO: the MockDocumentGet.generateDocumentMap() method should
         * TODO: be refactored to use this, but first the revision history
         * TODO: will need to be moved to this object.
         */
        private Map<String, Object> generateDocumentMap(boolean attachmentFollows) {
            Map<String, Object> docMap = new HashMap<String, Object>();
            docMap.put("_id", getDocId());
            docMap.put("_rev", getDocRev());

            if (hasAttachment()) {
                docMap.put("_attachments", generateAttachmentsMap(attachmentFollows));
            }
            docMap.putAll(jsonMap);
            return docMap;
        }

        /**
         * TODO: the MockDocumentGet.generateDocumentMap() method should
         * TODO: be refactored to use this.
         */
        public String generateDocumentBody(boolean attachmentFollows) {
            Map documentMap = generateDocumentMap(attachmentFollows);
            try {
                return Manager.getObjectMapper().writeValueAsString(documentMap);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        /**
         * TODO: the MockDocumentGet.generateDocumentMap() method should
         * TODO: be refactored to use this, but first need to remove
         * TODO: attachmentFileNames field from MockDocumentGet
         */
        private Map<String, Object> generateAttachmentsMap(boolean attachmentFollows) {
            Map<String, Object> attachmentsMap = new HashMap<String, Object>();
            Map<String, Object> attachmentMap = new HashMap<String, Object>();
            if (attachmentName.endsWith("png")) {
                attachmentMap.put("content_type", "image/png");
            } else {
                throw new RuntimeException("Only png files are supported as test attachemnts");
            }
            attachmentMap.put("digest", calculateSha1Digest(attachmentName));
            if (attachmentFollows) {
                attachmentMap.put("follows", true);
            } else {
                attachmentMap.put("stub", true);
            }
            attachmentMap.put("length", MockDocumentGet.getAssetByteArray(attachmentName).length);
            attachmentMap.put("revpos", 1);

            attachmentsMap.put(attachmentName, attachmentMap);
            return attachmentsMap;
        }


        public Map<String, Object> getJsonMap() {
            return jsonMap;
        }

        public void setJsonMap(Map<String, Object> jsonMap) {
            this.jsonMap = jsonMap;
        }

        public String getAttachmentName() {
            return attachmentName;
        }

        public void setAttachmentName(String attachmentName) {
            this.attachmentName = attachmentName;
        }

        public boolean hasAttachment() {
            if (this.attachmentName != null && this.attachmentName.length() > 0) {
                return true;
            }
            return false;
        }

        public String getDocPathRegex() {
            return String.format("/db/%s\\?.*", getDocId());
        }

        public String getDocId() {
            return docId;
        }

        public void setDocId(String docId) {
            this.docId = docId;
        }

        public String getDocRev() {
            return docRev;
        }

        public void setDocRev(String docRev) {
            this.docRev = docRev;
        }

        public int getDocSeq() {
            return docSeq;
        }

        public void setDocSeq(int docSeq) {
            this.docSeq = docSeq;
        }
    }


}




Java Source Code List

com.couchbase.lite.ApiTest.java
com.couchbase.lite.AttachmentsTest.java
com.couchbase.lite.AuthTest.java
com.couchbase.lite.Base64Test.java
com.couchbase.lite.BlobStoreWriterTest.java
com.couchbase.lite.CRUDOperationsTest.java
com.couchbase.lite.CacheTest.java
com.couchbase.lite.ChangesTest.java
com.couchbase.lite.CollationTest.java
com.couchbase.lite.DatabaseTest.java
com.couchbase.lite.DocumentTest.java
com.couchbase.lite.LitePerfTestCase.java
com.couchbase.lite.LiteTestCase.java
com.couchbase.lite.LiteTestContext.java
com.couchbase.lite.LocalDocsTest.java
com.couchbase.lite.ManagerTest.java
com.couchbase.lite.MiscTest.java
com.couchbase.lite.MultipartReaderTest.java
com.couchbase.lite.RevTreeTest.java
com.couchbase.lite.RevisionsTest.java
com.couchbase.lite.RouterTest.java
com.couchbase.lite.SequenceMapTest.java
com.couchbase.lite.ValidationsTest.java
com.couchbase.lite.ViewsTest.java
com.couchbase.lite.android.AndroidContext.java
com.couchbase.lite.android.AndroidLogger.java
com.couchbase.lite.android.AndroidNetworkReachabilityManager.java
com.couchbase.lite.android.AndroidSQLiteStorageEngineFactory.java
com.couchbase.lite.android.AndroidSQLiteStorageEngine.java
com.couchbase.lite.mockserver.MockBulkDocs.java
com.couchbase.lite.mockserver.MockChangesFeedNoResponse.java
com.couchbase.lite.mockserver.MockChangesFeed.java
com.couchbase.lite.mockserver.MockCheckpointGet.java
com.couchbase.lite.mockserver.MockCheckpointPut.java
com.couchbase.lite.mockserver.MockDispatcher.java
com.couchbase.lite.mockserver.MockDocumentBulkGet.java
com.couchbase.lite.mockserver.MockDocumentGet.java
com.couchbase.lite.mockserver.MockDocumentPut.java
com.couchbase.lite.mockserver.MockFacebookAuthPost.java
com.couchbase.lite.mockserver.MockHelper.java
com.couchbase.lite.mockserver.MockPreloadedPullTarget.java
com.couchbase.lite.mockserver.MockRevsDiff.java
com.couchbase.lite.mockserver.MockSessionGet.java
com.couchbase.lite.mockserver.SmartMockResponse.java
com.couchbase.lite.mockserver.WrappedSmartMockResponse.java
com.couchbase.lite.performance2.Test01_CreateDocs.java
com.couchbase.lite.performance2.Test02_CreateDocsUnoptimizedWay.java
com.couchbase.lite.performance2.Test03_CreateDocsWithAttachments.java
com.couchbase.lite.performance2.Test06_PullReplication.java
com.couchbase.lite.performance2.Test07_PushReplication.java
com.couchbase.lite.performance2.Test08_DocRevisions.java
com.couchbase.lite.performance2.Test09_LoadDB.java
com.couchbase.lite.performance2.Test10_DeleteDB.java
com.couchbase.lite.performance2.Test11_DeleteDocs.java
com.couchbase.lite.performance2.Test12_IndexView.java
com.couchbase.lite.performance2.Test13_QueryView.java
com.couchbase.lite.performance2.Test14_ReduceView.java
com.couchbase.lite.performance2.Test28_KeySizes.java
com.couchbase.lite.performance2.Test29_AllDocQuery.java
com.couchbase.lite.performance2.Test30_LiveQuery.java
com.couchbase.lite.performance2.Test31_CompactDB.java
com.couchbase.lite.performance.Test10_DeleteDB.java
com.couchbase.lite.performance.Test11_DeleteDocs.java
com.couchbase.lite.performance.Test12_IndexView.java
com.couchbase.lite.performance.Test13_QueryView.java
com.couchbase.lite.performance.Test14_ReduceView.java
com.couchbase.lite.performance.Test16_ParallelPushReplication.java
com.couchbase.lite.performance.Test1_CreateDocs.java
com.couchbase.lite.performance.Test2_CreateDocsUnoptimizedWay.java
com.couchbase.lite.performance.Test3_CreateDocsWithAttachments.java
com.couchbase.lite.performance.Test6_PushReplication.java
com.couchbase.lite.performance.Test7_PullReplication.java
com.couchbase.lite.performance.Test8_DocRevisions.java
com.couchbase.lite.performance.Test9_LoadDB.java
com.couchbase.lite.replicator.BulkDownloaderTest.java
com.couchbase.lite.replicator.ChangeTrackerTest.java
com.couchbase.lite.replicator.CustomizableMockHttpClient.java
com.couchbase.lite.replicator.ReplicationTest.java
com.couchbase.lite.replicator.ResponderChain.java
com.couchbase.lite.support.BatcherTest.java
com.couchbase.lite.support.JsonDocumentTest.java
com.couchbase.lite.support.PersistentCookieStoreTest.java
com.couchbase.lite.support.RemoteRequestTest.java
com.couchbase.touchdb.RevCollator.java
com.couchbase.touchdb.TDCollateJSON.java