// non-javadoc, see interface HttpResponse
 public virtual void SetStatusLine(StatusLine statusline)
 {
     this.statusline   = Args.NotNull(statusline, "Status line");
     this.ver          = statusline.GetProtocolVersion();
     this.code         = statusline.GetStatusCode();
     this.reasonPhrase = statusline.GetReasonPhrase();
 }
 /// <summary>Creates a response from a status line.</summary>
 /// <remarks>
 /// Creates a response from a status line.
 /// The response will not have a reason phrase catalog and
 /// use the system default locale.
 /// </remarks>
 /// <param name="statusline">the status line</param>
 public BasicHttpResponse(StatusLine statusline) : base()
 {
     this.statusline    = Args.NotNull(statusline, "Status line");
     this.ver           = statusline.GetProtocolVersion();
     this.code          = statusline.GetStatusCode();
     this.reasonPhrase  = statusline.GetReasonPhrase();
     this.reasonCatalog = null;
     this.locale        = null;
 }
 /// <summary>Creates a new response.</summary>
 /// <remarks>
 /// Creates a new response.
 /// This is the constructor to which all others map.
 /// </remarks>
 /// <param name="statusline">the status line</param>
 /// <param name="catalog">
 /// the reason phrase catalog, or
 /// <code>null</code> to disable automatic
 /// reason phrase lookup
 /// </param>
 /// <param name="locale">
 /// the locale for looking up reason phrases, or
 /// <code>null</code> for the system locale
 /// </param>
 public BasicHttpResponse(StatusLine statusline, ReasonPhraseCatalog catalog, CultureInfo
                          locale) : base()
 {
     this.statusline    = Args.NotNull(statusline, "Status line");
     this.ver           = statusline.GetProtocolVersion();
     this.code          = statusline.GetStatusCode();
     this.reasonPhrase  = statusline.GetReasonPhrase();
     this.reasonCatalog = catalog;
     this.locale        = locale;
 }
示例#4
0
        /// <summary>
        /// Returns the response body as a String if the response was successful (a
        /// 2xx status code).
        /// </summary>
        /// <remarks>
        /// Returns the response body as a String if the response was successful (a
        /// 2xx status code). If no response body exists, this returns null. If the
        /// response was unsuccessful (&gt;= 300 status code), throws an
        /// <see cref="Apache.Http.Client.HttpResponseException">Apache.Http.Client.HttpResponseException
        ///     </see>
        /// .
        /// </remarks>
        /// <exception cref="Apache.Http.Client.HttpResponseException"></exception>
        /// <exception cref="System.IO.IOException"></exception>
        public virtual string HandleResponse(HttpResponse response)
        {
            StatusLine statusLine = response.GetStatusLine();
            HttpEntity entity     = response.GetEntity();

            if (statusLine.GetStatusCode() >= 300)
            {
                EntityUtils.Consume(entity);
                throw new HttpResponseException(statusLine.GetStatusCode(), statusLine.GetReasonPhrase
                                                    ());
            }
            return(entity == null ? null : EntityUtils.ToString(entity));
        }
        /// <summary>Actually formats a status line.</summary>
        /// <remarks>
        /// Actually formats a status line.
        /// Called from
        /// <see cref="FormatStatusLine(Org.Apache.Http.StatusLine, LineFormatter)">FormatStatusLine(Org.Apache.Http.StatusLine, LineFormatter)
        ///     </see>
        /// .
        /// </remarks>
        /// <param name="buffer">
        /// the empty buffer into which to format,
        /// never <code>null</code>
        /// </param>
        /// <param name="statline">the status line to format, never <code>null</code></param>
        protected internal virtual void DoFormatStatusLine(CharArrayBuffer buffer, StatusLine
                                                           statline)
        {
            int len = EstimateProtocolVersionLen(statline.GetProtocolVersion()) + 1 + 3 + 1;
            // room for "HTTP/1.1 200 "
            string reason = statline.GetReasonPhrase();

            if (reason != null)
            {
                len += reason.Length;
            }
            buffer.EnsureCapacity(len);
            AppendProtocolVersion(buffer, statline.GetProtocolVersion());
            buffer.Append(' ');
            buffer.Append(Sharpen.Extensions.ToString(statline.GetStatusCode()));
            buffer.Append(' ');
            // keep whitespace even if reason phrase is empty
            if (reason != null)
            {
                buffer.Append(reason);
            }
        }
            public override void Run()
            {
                HttpClient   httpclient = new DefaultHttpClient();
                HttpResponse response;
                string       responseString = null;

                try
                {
                    response = httpclient.Execute(new HttpGet(pathToDoc.ToExternalForm()));
                    StatusLine statusLine = response.GetStatusLine();
                    NUnit.Framework.Assert.IsTrue(statusLine.GetStatusCode() == HttpStatus.ScOk);
                    if (statusLine.GetStatusCode() == HttpStatus.ScOk)
                    {
                        ByteArrayOutputStream @out = new ByteArrayOutputStream();
                        response.GetEntity().WriteTo(@out);
                        @out.Close();
                        responseString = @out.ToString();
                        NUnit.Framework.Assert.IsTrue(responseString.Contains(doc1Id));
                        Log.D(ReplicationTest.Tag, "result: " + responseString);
                    }
                    else
                    {
                        response.GetEntity().GetContent().Close();
                        throw new IOException(statusLine.GetReasonPhrase());
                    }
                }
                catch (ClientProtocolException e)
                {
                    NUnit.Framework.Assert.IsNull("Got ClientProtocolException: " + e.GetLocalizedMessage
                                                      (), e);
                }
                catch (IOException e)
                {
                    NUnit.Framework.Assert.IsNull("Got IOException: " + e.GetLocalizedMessage(), e);
                }
                httpRequestDoneSignal.CountDown();
            }
示例#7
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);
            }
        }
        protected internal override void ExecuteRequest(HttpClient httpClient, HttpRequestMessage
                                                        request)
        {
            object    fullBody = null;
            Exception error    = null;

            try
            {
                HttpResponse response = httpClient.Execute(request);
                try
                {
                    // add in cookies to global store
                    if (httpClient is DefaultHttpClient)
                    {
                        DefaultHttpClient defaultHttpClient = (DefaultHttpClient)httpClient;
                        CouchbaseLiteHttpClientFactory.Instance.AddCookies(defaultHttpClient.GetCookieStore
                                                                               ().GetCookies());
                    }
                }
                catch (Exception e)
                {
                    Log.E(Database.Tag, "Unable to add in cookies to global store", e);
                }
                StatusLine status = response.GetStatusLine();
                if (status.GetStatusCode() >= 300)
                {
                    Log.E(Database.Tag, "Got error " + Sharpen.Extensions.ToString(status.GetStatusCode
                                                                                       ()));
                    Log.E(Database.Tag, "Request was for: " + request.ToString());
                    Log.E(Database.Tag, "Status reason: " + 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/related"
                                                                                           ))
                    {
                        try
                        {
                            MultipartDocumentReader reader = new MultipartDocumentReader(response, db);
                            reader.SetContentType(contentTypeHeader.GetValue());
                            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);
                                    reader.AppendData(bufferToAppend);
                                }
                                else
                                {
                                    reader.AppendData(buffer);
                                }
                            }
                            reader.Finish();
                            fullBody = reader.GetDocumentProperties();
                            RespondWithResult(fullBody, error);
                        }
                        finally
                        {
                            try
                            {
                                inputStream.Close();
                            }
                            catch (IOException)
                            {
                            }
                        }
                    }
                    else
                    {
                        if (entity != null)
                        {
                            try
                            {
                                inputStream = entity.GetContent();
                                fullBody    = Manager.GetObjectMapper().ReadValue <object>(inputStream);
                                RespondWithResult(fullBody, error);
                            }
                            finally
                            {
                                try
                                {
                                    inputStream.Close();
                                }
                                catch (IOException)
                                {
                                }
                            }
                        }
                    }
                }
            }
            catch (ClientProtocolException e)
            {
                Log.E(Database.Tag, "client protocol exception", e);
                error = e;
            }
            catch (IOException e)
            {
                Log.E(Database.Tag, "io exception", e);
                error = e;
            }
        }
示例#9
0
        public virtual void Run()
        {
            running = true;
            HttpClient httpClient;

            if (client == null)
            {
                // This is a race condition that can be reproduced by calling cbpuller.start() and cbpuller.stop()
                // directly afterwards.  What happens is that by the time the Changetracker thread fires up,
                // the cbpuller has already set this.client to null.  See issue #109
                Log.W(Log.TagChangeTracker, "%s: ChangeTracker run() loop aborting because client == null"
                      , this);
                return;
            }
            if (mode == ChangeTracker.ChangeTrackerMode.Continuous)
            {
                // there is a failing unit test for this, and from looking at the code the Replication
                // object will never use Continuous mode anyway.  Explicitly prevent its use until
                // it is demonstrated to actually work.
                throw new RuntimeException("ChangeTracker does not correctly support continuous mode"
                                           );
            }
            httpClient = client.GetHttpClient();
            backoff    = new ChangeTrackerBackoff();
            while (running)
            {
                Uri url = GetChangesFeedURL();
                if (usePOST)
                {
                    HttpPost postRequest = new HttpPost(url.ToString());
                    postRequest.SetHeader("Content-Type", "application/json");
                    StringEntity entity;
                    try
                    {
                        entity = new StringEntity(ChangesFeedPOSTBody());
                    }
                    catch (UnsupportedEncodingException e)
                    {
                        throw new RuntimeException(e);
                    }
                    postRequest.SetEntity(entity);
                    request = postRequest;
                }
                else
                {
                    request = new HttpGet(url.ToString());
                }
                AddRequestHeaders(request);
                // Perform BASIC Authentication if needed
                bool isUrlBasedUserInfo = false;
                // If the URL contains user info AND if this a DefaultHttpClient then preemptively set the auth credentials
                string userInfo = url.GetUserInfo();
                if (userInfo != null)
                {
                    isUrlBasedUserInfo = true;
                }
                else
                {
                    if (authenticator != null)
                    {
                        AuthenticatorImpl auth = (AuthenticatorImpl)authenticator;
                        userInfo = auth.AuthUserInfo();
                    }
                }
                if (userInfo != null)
                {
                    if (userInfo.Contains(":") && !userInfo.Trim().Equals(":"))
                    {
                        string[] userInfoElements = userInfo.Split(":");
                        string   username         = isUrlBasedUserInfo ? URIUtils.Decode(userInfoElements[0]) : userInfoElements
                                                    [0];
                        string password = isUrlBasedUserInfo ? URIUtils.Decode(userInfoElements[1]) : userInfoElements
                                          [1];
                        Credentials credentials = new UsernamePasswordCredentials(username, password);
                        if (httpClient is DefaultHttpClient)
                        {
                            DefaultHttpClient        dhc            = (DefaultHttpClient)httpClient;
                            MessageProcessingHandler preemptiveAuth = new _MessageProcessingHandler_285(credentials
                                                                                                        );
                            dhc.AddRequestInterceptor(preemptiveAuth, 0);
                        }
                    }
                    else
                    {
                        Log.W(Log.TagChangeTracker, "RemoteRequest Unable to parse user info, not setting credentials"
                              );
                    }
                }
                try
                {
                    string maskedRemoteWithoutCredentials = GetChangesFeedURL().ToString();
                    maskedRemoteWithoutCredentials = maskedRemoteWithoutCredentials.ReplaceAll("://.*:.*@"
                                                                                               , "://---:---@");
                    Log.V(Log.TagChangeTracker, "%s: Making request to %s", this, maskedRemoteWithoutCredentials
                          );
                    HttpResponse response = httpClient.Execute(request);
                    StatusLine   status   = response.GetStatusLine();
                    if (status.GetStatusCode() >= 300 && !Utils.IsTransientError(status))
                    {
                        Log.E(Log.TagChangeTracker, "%s: Change tracker got error %d", this, status.GetStatusCode
                                  ());
                        this.error = new HttpResponseException(status.GetStatusCode(), status.GetReasonPhrase
                                                                   ());
                        Stop();
                    }
                    HttpEntity  entity = response.GetEntity();
                    InputStream input  = null;
                    if (entity != null)
                    {
                        try
                        {
                            input = entity.GetContent();
                            if (mode == ChangeTracker.ChangeTrackerMode.LongPoll)
                            {
                                // continuous replications
                                IDictionary <string, object> fullBody = Manager.GetObjectMapper().ReadValue <IDictionary
                                                                                                             >(input);
                                bool responseOK = ReceivedPollResponse(fullBody);
                                if (mode == ChangeTracker.ChangeTrackerMode.LongPoll && responseOK)
                                {
                                    Log.V(Log.TagChangeTracker, "%s: Starting new longpoll", this);
                                    backoff.ResetBackoff();
                                    continue;
                                }
                                else
                                {
                                    Log.W(Log.TagChangeTracker, "%s: Change tracker calling stop (LongPoll)", this);
                                    Stop();
                                }
                            }
                            else
                            {
                                // one-shot replications
                                JsonFactory jsonFactory = Manager.GetObjectMapper().GetJsonFactory();
                                JsonParser  jp          = jsonFactory.CreateJsonParser(input);
                                while (jp.NextToken() != JsonToken.StartArray)
                                {
                                }
                                // ignore these tokens
                                while (jp.NextToken() == JsonToken.StartObject)
                                {
                                    IDictionary <string, object> change = (IDictionary)Manager.GetObjectMapper().ReadValue
                                                                          <IDictionary>(jp);
                                    if (!ReceivedChange(change))
                                    {
                                        Log.W(Log.TagChangeTracker, "Received unparseable change line from server: %s", change
                                              );
                                    }
                                }
                                Log.W(Log.TagChangeTracker, "%s: Change tracker calling stop (OneShot)", this);
                                Stop();
                                break;
                            }
                            backoff.ResetBackoff();
                        }
                        finally
                        {
                            try
                            {
                                entity.ConsumeContent();
                            }
                            catch (IOException)
                            {
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    if (!running && e is IOException)
                    {
                    }
                    else
                    {
                        // in this case, just silently absorb the exception because it
                        // frequently happens when we're shutting down and have to
                        // close the socket underneath our read.
                        Log.E(Log.TagChangeTracker, this + ": Exception in change tracker", e);
                    }
                    backoff.SleepAppropriateAmountOfTime();
                }
            }
            Log.V(Log.TagChangeTracker, "%s: Change tracker run loop exiting", this);
        }
        protected internal virtual void ExecuteRequest(HttpClient httpClient, HttpRequestMessage
                                                       request)
        {
            object    fullBody = null;
            Exception error    = null;

            try
            {
                HttpResponse response = httpClient.Execute(request);
                // add in cookies to global store
                try
                {
                    if (httpClient is DefaultHttpClient)
                    {
                        DefaultHttpClient defaultHttpClient = (DefaultHttpClient)httpClient;
                        CouchbaseLiteHttpClientFactory.Instance.AddCookies(defaultHttpClient.GetCookieStore
                                                                               ().GetCookies());
                    }
                }
                catch (Exception e)
                {
                    Log.E(Database.Tag, "Unable to add in cookies to global store", e);
                }
                StatusLine status = response.GetStatusLine();
                if (status.GetStatusCode() >= 300)
                {
                    Log.E(Database.Tag, "Got error " + Sharpen.Extensions.ToString(status.GetStatusCode
                                                                                       ()));
                    Log.E(Database.Tag, "Request was for: " + request.ToString());
                    Log.E(Database.Tag, "Status reason: " + status.GetReasonPhrase());
                    error = new HttpResponseException(status.GetStatusCode(), status.GetReasonPhrase(
                                                          ));
                }
                else
                {
                    HttpEntity temp = response.GetEntity();
                    if (temp != null)
                    {
                        InputStream stream = null;
                        try
                        {
                            stream   = temp.GetContent();
                            fullBody = Manager.GetObjectMapper().ReadValue <object>(stream);
                        }
                        finally
                        {
                            try
                            {
                                stream.Close();
                            }
                            catch (IOException)
                            {
                            }
                        }
                    }
                }
            }
            catch (ClientProtocolException e)
            {
                Log.E(Database.Tag, "client protocol exception", e);
                error = e;
            }
            catch (IOException e)
            {
                Log.E(Database.Tag, "io exception", e);
                error = e;
            }
            RespondWithResult(fullBody, error);
        }
示例#11
0
        protected internal virtual void ExecuteRequest(HttpClient httpClient, HttpRequestMessage
                                                       request)
        {
            object       fullBody = null;
            Exception    error    = null;
            HttpResponse response = null;

            try
            {
                Log.V(Log.TagSync, "%s: RemoteRequest executeRequest() called, url: %s", this, url
                      );
                if (request.IsAborted())
                {
                    Log.V(Log.TagSync, "%s: RemoteRequest has already been aborted", this);
                    RespondWithResult(fullBody, new Exception(string.Format("%s: Request %s has been aborted"
                                                                            , this, request)), response);
                    return;
                }
                Log.V(Log.TagSync, "%s: RemoteRequest calling httpClient.execute", this);
                response = httpClient.Execute(request);
                Log.V(Log.TagSync, "%s: RemoteRequest called httpClient.execute", this);
                // add in cookies to global store
                try
                {
                    if (httpClient is DefaultHttpClient)
                    {
                        DefaultHttpClient defaultHttpClient = (DefaultHttpClient)httpClient;
                        this.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 (Utils.IsTransientError(status) && RetryRequest())
                {
                    return;
                }
                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 temp = response.GetEntity();
                    if (temp != null)
                    {
                        InputStream stream = null;
                        try
                        {
                            stream   = temp.GetContent();
                            fullBody = Manager.GetObjectMapper().ReadValue <object>(stream);
                        }
                        finally
                        {
                            try
                            {
                                stream.Close();
                            }
                            catch (IOException)
                            {
                            }
                        }
                    }
                }
            }
            catch (IOException e)
            {
                Log.E(Log.TagRemoteRequest, "io exception", e);
                error = e;
                // Treat all IOExceptions as transient, per:
                // http://hc.apache.org/httpclient-3.x/exception-handling.html
                Log.V(Log.TagSync, "%s: RemoteRequest calling retryRequest()", this);
                if (RetryRequest())
                {
                    return;
                }
            }
            catch (Exception e)
            {
                Log.E(Log.TagRemoteRequest, "%s: executeRequest() Exception: ", e, this);
                error = e;
            }
            Log.V(Log.TagSync, "%s: RemoteRequest calling respondWithResult.  error: %s", this
                  , error);
            RespondWithResult(fullBody, error, response);
        }