Exemplo n.º 1
0
        private void ReaderOperationWithMime(byte[] mime, string part1ExpectedStr, string
                                             part2ExpectedStr, int recommendedChunkSize)
        {
            Encoding utf8 = Sharpen.Extensions.GetEncoding("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);
                MultipartReaderTest.TestMultipartReaderDelegate delegate_ = new MultipartReaderTest.TestMultipartReaderDelegate
                                                                                (this);
                string          contentType = "multipart/related; boundary=\"BOUNDARY\"";
                MultipartReader reader      = new MultipartReader(contentType, delegate_);
                NUnit.Framework.Assert.IsFalse(reader.Finished());
                int location = 0;
                int length   = 0;
                do
                {
                    NUnit.Framework.Assert.IsTrue("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());
                NUnit.Framework.Assert.AreEqual(delegate_.partList.Count, 2);
                NUnit.Framework.Assert.AreEqual(delegate_.headersList.Count, 2);
                byte[]          part1Expected = Sharpen.Runtime.GetBytesForString(part1ExpectedStr, utf8);
                byte[]          part2Expected = Sharpen.Runtime.GetBytesForString(part2ExpectedStr, utf8);
                ByteArrayBuffer part1         = delegate_.partList[0];
                ByteArrayBuffer part2         = delegate_.partList[1];
                NUnit.Framework.Assert.IsTrue(Arrays.Equals(part1.ToByteArray(), part1Expected));
                NUnit.Framework.Assert.IsTrue(Arrays.Equals(part2.ToByteArray(), part2Expected));
                IDictionary <string, string> headers1 = delegate_.headersList[0];
                NUnit.Framework.Assert.IsTrue(headers1.ContainsKey("Foo"));
                NUnit.Framework.Assert.AreEqual(headers1.Get("Foo"), "Bar");
                NUnit.Framework.Assert.IsTrue(headers1.ContainsKey("Header"));
                NUnit.Framework.Assert.AreEqual(headers1.Get("Header"), "Val ue");
            }
        }
Exemplo n.º 2
0
        protected internal override void ExecuteRequest(HttpClient httpClient, HttpRequestMessage
                                                        request)
        {
            object       fullBody = null;
            Exception    error    = null;
            HttpResponse response = null;

            try
            {
                if (request.IsAborted())
                {
                    RespondWithResult(fullBody, new Exception(string.Format("%s: Request %s has been aborted"
                                                                            , this, request)), response);
                    return;
                }
                response = httpClient.Execute(request);
                try
                {
                    // add in cookies to global store
                    if (httpClient is DefaultHttpClient)
                    {
                        DefaultHttpClient defaultHttpClient = (DefaultHttpClient)httpClient;
                        clientFactory.AddCookies(defaultHttpClient.GetCookieStore().GetCookies());
                    }
                }
                catch (Exception e)
                {
                    Log.E(Log.TagRemoteRequest, "Unable to add in cookies to global store", e);
                }
                StatusLine status = response.GetStatusLine();
                if (status.GetStatusCode() >= 300)
                {
                    Log.E(Log.TagRemoteRequest, "Got error status: %d for %s.  Reason: %s", status.GetStatusCode
                              (), request, status.GetReasonPhrase());
                    error = new HttpResponseException(status.GetStatusCode(), status.GetReasonPhrase(
                                                          ));
                }
                else
                {
                    HttpEntity  entity            = response.GetEntity();
                    Header      contentTypeHeader = entity.GetContentType();
                    InputStream inputStream       = null;
                    if (contentTypeHeader != null && contentTypeHeader.GetValue().Contains("multipart/"
                                                                                           ))
                    {
                        Log.V(Log.TagSync, "contentTypeHeader = %s", contentTypeHeader.GetValue());
                        try
                        {
                            _topReader  = new MultipartReader(contentTypeHeader.GetValue(), this);
                            inputStream = entity.GetContent();
                            int    bufLen       = 1024;
                            byte[] buffer       = new byte[bufLen];
                            int    numBytesRead = 0;
                            while ((numBytesRead = inputStream.Read(buffer)) != -1)
                            {
                                if (numBytesRead != bufLen)
                                {
                                    byte[] bufferToAppend = Arrays.CopyOfRange(buffer, 0, numBytesRead);
                                    _topReader.AppendData(bufferToAppend);
                                }
                                else
                                {
                                    _topReader.AppendData(buffer);
                                }
                            }
                            _topReader.Finished();
                            RespondWithResult(fullBody, error, response);
                        }
                        finally
                        {
                            try
                            {
                                inputStream.Close();
                            }
                            catch (IOException)
                            {
                            }
                        }
                    }
                    else
                    {
                        Log.V(Log.TagSync, "contentTypeHeader is not multipart = %s", contentTypeHeader.GetValue
                                  ());
                        if (entity != null)
                        {
                            try
                            {
                                inputStream = entity.GetContent();
                                fullBody    = Manager.GetObjectMapper().ReadValue <object>(inputStream);
                                RespondWithResult(fullBody, error, response);
                            }
                            finally
                            {
                                try
                                {
                                    inputStream.Close();
                                }
                                catch (IOException)
                                {
                                }
                            }
                        }
                    }
                }
            }
            catch (IOException e)
            {
                Log.E(Log.TagRemoteRequest, "io exception", e);
                error = e;
                RespondWithResult(fullBody, e, response);
            }
            catch (Exception e)
            {
                Log.E(Log.TagRemoteRequest, "%s: executeRequest() Exception: ", e, this);
                error = e;
                RespondWithResult(fullBody, e, response);
            }
        }
Exemplo n.º 3
0
        protected override internal void ExecuteRequest(HttpClient httpClient, HttpRequestMessage request)
        {
            object              fullBody = null;
            Exception           error    = null;
            HttpResponseMessage response = null;

            try
            {
                if (_tokenSource.IsCancellationRequested)
                {
                    RespondWithResult(fullBody, new Exception(string.Format("{0}: Request {1} has been aborted", this, request)), response);
                    return;
                }
            }
            catch (AggregateException e)
            {
                var err = e.InnerException;
                Log.E(Tag, "Unhandled Exception", err);
                error = err;
                RespondWithResult(fullBody, err, response);
                return;
            }
            catch (IOException e)
            {
                Log.E(Tag, "IO Exception", e);
                error = e;
                RespondWithResult(fullBody, e, response);
                return;
            }
            catch (Exception e)
            {
                Log.E(Tag, "ExecuteRequest Exception: ", e);
                error = e;
                RespondWithResult(fullBody, e, response);
                return;
            }

            try
            {
                Log.D(Tag + ".ExecuteRequest", "Sending request: {0}", request);
                var requestTokenSource = CancellationTokenSource.CreateLinkedTokenSource(_tokenSource.Token);
                var responseTask       = httpClient.SendAsync(request, requestTokenSource.Token);
                if (!responseTask.Wait((Int32)ManagerOptions.Default.RequestTimeout.TotalMilliseconds, requestTokenSource.Token))
                {
                    Log.E(Tag, "Response task timed out: {0}, {1}", responseTask, TaskScheduler.Current);
                    throw new HttpResponseException(HttpStatusCode.RequestTimeout);
                }
                requestTokenSource.Dispose();
                response = responseTask.Result;
            }
            catch (AggregateException e)
            {
                var err = e.InnerException;
                Log.E(Tag, "Unhandled Exception at Line 129 or 130", err);
                error = err;
                RespondWithResult(fullBody, err, response);
            }
            catch (IOException e)
            {
                Log.E(Tag, "IO Exception", e);
                error = e;
                RespondWithResult(fullBody, e, response);
            }
            catch (Exception e)
            {
                Log.E(Tag, "ExecuteRequest Exception: ", e);
                error = e;
                RespondWithResult(fullBody, e, response);
            }

            try
            {
                var status = response.StatusCode;
                if (response == null || !response.IsSuccessStatusCode)
                {
                    Log.E(Tag, "Got error status: {0} for {1}.  Reason: {2}", status.GetStatusCode(), request, response.ReasonPhrase);
                    error = new HttpResponseException(status);
                }
                else
                {
                    Log.D(Tag, "Processing response: {0}", response);
                    var    entity            = response.Content;
                    var    contentTypeHeader = entity.Headers.ContentType;
                    Stream inputStream       = null;
                    if (contentTypeHeader != null && contentTypeHeader.ToString().Contains("multipart/"))
                    {
                        Log.V(Tag, "contentTypeHeader = {0}", contentTypeHeader.ToString());
                        try
                        {
                            _topReader  = new MultipartReader(contentTypeHeader.ToString(), this);
                            inputStream = entity.ReadAsStreamAsync().Result;
                            const int bufLen       = 1024;
                            var       buffer       = new byte[bufLen];
                            var       numBytesRead = 0;
                            while ((numBytesRead = inputStream.Read(buffer, 0, bufLen)) > 0)
                            {
                                if (numBytesRead != bufLen)
                                {
                                    var bufferToAppend = new ArraySegment <byte>(buffer, 0, numBytesRead).ToArray();
                                    _topReader.AppendData(bufferToAppend);
                                }
                                else
                                {
                                    _topReader.AppendData(buffer);
                                }
                            }
                            _topReader.Finished();
                            RespondWithResult(fullBody, error, response);
                        }
                        finally
                        {
                            try
                            {
                                inputStream.Close();
                            }
                            catch (IOException)
                            {
                            }
                        }
                    }
                    else
                    {
                        Log.V(Tag, "contentTypeHeader is not multipart = {0}", contentTypeHeader.ToString());
                        if (entity != null)
                        {
                            try
                            {
                                inputStream = entity.ReadAsStreamAsync().Result;
                                fullBody    = Manager.GetObjectMapper().ReadValue <object>(inputStream);
                                RespondWithResult(fullBody, error, response);
                            }
                            finally
                            {
                                try
                                {
                                    inputStream.Close();
                                }
                                catch (IOException)
                                {
                                }
                            }
                        }
                    }
                }
            }
            catch (AggregateException e)
            {
                var err = e.InnerException;
                Log.E(Tag, "Unhandled Exception", err);
                error = err;
                RespondWithResult(fullBody, err, response);
            }
            catch (IOException e)
            {
                Log.E(Tag, "IO Exception", e);
                error = e;
                RespondWithResult(fullBody, e, response);
            }
            catch (Exception e)
            {
                Log.E(Tag, "ExecuteRequest Exception: ", e);
                error = e;
                RespondWithResult(fullBody, e, response);
            }
        }
Exemplo n.º 4
0
        protected override internal Task ExecuteRequest(HttpClient httpClient, HttpRequestMessage request)
        {
            object              fullBody = null;
            Exception           error    = null;
            HttpResponseMessage response = null;

            if (_tokenSource.IsCancellationRequested)
            {
                RespondWithResult(fullBody, new Exception(string.Format("{0}: Request {1} has been aborted", this, request)), response);
                var tcs = new TaskCompletionSource <bool>();
                tcs.SetCanceled();
                return(tcs.Task);
            }

            Log.D(Tag + ".ExecuteRequest", "Sending request: {0}", request);
            var requestTokenSource = CancellationTokenSource.CreateLinkedTokenSource(_tokenSource.Token);
            var retVal             = httpClient.SendAsync(request, requestTokenSource.Token);

            retVal.ConfigureAwait(false).GetAwaiter().OnCompleted(() => {
                requestTokenSource.Dispose();
                try {
                    response = retVal.Result;
                } catch (Exception e) {
                    var err = (e is AggregateException) ? e.InnerException : e;
                    Log.E(Tag, "Unhandled Exception", err);
                    error = err;
                    RespondWithResult(fullBody, err, response);
                    return;
                }

                try
                {
                    if (response == null)
                    {
                        Log.E(Tag, "Didn't get response for {0}", request);

                        error = new HttpRequestException();
                        RespondWithResult(fullBody, error, response);
                    }
                    else if (!response.IsSuccessStatusCode)
                    {
                        HttpStatusCode status = response.StatusCode;

                        Log.E(Tag, "Got error status: {0} for {1}.  Reason: {2}", status.GetStatusCode(), request, response.ReasonPhrase);
                        error = new HttpResponseException(status);

                        RespondWithResult(fullBody, error, response);
                    }
                    else
                    {
                        Log.D(Tag, "Processing response: {0}", response);
                        var entity            = response.Content;
                        var contentTypeHeader = entity.Headers.ContentType;
                        Stream inputStream    = null;
                        if (contentTypeHeader != null && contentTypeHeader.ToString().Contains("multipart/"))
                        {
                            Log.V(Tag, "contentTypeHeader = {0}", contentTypeHeader.ToString());
                            try
                            {
                                _topReader       = new MultipartReader(contentTypeHeader.ToString(), this);
                                inputStream      = entity.ReadAsStreamAsync().Result;
                                const int bufLen = 1024;
                                var buffer       = new byte[bufLen];
                                var numBytesRead = 0;
                                while ((numBytesRead = inputStream.Read(buffer, 0, bufLen)) > 0)
                                {
                                    if (numBytesRead != bufLen)
                                    {
                                        var bufferToAppend = new Couchbase.Lite.Util.ArraySegment <byte>(buffer, 0, numBytesRead).ToArray();
                                        _topReader.AppendData(bufferToAppend);
                                    }
                                    else
                                    {
                                        _topReader.AppendData(buffer);
                                    }
                                }
                                _topReader.Finished();
                                RespondWithResult(fullBody, error, response);
                            }
                            finally
                            {
                                try
                                {
                                    inputStream.Close();
                                }
                                catch (IOException)
                                {
                                }
                            }
                        }
                        else
                        {
                            Log.V(Tag, "contentTypeHeader is not multipart = {0}", contentTypeHeader.ToString());
                            if (entity != null)
                            {
                                try
                                {
                                    inputStream = entity.ReadAsStreamAsync().Result;
                                    fullBody    = Manager.GetObjectMapper().ReadValue <object>(inputStream);
                                    RespondWithResult(fullBody, error, response);
                                }
                                finally
                                {
                                    try
                                    {
                                        inputStream.Close();
                                    }
                                    catch (IOException)
                                    {
                                    }
                                }
                            }
                        }
                    }
                }
                catch (AggregateException e)
                {
                    var err = e.InnerException;
                    Log.E(Tag, "Unhandled Exception", err);
                    error = err;
                    RespondWithResult(fullBody, err, response);
                }
                catch (IOException e)
                {
                    Log.E(Tag, "IO Exception", e);
                    error = e;
                    RespondWithResult(fullBody, e, response);
                }
                catch (Exception e)
                {
                    Log.E(Tag, "ExecuteRequest Exception: ", e);
                    error = e;
                    RespondWithResult(fullBody, e, response);
                }
                finally {
                    response.Dispose();
                }
            });

            return(retVal);
        }