Android Open Source - couchbase-lite-android Multipart Reader Test






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;
/*from ww w  .j  a va2  s .c  om*/
import com.couchbase.lite.support.MultipartReaderDelegate;
import com.couchbase.lite.support.Range;

import junit.framework.Assert;

import org.apache.http.util.ByteArrayBuffer;

import java.io.ByteArrayInputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MultipartReaderTest extends LiteTestCase {

    class TestMultipartReaderDelegate implements MultipartReaderDelegate {

        private ByteArrayBuffer currentPartData;
        private List<Map<String, String>> headersList;
        private List<ByteArrayBuffer> partList;

        public void startedPart(Map<String, String> headers) {
            Assert.assertNull(currentPartData);
            if (partList == null) {
                partList = new ArrayList<ByteArrayBuffer>();
            }
            currentPartData = new ByteArrayBuffer(1024);
            partList.add(currentPartData);
            if (headersList == null) {
                headersList = new ArrayList<Map<String, String>>();
            }
            headersList.add(headers);
        }

        public void appendToPart(byte[] data) {
            Assert.assertNotNull(currentPartData);
            currentPartData.append(data, 0, data.length);
        }

        public void finishedPart() {
            Assert.assertNotNull(currentPartData);
            currentPartData = null;
        }

    }

    public void testParseContentType() {

        Charset utf8 = Charset.forName("UTF-8");
        HashMap<String, byte[]> contentTypes = new HashMap<String, byte[]>();
        contentTypes.put("multipart/related; boundary=\"BOUNDARY\"", new String("\r\n--BOUNDARY").getBytes(utf8));
        contentTypes.put("multipart/related; boundary=BOUNDARY", new String("\r\n--BOUNDARY").getBytes(utf8));
        contentTypes.put("multipart/related;boundary=X", new String("\r\n--X").getBytes(utf8));

        for (String contentType : contentTypes.keySet()) {
            MultipartReaderDelegate delegate = null;
            com.couchbase.lite.support.MultipartReader reader = new com.couchbase.lite.support.MultipartReader(contentType, delegate);
            byte[] expectedBoundary = (byte[]) contentTypes.get(contentType);
            byte[] boundary = reader.getBoundary();
            Assert.assertTrue(Arrays.equals(boundary, expectedBoundary));
        }

        try {
            MultipartReaderDelegate delegate = null;
            com.couchbase.lite.support.MultipartReader reader = new com.couchbase.lite.support.MultipartReader("multipart/related; boundary=\"BOUNDARY", delegate);
            Assert.assertTrue("Should not have gotten here, above lines should have thrown exception", false);
        } catch (Exception e) {
            // expected exception
        }

    }

    public void testParseHeaders() {
        String testString = new String("\r\nFoo: Bar\r\n Header : Val ue ");
        com.couchbase.lite.support.MultipartReader reader = new com.couchbase.lite.support.MultipartReader("multipart/related;boundary=X", null);
        reader.parseHeaders(testString);
        Assert.assertEquals(reader.headers.keySet().size(), 2);
    }

    public void testSearchFor() throws Exception {
        String testString = new String("\r\n\r\n");
        byte[] testStringBytes = testString.getBytes(Charset.forName("UTF-8"));
        com.couchbase.lite.support.MultipartReader reader = new com.couchbase.lite.support.MultipartReader("multipart/related;boundary=X", null);
        reader.appendData(testStringBytes);
        Range r = reader.searchFor(testStringBytes, 0);
        Assert.assertEquals(0, r.getLocation());
        Assert.assertEquals(4, r.getLength());

        Range r2 = reader.searchFor(new String("nomatch").getBytes(Charset.forName("UTF-8")), 0);
        Assert.assertEquals(-1, r2.getLocation());
        Assert.assertEquals(0, r2.getLength());

    }

    public void testReaderOperation() {

        Charset utf8 = Charset.forName("UTF-8");

        byte[] mime = new String("--BOUNDARY\r\nFoo: Bar\r\n Header : Val ue \r\n\r\npart the first\r\n--BOUNDARY  \r\n\r\n2nd part\r\n--BOUNDARY--").getBytes(utf8);
        readerOperationWithMime(mime, "part the first", "2nd part", mime.length);

        byte[] mime2 = new String("--BOUNDARY\r\nFoo: Bar\r\n Header : Val ue \r\n\r\npart the first\r\n--BOUNDARY\r\n\r\n2nd part\r\n--BOUNDARY--").getBytes(utf8);
        readerOperationWithMime(mime2, "part the first", "2nd part", mime2.length);

        StringBuffer mime3Buffer = new StringBuffer();
        StringBuffer mime3BufferFirstPart = new StringBuffer();
        mime3Buffer.append("--BOUNDARY\r\nFoo: Bar\r\n Header : Val ue \r\n\r\n");
        for (int i=0; i<10000; i++) {
            mime3BufferFirstPart.append("large_part_data");
        }
        mime3Buffer.append(mime3BufferFirstPart);
        mime3Buffer.append("\r\n--BOUNDARY\r\n\r\n2nd part\r\n--BOUNDARY--");
        byte[] mime3 = mime3Buffer.toString().getBytes(utf8);
        readerOperationWithMime(mime3, mime3BufferFirstPart.toString(), "2nd part", 1024);


    }

    private void readerOperationWithMime(byte[] mime, String part1ExpectedStr, String part2ExpectedStr, int recommendedChunkSize) {

        Charset utf8 = Charset.forName("UTF-8");

        // if the caller passes in a special chunksize, which is not equal to mime.length, then
        // lets test the algorithm _only_ at that chunksize.  otherwise, test it at every chunksize
        // between 1 and mime.length.  (this is needed because when testing with a very large mime value,
        // the test takes too long to test at every single chunk size)
        int chunkSize=1;
        if (recommendedChunkSize != mime.length) {
            chunkSize = recommendedChunkSize;
        }

        for (; chunkSize <= recommendedChunkSize; ++chunkSize) {
            ByteArrayInputStream mimeInputStream = new ByteArrayInputStream(mime);
            TestMultipartReaderDelegate delegate = new TestMultipartReaderDelegate();
            String contentType = "multipart/related; boundary=\"BOUNDARY\"";
            com.couchbase.lite.support.MultipartReader reader = new com.couchbase.lite.support.MultipartReader(contentType, delegate);
            Assert.assertFalse(reader.finished());

            int location = 0;
            int length = 0;

            do {
                Assert.assertTrue("Parser didn't stop at end", location < mime.length);
                length = Math.min(chunkSize, (mime.length - location));
                byte[] bytesRead = new byte[length];
                mimeInputStream.read(bytesRead, 0, length);
                reader.appendData(bytesRead);
                location += chunkSize;
            } while (!reader.finished());

            Assert.assertEquals(delegate.partList.size(), 2);
            Assert.assertEquals(delegate.headersList.size(), 2);

            byte[] part1Expected = part1ExpectedStr.getBytes(utf8);
            byte[] part2Expected = part2ExpectedStr.getBytes(utf8);
            ByteArrayBuffer part1 = delegate.partList.get(0);
            ByteArrayBuffer part2 = delegate.partList.get(1);
            Assert.assertTrue(Arrays.equals(part1.toByteArray(), part1Expected));
            Assert.assertTrue(Arrays.equals(part2.toByteArray(), part2Expected));

            Map<String, String> headers1 = delegate.headersList.get(0);
            Assert.assertTrue(headers1.containsKey("Foo"));
            Assert.assertEquals(headers1.get("Foo"), "Bar");

            Assert.assertTrue(headers1.containsKey("Header"));
            Assert.assertEquals(headers1.get("Header"), "Val ue");

        }
    }

}




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