Esempio n. 1
0
        public RiakBucketProperties(RiakRestResponse response)
        {
            System.Diagnostics.Debug.Assert(response.ContentType == RiakConstants.ContentTypes.ApplicationJson);

            var json  = JObject.Parse(response.Body);
            var props = (JObject)json["props"];

            NVal          = props.Value <uint?>("n_val");
            AllowMultiple = props.Value <bool?>("allow_mult");
            LastWriteWins = props.Value <bool?>("last_write_wins");
            Backend       = props.Value <string>("backend");
            NotFoundOk    = props.Value <bool?>("notfound_ok");
            BasicQuorum   = props.Value <bool?>("basic_quorum");

            ReadQuorum(props, "r", v => RVal   = v);
            ReadQuorum(props, "rw", v => RwVal = v);
            ReadQuorum(props, "dw", v => DwVal = v);
            ReadQuorum(props, "w", v => WVal   = v);
            ReadQuorum(props, "pr", v => PrVal = v);
            ReadQuorum(props, "pw", v => PwVal = v);

            var preCommitHooks = props.Value <JArray>("precommit");

            if (preCommitHooks.Count > 0)
            {
                PreCommitHooks = preCommitHooks.Cast <JObject>().Select(LoadPreCommitHook).ToList();
            }

            var postCommitHooks = props.Value <JArray>("postcommit");

            if (postCommitHooks.Count > 0)
            {
                PostCommitHooks = postCommitHooks.Cast <JObject>().Select(LoadPostCommitHook).ToList();
            }
        }
        public RiakResult <RiakRestResponse> RestRequest(RiakRestRequest request)
        {
            var baseUri = new StringBuilder(_restRootUrl).Append(request.Uri);

            if (request.QueryParams.Count > 0)
            {
                baseUri.Append("?");
                var first = request.QueryParams.First();
                baseUri.Append(first.Key.UrlEncoded()).Append("=").Append(first.Value.UrlEncoded());
                request.QueryParams.Skip(1).ForEach(kv => baseUri.Append("&").Append(kv.Key.UrlEncoded()).Append("=").Append(kv.Value.UrlEncoded()));
            }
            var targetUri = new Uri(baseUri.ToString());

            var req = (HttpWebRequest)WebRequest.Create(targetUri);

            req.KeepAlive   = true;
            req.Method      = request.Method;
            req.Credentials = CredentialCache.DefaultCredentials;

            if (!string.IsNullOrWhiteSpace(request.ContentType))
            {
                req.ContentType = request.ContentType;
            }

            if (!request.Cache)
            {
                req.Headers.Set(RiakConstants.Rest.HttpHeaders.DisableCacheKey, RiakConstants.Rest.HttpHeaders.DisableCacheValue);
            }

            request.Headers.ForEach(h => req.Headers.Set(h.Key, h.Value));

            if (request.Body != null && request.Body.Length > 0)
            {
                req.ContentLength = request.Body.Length;
                using (var writer = req.GetRequestStream())
                {
                    writer.Write(request.Body, 0, request.Body.Length);
                }
            }
            else
            {
                req.ContentLength = 0;
            }

            try
            {
                var response = (HttpWebResponse)req.GetResponse();

                var result = new RiakRestResponse
                {
                    ContentLength   = response.ContentLength,
                    ContentType     = response.ContentType,
                    StatusCode      = response.StatusCode,
                    Headers         = response.Headers.AllKeys.ToDictionary(k => k, k => response.Headers[k]),
                    ContentEncoding = !string.IsNullOrWhiteSpace(response.ContentEncoding)
                        ? Encoding.GetEncoding(response.ContentEncoding)
                        : Encoding.Default
                };

                if (response.ContentLength > 0)
                {
                    using (var responseStream = response.GetResponseStream())
                    {
                        if (responseStream != null)
                        {
                            using (var reader = new StreamReader(responseStream, result.ContentEncoding))
                            {
                                result.Body = reader.ReadToEnd();
                            }
                        }
                    }
                }

                return(RiakResult <RiakRestResponse> .Success(result));
            }
            catch (RiakException ex)
            {
                return(RiakResult <RiakRestResponse> .Error(ResultCode.CommunicationError, ex.Message, ex.NodeOffline));
            }
            catch (WebException ex)
            {
                if (ex.Status == WebExceptionStatus.ProtocolError)
                {
                    return(RiakResult <RiakRestResponse> .Error(ResultCode.HttpError, ex.Message, false));
                }

                return(RiakResult <RiakRestResponse> .Error(ResultCode.HttpError, ex.Message, true));
            }
            catch (Exception ex)
            {
                return(RiakResult <RiakRestResponse> .Error(ResultCode.CommunicationError, ex.Message, true));
            }
        }
Esempio n. 3
0
        public Task <RiakResult <RiakRestResponse> > RestRequest(RiakRestRequest request)
        {
            var baseUri = new StringBuilder(_restRootUrl).Append(request.Uri);

            if (request.QueryParams.Count > 0)
            {
                baseUri.Append("?");
                var first = request.QueryParams.First();
                baseUri.Append(first.Key.UrlEncoded()).Append("=").Append(first.Value.UrlEncoded());
                request.QueryParams.Skip(1).ForEach(kv => baseUri.Append("&").Append(kv.Key.UrlEncoded()).Append("=").Append(kv.Value.UrlEncoded()));
            }
            var targetUri = new Uri(baseUri.ToString());

            var req = (HttpWebRequest)WebRequest.Create(targetUri);

            req.KeepAlive   = true;
            req.Method      = request.Method;
            req.Credentials = CredentialCache.DefaultCredentials;

            if (!string.IsNullOrWhiteSpace(request.ContentType))
            {
                req.ContentType = request.ContentType;
            }

            if (!request.Cache)
            {
                req.Headers.Set(RiakConstants.Rest.HttpHeaders.DisableCacheKey, RiakConstants.Rest.HttpHeaders.DisableCacheValue);
            }

            request.Headers.ForEach(h => req.Headers.Set(h.Key, h.Value));

            if (request.Body != null && request.Body.Length > 0)
            {
                req.ContentLength = request.Body.Length;
                using (var writer = req.GetRequestStream())
                {
                    writer.Write(request.Body, 0, request.Body.Length);
                }
            }
            else
            {
                req.ContentLength = 0;
            }

            // process response
            var asyncResult = req.BeginGetResponse(null, null);

            return(Task <WebResponse> .Factory.FromAsync(asyncResult, req.EndGetResponse)
                   .ContinueWith((Task <WebResponse> responseTask) => {
                // rethrow exception on fault
                if (responseTask.IsFaulted)
                {
                    throw responseTask.Exception;
                }

                // pull out response
                var response = (HttpWebResponse)responseTask.Result;
                var result = new RiakRestResponse()
                {
                    ContentLength = response.ContentLength,
                    ContentType = response.ContentType,
                    StatusCode = response.StatusCode,
                    Headers = response.Headers.AllKeys.ToDictionary(k => k, k => response.Headers[k]),
                    ContentEncoding = !string.IsNullOrWhiteSpace(response.ContentEncoding)
                            ? Encoding.GetEncoding(response.ContentEncoding)
                            : Encoding.Default
                };

                if (response.ContentLength > 0)
                {
                    using (var responseStream = response.GetResponseStream())
                    {
                        if (responseStream != null)
                        {
                            return ReadStreamAsync(responseStream, (int)response.ContentLength)
                            .ContinueWith((Task <byte[]> readTask) => {
                                result.Body = result.ContentEncoding.GetString(readTask.Result);
                                return result;
                            });
                        }
                    }
                }

                // end of the line
                throw new RiakException("Couldn't read HTTP response", false);
            }).Unwrap()
                   .ContinueWith((Task <RiakRestResponse> responseTask) => {
                if (!responseTask.IsFaulted)
                {
                    return RiakResult <RiakRestResponse> .Success(responseTask.Result);
                }
                else
                {
                    var exceptions = responseTask.Exception.Flatten().InnerExceptions;
                    var rEx = exceptions.OfType <RiakException>().FirstOrDefault();
                    var wEx = exceptions.OfType <WebException>().FirstOrDefault();

                    // process exceptions
                    if (rEx != null)
                    {
                        return RiakResult <RiakRestResponse> .Error(ResultCode.CommunicationError, rEx.Message, rEx.NodeOffline);
                    }
                    else if (wEx != null)
                    {
                        if (wEx.Status == WebExceptionStatus.ProtocolError)
                        {
                            return RiakResult <RiakRestResponse> .Error(ResultCode.HttpError, wEx.Message, false);
                        }

                        return RiakResult <RiakRestResponse> .Error(ResultCode.HttpError, wEx.Message, true);
                    }
                    else
                    {
                        var ex = exceptions.FirstOrDefault();
                        return RiakResult <RiakRestResponse> .Error(ResultCode.CommunicationError, ex.Message, true);
                    }
                }
            }));
        }
Esempio n. 4
0
        public Task <RiakRestResponse> RestRequest(IRiakEndPoint endPoint, RiakRestRequest request)
        {
            return(endPoint.GetSingleResultViaRest(async serverUrl =>
            {
                var baseUri = new StringBuilder(serverUrl).Append(request.Uri);
                if (request.QueryParams.Count > 0)
                {
                    baseUri.Append("?");
                    var first = request.QueryParams.First();
                    baseUri.Append(first.Key.UrlEncoded()).Append("=").Append(first.Value.UrlEncoded());
                    request.QueryParams.Skip(1)
                    .ForEach(
                        kv =>
                        baseUri.Append("&")
                        .Append(kv.Key.UrlEncoded())
                        .Append("=")
                        .Append(kv.Value.UrlEncoded()));
                }
                var targetUri = new Uri(baseUri.ToString());

                var req = (HttpWebRequest)WebRequest.Create(targetUri);
                req.KeepAlive = true;
                req.Method = request.Method;
                req.Credentials = CredentialCache.DefaultCredentials;

                if (!string.IsNullOrWhiteSpace(request.ContentType))
                {
                    req.ContentType = request.ContentType;
                }

                if (!request.Cache)
                {
                    req.Headers.Set(RiakConstants.Rest.HttpHeaders.DisableCacheKey,
                                    RiakConstants.Rest.HttpHeaders.DisableCacheValue);
                }

                request.Headers.ForEach(h => req.Headers.Set(h.Key, h.Value));

                if (request.Body != null && request.Body.Length > 0)
                {
                    req.ContentLength = request.Body.Length;

                    var writer = await req.GetRequestStreamAsync().ConfigureAwait(false);
                    writer.Write(request.Body, 0, request.Body.Length);
                }
                else
                {
                    req.ContentLength = 0;
                }

                try
                {
                    var response = (HttpWebResponse)await req.GetResponseAsync().ConfigureAwait(false);

                    var result = new RiakRestResponse
                    {
                        ContentLength = response.ContentLength,
                        ContentType = response.ContentType,
                        StatusCode = response.StatusCode,
                        Headers = response.Headers.AllKeys.ToDictionary(k => k, k => response.Headers[k]),
                        ContentEncoding = !string.IsNullOrWhiteSpace(response.ContentEncoding)
                            ? Encoding.GetEncoding(response.ContentEncoding)
                            : Encoding.Default
                    };

                    if (response.ContentLength > 0)
                    {
                        using (var responseStream = response.GetResponseStream())
                        {
                            if (responseStream != null)
                            {
                                using (var reader = new StreamReader(responseStream, result.ContentEncoding))
                                {
                                    result.Body = reader.ReadToEnd();
                                }
                            }
                        }
                    }

                    if (result.StatusCode != HttpStatusCode.NoContent)
                    {
                        throw new RiakException((uint)ResultCode.InvalidResponse, "Unexpected Status Code: {0} ({1})".Fmt(result.StatusCode, (int)result.StatusCode), false);
                    }

                    return result;
                }
                catch (RiakException ex)
                {
                    throw;
                }
                catch (WebException ex)
                {
                    if (ex.Status == WebExceptionStatus.ProtocolError)
                    {
                        throw new RiakException((uint)ResultCode.HttpError, ex.Message, false);
                    }

                    throw new RiakException((uint)ResultCode.HttpError, ex.Message, true);
                }
                catch (Exception ex)
                {
                    throw new RiakException((uint)ResultCode.CommunicationError, ex.Message, true);
                }
            }));
        }