Android Open Source - couchbase-lite-android Mock Dispatcher






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 ww . j  a v  a  2  s  .co m*/
import com.squareup.okhttp.mockwebserver.Dispatcher;
import com.squareup.okhttp.mockwebserver.MockResponse;
import com.squareup.okhttp.mockwebserver.RecordedRequest;

import java.util.HashMap;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * Custom dispatcher which allows to queue up MockResponse objects
 * based on the request path.  Eg, there will be a separate response
 * queue for requests to /db/_changes.
 */
public class MockDispatcher extends Dispatcher {

    // Map where the key is a path regex, (eg, "/_changes/*), and
    // the value is a Queue of MockResponse objects
    private Map<String, BlockingQueue<SmartMockResponse>> queueMap;

    // Map where the key is a path regex, (eg, "/_changes/*), and
    // the value is a Queue of RecordedRequest objects this dispatcher has dispatched.
    private Map<String, BlockingQueue<RecordedRequest>> recordedRequestQueueMap;

    // Map where key is RecordedReqeust instance, and value is the MockResponse that
    // was returned for that RecordedRequest.
    private Map<RecordedRequest, MockResponse> recordedReponseMap;

    // add these headers to every request
    private Map<String, String> headers;

    public enum ServerType { SYNC_GW, COUCHDB }

    public MockDispatcher() {
        super();
        queueMap = new ConcurrentHashMap<String, BlockingQueue<SmartMockResponse>>();
        recordedRequestQueueMap = new ConcurrentHashMap<String, BlockingQueue<RecordedRequest>>();
        recordedReponseMap = new ConcurrentHashMap<RecordedRequest, MockResponse>();
        headers = new HashMap<String, String>();
    }

    public Map<String, String> getHeaders() {
        return headers;
    }

    public void setHeaders(Map<String, String> headers) {
        this.headers = headers;
    }

    public void setServerType(ServerType serverType) {
        switch (serverType) {
            case SYNC_GW:
                headers.put("Server", "Couchbase Sync Gateway/1.0.0");
                break;
            default:
                headers.remove("Server");
        }
    }

    @Override
    public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
        System.out.println(String.format("Request: %s", request));
        for(String pathRegex: queueMap.keySet()){
            if (regexMatches(pathRegex, request.getPath())) {
                recordRequest(pathRegex, request);
                BlockingQueue<SmartMockResponse> responseQueue = queueMap.get(pathRegex);
                if (responseQueue == null) {
                    String msg = String.format("No queue found for pathRegex: %s", pathRegex);
                    throw new RuntimeException(msg);
                }
                if (!responseQueue.isEmpty()) {
                    SmartMockResponse smartMockResponse = responseQueue.take();
                    if (smartMockResponse.isSticky()) {
                        responseQueue.put(smartMockResponse); // if it's sticky, put it back in queue
                    }
                    if (smartMockResponse.delayMs() > 0) {
                        System.out.println(String.format("Delaying response %s for %d ms (path: %s)", smartMockResponse, smartMockResponse.delayMs(), pathRegex));
                        Thread.sleep(smartMockResponse.delayMs());
                        System.out.println(String.format("Finished delaying response %s for %d (path: %s)", smartMockResponse, smartMockResponse.delayMs(), pathRegex));
                    }
                    MockResponse mockResponse = smartMockResponse.generateMockResponse(request);
                    System.out.println(String.format("Response: %s", mockResponse.getBody()));
                    addHeaders(mockResponse);
                    recordedReponseMap.put(request, mockResponse);
                    return mockResponse;
                } else {
                    MockResponse mockResponse = new MockResponse();
                    mockResponse.setStatus("HTTP/1.1 406 NOT ACCEPTABLE");
                    recordedReponseMap.put(request, mockResponse);
                    return mockResponse; // fail fast
                }
            }
        }
        MockResponse mockResponse = new MockResponse();
        mockResponse.setStatus("HTTP/1.1 406 NOT ACCEPTABLE");
        recordedReponseMap.put(request, mockResponse);
        return mockResponse; // fail fast
    }

    public void enqueueResponse(String pathRegex, SmartMockResponse response) {
        BlockingQueue<SmartMockResponse> responseQueue = queueMap.get(pathRegex);
        if (responseQueue == null) {
            responseQueue = new LinkedBlockingDeque<SmartMockResponse>();
            queueMap.put(pathRegex, responseQueue);
        }
        responseQueue.add(response);
    }

    public void enqueueResponse(String pathRegex, MockResponse response) {

        // get the response queue for this path regex
        BlockingQueue<SmartMockResponse> responseQueue = queueMap.get(pathRegex);
        if (responseQueue == null) {
            // create one on demand if it doesn't already exist
            responseQueue = new LinkedBlockingDeque<SmartMockResponse>();
            queueMap.put(pathRegex, responseQueue);
        }
        // add the response to the queue.  since it's not a smart mock response, wrap it
        responseQueue.add(MockHelper.wrap(response));
    }

    public void clearQueuedResponse(String pathRegex) {
        // get the response queue for this path regex
        BlockingQueue<SmartMockResponse> responseQueue = queueMap.get(pathRegex);
        if (responseQueue != null) {
            responseQueue.clear();
        }
    }

    public void clearRecordedRequests(String pathRegex) {
        BlockingQueue<RecordedRequest> queue = recordedRequestQueueMap.get(pathRegex);
        if (queue != null) {
            queue.clear();
        }
    }

    public RecordedRequest takeRequest(String pathRegex) {
        BlockingQueue<RecordedRequest> queue = recordedRequestQueueMap.get(pathRegex);
        if (queue == null) {
            return null;
        }
        if (queue.isEmpty()) {
            return null;
        }
        try {
            return queue.take();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    public BlockingQueue<RecordedRequest> getRequestQueueSnapshot(String pathRegex) {
        BlockingQueue<RecordedRequest> queue = recordedRequestQueueMap.get(pathRegex);
        if (queue == null) {
            return null;
        }
        BlockingQueue<RecordedRequest> result = new LinkedBlockingQueue<RecordedRequest>(queue);
        return result;
    }

    public MockResponse takeRecordedResponseBlocking(RecordedRequest request) {
        while (true) {
            if (!recordedReponseMap.containsKey(request)) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                continue;
            } else {
                MockResponse response = recordedReponseMap.get(request);
                if (response != null) {
                    return response;
                }
            }

        }
    }

    public RecordedRequest takeRequestBlocking(String pathRegex) {

        BlockingQueue<RecordedRequest> queue = recordedRequestQueueMap.get(pathRegex);

        // since the queue itself will be created lazily, we need to do a silly
        // polling loop until the queue appears (if ever -- otherwise this will never return)
        while (queue == null) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            queue = recordedRequestQueueMap.get(pathRegex);
        }

        try {
            return queue.take();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    public boolean verifyAllRecordedRequestsTaken() {
        for (String pathRegex : recordedRequestQueueMap.keySet()) {
            BlockingQueue<RecordedRequest> queue = recordedRequestQueueMap.get(pathRegex);
            if (queue == null) {
                continue;
            }
            if (!queue.isEmpty()) {
                return false;
            }
        }
        return true;
    }

    public void reset() {
        recordedRequestQueueMap.clear();
        queueMap.clear();
    }

    private void recordRequest(String pathRegex, RecordedRequest request) {
        BlockingQueue<RecordedRequest> queue = recordedRequestQueueMap.get(pathRegex);
        if (queue == null) {
            queue = new LinkedBlockingQueue<RecordedRequest>();
            recordedRequestQueueMap.put(pathRegex, queue);
        }
        queue.add(request);
    }

    private void addHeaders(MockResponse mockResponse) {
        if (!headers.isEmpty()) {
            for (String headerKey : headers.keySet()) {
                String headerVal = headers.get(headerKey);
                mockResponse.setHeader(headerKey, headerVal);
            }
        }
    }

    private boolean regexMatches(String pathRegex, String actualPath) {
        try {
            return actualPath.matches(pathRegex);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


}




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