Example #1
0
 void GivenAMatching(string baseUri, string template, string candidate)
 {
     ThenTheMatch = new UriTemplate(template).Match(baseUri.ToUri(), candidate.ToUri());
 }
Example #2
0
 private void OnPostPrepare(HttpEntityManager manager, UriTemplateMatch match)
 {
     OnPost(manager, (ElectionMessageDto.PrepareDto dto) => new ElectionMessage.Prepare(dto));
 }
Example #3
0
 private void OnProjectionsPostContinuous(HttpEntityManager http, UriTemplateMatch match)
 {
     ProjectionsPost(http, match, ProjectionMode.Continuous, match.BoundVariables["name"]);
 }
Example #4
0
 private static ProjectionManagementMessage.RunAs GetRunAs(HttpEntityManager http, UriTemplateMatch match)
 {
     return(new ProjectionManagementMessage.RunAs(http.User));
 }
Example #5
0
 private void OnProjectionsGetOneTime(HttpEntityManager http, UriTemplateMatch match)
 {
     ProjectionsGet(http, match, ProjectionMode.OneTime);
 }
Example #6
0
 private void OnProjectionsPostTransient(HttpEntityManager http, UriTemplateMatch match)
 {
     ProjectionsPost(http, match, ProjectionMode.Transient, match.BoundVariables["name"]);
 }
 private void OnProjectionsGetPersistent(HttpEntity http, UriTemplateMatch match)
 {
     ProjectionsGet(http, match, ProjectionMode.Persistent);
 }
Example #8
0
 private void OnProjectionsGetAny(HttpEntityManager http, UriTemplateMatch match)
 {
     ProjectionsGet(http, match, null);
 }
Example #9
0
        /// <summary>
        /// Deserialize the request
        /// </summary>
        public void DeserializeRequest(Message request, object[] parameters)
        {
            try
            {
#if DEBUG
                RemoteEndpointMessageProperty endpoint = (RemoteEndpointMessageProperty)request.Properties[RemoteEndpointMessageProperty.Name];

                this.m_traceSource.TraceEvent(TraceEventType.Information, 0, "Received request from: {0}:{1}", endpoint.Address, endpoint.Port);
#endif

                HttpRequestMessageProperty httpRequest = (HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name];
                string contentType = httpRequest.Headers[HttpRequestHeader.ContentType];

                UriTemplateMatch templateMatch = (UriTemplateMatch)request.Properties.SingleOrDefault(o => o.Value is UriTemplateMatch).Value;
                // Not found
                if (templateMatch == null)
                {
                    throw new WebFaultException(HttpStatusCode.NotFound);
                }

                for (int pNumber = 0; pNumber < parameters.Length; pNumber++)
                {
                    var parm = this.m_operationDescription.Messages[0].Body.Parts[pNumber];

                    // Simple parameter
                    if (templateMatch.BoundVariables.AllKeys.Any(o => o.ToLower() == parm.Name.ToLower()))
                    {
                        var rawData = templateMatch.BoundVariables[parm.Name];
                        parameters[pNumber] = Convert.ChangeType(rawData, parm.Type);
                    }
                    // Use XML Serializer
                    else if (contentType?.StartsWith("application/xml") == true)
                    {
                        var messageFormatProperty     = (WebBodyFormatMessageProperty)request.Properties[WebBodyFormatMessageProperty.Name];
                        XmlDictionaryReader rawReader = request.GetReaderAtBodyContents();

                        switch (messageFormatProperty.Format)
                        {
                        case WebContentFormat.Raw:
                        {
                            rawReader.ReadStartElement("Binary");
                            byte[] rawBody = rawReader.ReadContentAsBase64();

                            using (MemoryStream ms = new MemoryStream(rawBody))
                            {
                                using (XmlReader bodyReader = XmlReader.Create(ms))
                                {
                                    while (bodyReader.NodeType != XmlNodeType.Element)
                                    {
                                        bodyReader.Read();
                                    }

                                    Type eType = s_knownTypes.FirstOrDefault(o => o.GetCustomAttribute <XmlRootAttribute>()?.ElementName == bodyReader.LocalName &&
                                                                             o.GetCustomAttribute <XmlRootAttribute>()?.Namespace == bodyReader.NamespaceURI);
                                    XmlSerializer xsz = s_serializers[eType];
                                    parameters[pNumber] = xsz.Deserialize(bodyReader);
                                }
                            }
                        }

                        break;

                        case WebContentFormat.Xml:
                        {
                            rawReader.MoveToStartElement();
                            using (rawReader)
                            {
                                Type eType = s_knownTypes.FirstOrDefault(o => o.GetCustomAttribute <XmlRootAttribute>()?.ElementName == rawReader.LocalName && o.GetCustomAttribute <XmlRootAttribute>()?.Namespace == rawReader.NamespaceURI);

                                this.m_traceSource.TraceEvent(TraceEventType.Information, 0, "Contract: {0}", typeof(TContract).Name);
                                this.m_traceSource.TraceEvent(TraceEventType.Information, 0, "Attempting to deserialize type: {0}", eType?.Name);

                                XmlSerializer xsz = s_serializers[eType];
                                parameters[pNumber] = xsz.Deserialize(rawReader);
                            }
                        }
                        break;
                        }
                    }
                    // Use JSON Serializer
                    else if (contentType?.StartsWith("application/json") == true)
                    {
                        // Read the binary contents form the WCF pipeline
                        XmlDictionaryReader bodyReader = request.GetReaderAtBodyContents();
                        bodyReader.ReadStartElement("Binary");
                        byte[] rawBody = bodyReader.ReadContentAsBase64();

                        // Now read the JSON data
                        MemoryStream   ms  = new MemoryStream(rawBody);
                        StreamReader   sr  = new StreamReader(ms);
                        JsonSerializer jsz = new JsonSerializer()
                        {
                            Binder = new ModelSerializationBinder(),
                            TypeNameAssemblyFormat = 0,
                            TypeNameHandling       = TypeNameHandling.All
                        };
                        jsz.Converters.Add(new StringEnumConverter());
                        var dserType = parm.Type;
                        parameters[pNumber] = jsz.Deserialize(sr, dserType);
                    }
                    else if (contentType == "application/octet-stream")
                    {
                        XmlDictionaryReader rawReader = request.GetReaderAtBodyContents();
                        rawReader.ReadStartElement("Binary");
                        byte[] rawBody = rawReader.ReadContentAsBase64();

                        MemoryStream ms = new MemoryStream(rawBody);
                        parameters[pNumber] = ms;
                    }
                    else if (contentType != null)// TODO: Binaries
                    {
                        throw new InvalidOperationException("Invalid request format");
                    }
                }
            }
            catch (Exception e)
            {
                this.m_traceSource.TraceEvent(TraceEventType.Error, e.HResult, e.ToString());
                throw;
            }
        }
 private void OnProjectionsGetAdHoc(HttpEntity http, UriTemplateMatch match)
 {
     ProjectionsGet(http, match, ProjectionMode.AdHoc);
 }
Example #11
0
        public Stream RunDEAnalysis(Stream request)
        {
            bool         ok           = true;
            string       errorMessage = null;
            DEAContext   context      = null;
            string       jsonRequest  = null;
            string       jsonResponse = null;
            const string fn           = "RunDEAnalysis";

            LOG.DebugFormat("{0} - started", fn);

            UriTemplateMatch utm = WebOperationContext.Current.IncomingRequest.UriTemplateMatch;

            LOG.Debug(utm.RequestUri.OriginalString);

            try
            {
                using (StreamReader reader = new StreamReader(request))
                {
                    jsonRequest = reader.ReadToEnd();
                }

                LOG.DebugFormat("Request: {0}", jsonRequest);

                context = DEAContext.CreateFromJsonString(jsonRequest, out errorMessage);
                ok      = (context != null);
                if (ok)
                {
                    ok = context.RunDEA(out errorMessage);
                    if (ok && context.ConstraintsSet)
                    {
                        ok = context.ApplyCostConstraintsToProjectSelection(out errorMessage);
                    }
                    if (ok)
                    {
                        jsonResponse = context.ToJsonString(out errorMessage);
                        ok           = (jsonResponse != null);
                    }
                }
            }
            catch (Exception ex)
            {
                ok           = false;
                errorMessage = ex.Message;
            }

            DEAResponse response = new DEAResponse();

            response.OK           = ok;
            response.errorMessage = errorMessage;
            response.context      = context;

            jsonResponse = JsonConvert.SerializeObject(response, Formatting.Indented);

            LOG.DebugFormat("Response: {0}", jsonResponse);
            Stream ms = new MemoryStream(ASCIIEncoding.Default.GetBytes(s: jsonResponse));

            LOG.DebugFormat("{0} - ended", fn);

            return(ms);
        }
Example #12
0
        public bool Parse(Socket socket, out RouteMatch?match, out RouteHandler route)
        {
            positionInTmp = 0;
            Pipeline      = false;
            var methodEnd = ReadUntil(socket, Space, 0);

            if (methodEnd == -1)
            {
                match = null;
                route = null;
                if (!socket.Connected)
                {
                    offsetInOutput = 0;
                    return(false);
                }
                else if (positionInTmp == 0)
                {
                    if (offsetInOutput != 0)
                    {
                        socket.Send(OutputTemp, offsetInOutput, SocketFlags.None);
                        offsetInOutput = 0;
                        socket.Close();
                        return(false);
                    }
                    else
                    {
                        return(ReturnError(socket, 408));
                    }
                }
                else
                {
                    return(ReturnError(socket, 505));
                }
            }
            HttpMethod = ReadMethod(methodEnd, InputTemp);
            var rowEnd = ReadUntil(socket, LF, methodEnd + 1);

            if (rowEnd == -1 || rowEnd < 12)
            {
                match = null;
                route = null;
                return(ReturnError(socket, 505));
            }
            RequestHeadersLength  = 0;
            ResponseHeadersLength = 0;
            HttpProtocolVersion   = ReadProtocol(rowEnd - 2);
            if (HttpProtocolVersion == null)
            {
                match = null;
                route = null;
                ReturnError(socket, 505, "Only HTTP/1.1 and HTTP/1.0 supported (partially)", false);
                return(false);
            }
            match = ReadUrl(rowEnd, out route);
            if (route == null)
            {
                var unknownRoute = "Unknown route " + RawUrl + " on method " + HttpMethod;
                ReturnError(socket, 404, unknownRoute, false);
                return(false);
            }
            ResponseStatus           = HttpStatusCode.OK;
            ResponseLength           = null;
            ResponseContentType      = null;
            TemplateMatch            = null;
            ResponseIsJson           = false;
            ContentTypeResponseIndex = -1;
            do
            {
                var start = rowEnd + 1;
                rowEnd = ReadUntil(socket, CR, start);
                if (rowEnd == start)
                {
                    break;
                }
                else if (rowEnd == -1)
                {
                    return(ReturnError(socket, 414));
                }
                else
                {
                    int i = start;
                    for (; i < rowEnd; i++)
                    {
                        if (InputTemp[i] == ':')
                        {
                            break;
                        }
                    }
                    if (i == rowEnd)
                    {
                        return(ReturnError(socket, 414));
                    }
                    var nameBuf = TmpCharBuf;
                    for (int x = start; x < i; x++)
                    {
                        nameBuf[x - start] = Lower[InputTemp[x]];
                    }
                    var name = KeyCache.Get(nameBuf, i - start);
                    if (InputTemp[i + 1] == 32)
                    {
                        i++;
                    }
                    for (int x = i + 1; x < rowEnd; x++)
                    {
                        nameBuf[x - i - 1] = (char)InputTemp[x];
                    }
                    var value = ValueCache.Get(nameBuf, rowEnd - i - 1);
                    if (RequestHeadersLength == RequestHeaders.Length)
                    {
                        var newHeaders = new HeaderPair[RequestHeaders.Length * 2];
                        Array.Copy(RequestHeaders, newHeaders, RequestHeaders.Length);
                        RequestHeaders = newHeaders;
                    }
                    RequestHeaders[RequestHeadersLength++] = new HeaderPair(name, value);
                }
                rowEnd++;
            } while (positionInTmp <= InputTemp.Length);
            rowEnd += 2;
            if (HttpMethod == "POST" || HttpMethod == "PUT")
            {
                int len = 0;
                var ct  = GetRequestHeader("content-length");
                if (ct != null)
                {
                    if (!int.TryParse(ct, out len))
                    {
                        return(ReturnError(socket, 411));
                    }
                    if (len > Limit)
                    {
                        return(ReturnError(socket, 413));
                    }
                }
                else
                {
                    return(ReturnError(socket, 411));
                }
                InputStream.Reset();
                var size = totalBytes - rowEnd;
                InputStream.Write(InputTemp, rowEnd, size);
                len -= size;
                var oldTimeout = socket.ReceiveTimeout;
                socket.ReceiveTimeout = 10000;
                while (len > 0)
                {
                    size = socket.Receive(InputTemp, Math.Min(len, InputTemp.Length), SocketFlags.None);
                    if (size < 1)
                    {
                        return(ReturnError(socket, 408));
                    }
                    InputStream.Write(InputTemp, 0, size);
                    len -= size;
                }
                socket.ReceiveTimeout = oldTimeout;
                InputStream.Position  = 0;
                rowEnd     = totalBytes;
                totalBytes = 0;
            }
            else
            {
                Pipeline = rowEnd < totalBytes;
                if (Pipeline)
                {
                    Buffer.BlockCopy(InputTemp, rowEnd, InputTemp, 0, totalBytes - rowEnd);
                    totalBytes -= rowEnd;
                }
                else
                {
                    totalBytes = 0;
                }
            }
            return(true);
        }
Example #13
0
        private ServerResponse DispatchRequest(Uri resourcePath, string httpMethod, string requestBody)
        {
            HttpStatusCode codeToReturn    = HttpStatusCode.OK;
            Response       commandResponse = new Response();
            Dictionary <string, string> locatorParameters = new Dictionary <string, string>();
            UriTemplateTable            templateTable     = this.FindDispatcherTable(httpMethod);
            UriTemplateMatch            match             = templateTable.MatchSingle(resourcePath);

            if (resourcePath.AbsolutePath.ToUpperInvariant().Contains(ShutdownUrlFragment))
            {
                this.serverLogger.Log("Executing: [Shutdown] at URL: " + resourcePath.AbsolutePath);
            }
            else if (match == null)
            {
                codeToReturn          = HttpStatusCode.NotFound;
                commandResponse.Value = "No command associated with " + resourcePath.AbsolutePath;
            }
            else
            {
                string    relativeUrl    = match.RequestUri.AbsoluteUri.Substring(match.RequestUri.AbsoluteUri.IndexOf(this.listenerPath, StringComparison.OrdinalIgnoreCase) + this.listenerPath.Length - 1);
                SessionId sessionIdValue = null;

                string commandName = (string)match.Data;
                foreach (string key in match.BoundVariables.Keys)
                {
                    string value = match.BoundVariables[key];
                    locatorParameters.Add(key, value);
                }

                Command commandToExecute = new Command(commandName, requestBody);

                object          resultValue = null;
                WebDriverResult resultCode  = WebDriverResult.Success;
                try
                {
                    CommandHandler handler = this.handlerFactory.CreateHandler(commandToExecute.Name, locatorParameters, commandToExecute.Parameters);
                    sessionIdValue = handler.SessionId;
                    this.serverLogger.Log("Executing: " + handler.ToString() + " at URL: " + relativeUrl);
                    resultValue  = handler.Execute();
                    codeToReturn = handler.StatusCode;
                }
                catch (CommandNotImplementedException ex)
                {
                    codeToReturn = HttpStatusCode.NotImplemented;
                    resultValue  = ex.Message + " (" + commandName + ")";
                }
                catch (InvalidCommandException ex)
                {
                    codeToReturn = HttpStatusCode.MethodNotAllowed;
                    resultValue  = ex.Message;
                }
                catch (ResourceNotFoundException ex)
                {
                    codeToReturn = HttpStatusCode.NotFound;
                    resultValue  = ex.Message + " (" + resourcePath.AbsolutePath + ")";
                }
                catch (InvalidParameterException ex)
                {
                    codeToReturn = HttpStatusCode.BadRequest;
                    resultValue  = ex.Message;
                }
                catch (NoSuchWindowException ex)
                {
                    resultCode  = WebDriverResult.NoSuchWindow;
                    resultValue = CreateErrorResponse(commandName, ex);
                }
                catch (NoSuchElementException ex)
                {
                    resultCode  = WebDriverResult.NoSuchElement;
                    resultValue = CreateErrorResponse(commandName, ex);
                }
                catch (NoSuchFrameException ex)
                {
                    resultCode  = WebDriverResult.NoSuchFrame;
                    resultValue = CreateErrorResponse(commandName, ex);
                }
                catch (StaleElementReferenceException ex)
                {
                    resultCode  = WebDriverResult.ObsoleteElement;
                    resultValue = CreateErrorResponse(commandName, ex);
                }
                catch (ElementNotVisibleException ex)
                {
                    resultCode  = WebDriverResult.ElementNotDisplayed;
                    resultValue = CreateErrorResponse(commandName, ex);
                }
                catch (InvalidElementStateException ex)
                {
                    resultCode  = WebDriverResult.InvalidElementState;
                    resultValue = CreateErrorResponse(commandName, ex);
                }
                catch (NotImplementedException ex)
                {
                    resultCode  = WebDriverResult.InvalidElementState;
                    resultValue = CreateErrorResponse(commandName, ex);
                }
                catch (XPathLookupException ex)
                {
                    resultCode  = WebDriverResult.XPathLookupError;
                    resultValue = CreateErrorResponse(commandName, ex);
                }
                catch (WebDriverTimeoutException ex)
                {
                    resultCode  = WebDriverResult.Timeout;
                    resultValue = CreateErrorResponse(commandName, ex);
                }
                catch (UnhandledAlertException ex)
                {
                    resultCode = WebDriverResult.UnexpectedAlertOpen;

                    // This is ridiculously ugly. To be refactored.
                    ErrorResponse err = CreateErrorResponse(commandName, ex);
                    Dictionary <string, object> resp = new Dictionary <string, object>();
                    resp["class"]      = err.ClassName;
                    resp["message"]    = err.Message;
                    resp["screen"]     = err.Screenshot;
                    resp["stackTrace"] = err.StackTrace;
                    Dictionary <string, object> alert = new Dictionary <string, object>();
                    alert["text"] = ex.Alert.Text;
                    resp["alert"] = alert;
                    resultValue   = resp;
                }
                catch (Exception ex)
                {
                    resultCode  = WebDriverResult.UnhandledError;
                    resultValue = CreateErrorResponse(commandName, ex);
                }

                commandResponse        = new Response(sessionIdValue);
                commandResponse.Status = resultCode;
                commandResponse.Value  = resultValue;

                this.serverLogger.Log("Done: " + relativeUrl);
            }

            return(new ServerResponse(commandResponse, codeToReturn));
        }
Example #14
0
 private void OnPostMasterIsResigningOk(HttpEntityManager manager, UriTemplateMatch match)
 {
     OnPost(manager, (ElectionMessageDto.MasterIsResigningOkDto dto) => new ElectionMessage.MasterIsResigningOk(dto));
 }
 private void OnProjectionsPostAdHoc(HttpEntity http, UriTemplateMatch match)
 {
     ProjectionsPost(http, match, ProjectionMode.AdHoc, match.BoundVariables["name"]);
 }
Example #16
0
 public void setup()
 {
     _urlTemplate = new UriTemplate("/a/b?c={C}");
     _match       = _urlTemplate.Match(new Uri("http://localhost"), new Uri("http://localhost/a/b"));
 }
 private void OnProjectionsPostPersistent(HttpEntity http, UriTemplateMatch match)
 {
     ProjectionsPost(http, match, ProjectionMode.Persistent, match.BoundVariables["name"]);
 }
Example #18
0
 private void OnProjectionsGetTransient(HttpEntityManager http, UriTemplateMatch match)
 {
     ProjectionsGet(http, match, ProjectionMode.Transient);
 }
 private void OnProjectionStatusGet(HttpEntity http, UriTemplateMatch match)
 {
     http.Manager.Reply(
         HttpStatusCode.NotImplemented, "Not Implemented",
         e => Log.ErrorException(e, "Error while closing http connection (http service core)"));
 }
Example #20
0
 private void OnProjectionsGetContinuous(HttpEntityManager http, UriTemplateMatch match)
 {
     ProjectionsGet(http, match, ProjectionMode.Continuous);
 }
Example #21
0
        /// <inheritdoc/>
        public Task <QueuedMessageList> ListMessagesAsync(QueueName queueName, QueuedMessageListId marker, int?limit, bool echo, bool includeClaimed, CancellationToken cancellationToken)
        {
            if (queueName == null)
            {
                throw new ArgumentNullException("queueName");
            }
            if (limit <= 0)
            {
                throw new ArgumentOutOfRangeException("limit");
            }

            UriTemplate template = new UriTemplate("/queues/{queue_name}/messages?marker={marker}&limit={limit}&echo={echo}&include_claimed={include_claimed}");

            var parameters =
                new Dictionary <string, string>()
            {
                { "queue_name", queueName.Value },
                { "echo", echo.ToString() },
                { "include_claimed", includeClaimed.ToString() }
            };

            if (marker != null)
            {
                parameters["marker"] = marker.Value;
            }
            if (limit != null)
            {
                parameters["limit"] = limit.ToString();
            }

            Func <Task <Tuple <IdentityToken, Uri> >, HttpWebRequest> prepareRequest =
                PrepareRequestAsyncFunc(HttpMethod.GET, template, parameters);

            Func <Task <HttpWebRequest>, Task <ListCloudQueueMessagesResponse> > requestResource =
                GetResponseAsyncFunc <ListCloudQueueMessagesResponse>(cancellationToken);

            Func <Task <ListCloudQueueMessagesResponse>, QueuedMessageList> resultSelector =
                task =>
            {
                ReadOnlyCollection <QueuedMessage> messages = null;
                if (task.Result != null)
                {
                    messages = task.Result.Messages;
                }

                QueuedMessageListId nextMarker = null;
                if (task.Result != null && task.Result.Links != null)
                {
                    Link nextLink = task.Result.Links.FirstOrDefault(i => string.Equals(i.Rel, "next", StringComparison.OrdinalIgnoreCase));
                    if (nextLink != null)
                    {
                        Uri baseUri = new Uri("https://example.com");
                        Uri absoluteUri;
                        if (nextLink.Href.StartsWith("/v1"))
                        {
                            absoluteUri = new Uri(baseUri, nextLink.Href.Substring("/v1".Length));
                        }
                        else
                        {
                            absoluteUri = new Uri(baseUri, nextLink.Href);
                        }

                        UriTemplateMatch match = template.Match(baseUri, absoluteUri);
                        if (!string.IsNullOrEmpty(match.BoundVariables["marker"]))
                        {
                            nextMarker = new QueuedMessageListId(match.BoundVariables["marker"]);
                        }
                    }
                }

                if (messages == null || messages.Count == 0)
                {
                    // use the same marker again
                    messages   = messages ?? new ReadOnlyCollection <QueuedMessage>(new QueuedMessage[0]);
                    nextMarker = marker;
                }

                Func <CancellationToken, Task <ReadOnlyCollectionPage <QueuedMessage> > > getNextPageAsync = null;
                if (nextMarker != null || messages.Count == 0)
                {
                    getNextPageAsync =
                        nextCancellationToken => ListMessagesAsync(queueName, nextMarker, limit, echo, includeClaimed, nextCancellationToken)
                        .Select(t => (ReadOnlyCollectionPage <QueuedMessage>)t.Result);
                }

                return(new QueuedMessageList(messages, getNextPageAsync, nextMarker));
            };

            return(AuthenticateServiceAsync(cancellationToken)
                   .Select(prepareRequest)
                   .Then(requestResource)
                   .Select(resultSelector));
        }
Example #22
0
 private void OnProjectionsPostOneTime(HttpEntityManager http, UriTemplateMatch match)
 {
     ProjectionsPost(http, match, ProjectionMode.OneTime, match.BoundVariables["name"]);
 }
 private void OnPostGossip(HttpEntityManager entity, UriTemplateMatch match)
 {
     entity.ReadTextRequestAsync(OnPostGossipRequestRead, e => Log.Debug("Error while reading request (gossip): {0}", e.Message));
 }
Example #24
0
 private static string MakeUrl(UriTemplateMatch match, string localPath)
 {
     return(new Uri(match.BaseUri, localPath).AbsoluteUri);
 }
Example #25
0
        private void PostSubscription(HttpEntityManager http, UriTemplateMatch match)
        {
            if (_httpForwarder.ForwardRequest(http))
            {
                return;
            }
            var groupname = match.BoundVariables["subscription"];
            var stream    = match.BoundVariables["stream"];
            var envelope  = new SendToHttpEnvelope(
                _networkSendQueue, http,
                (args, message) => http.ResponseCodec.To(message),
                (args, message) =>
            {
                int code;
                var m = message as ClientMessage.UpdatePersistentSubscriptionCompleted;
                if (m == null)
                {
                    throw new Exception("unexpected message " + message);
                }
                switch (m.Result)
                {
                case ClientMessage.UpdatePersistentSubscriptionCompleted.UpdatePersistentSubscriptionResult.Success:
                    code = HttpStatusCode.OK;
                    //TODO competing return uri to subscription
                    break;

                case ClientMessage.UpdatePersistentSubscriptionCompleted.UpdatePersistentSubscriptionResult.DoesNotExist:
                    code = HttpStatusCode.NotFound;
                    break;

                case ClientMessage.UpdatePersistentSubscriptionCompleted.UpdatePersistentSubscriptionResult.AccessDenied:
                    code = HttpStatusCode.Unauthorized;
                    break;

                default:
                    code = HttpStatusCode.InternalServerError;
                    break;
                }
                return(new ResponseConfiguration(code, http.ResponseCodec.ContentType,
                                                 http.ResponseCodec.Encoding, new KeyValuePair <string, string>("location", MakeUrl(http, "/subscriptions/" + stream + "/" + groupname))));
            });

            http.ReadTextRequestAsync(
                (o, s) =>
            {
                var data   = http.RequestCodec.From <SubscriptionConfigData>(s);
                var config = ParseConfig(data);
                if (!ValidateConfig(config, http))
                {
                    return;
                }
                var message = new ClientMessage.UpdatePersistentSubscription(Guid.NewGuid(),
                                                                             Guid.NewGuid(),
                                                                             envelope,
                                                                             stream,
                                                                             groupname,
                                                                             config.ResolveLinktos,
                                                                             config.StartFrom,
                                                                             config.MessageTimeoutMilliseconds,
                                                                             config.ExtraStatistics,
                                                                             config.MaxRetryCount,
                                                                             config.BufferSize,
                                                                             config.LiveBufferSize,
                                                                             config.ReadBatchSize,
                                                                             config.CheckPointAfterMilliseconds,
                                                                             config.MinCheckPointCount,
                                                                             config.MaxCheckPointCount,
                                                                             config.MaxSubscriberCount,
                                                                             CalculateNamedConsumerStrategyForOldClients(data),
                                                                             http.User,
                                                                             "",
                                                                             "");
                Publish(message);
            }, x => Log.DebugException(x, "Reply Text Content Failed."));
        }
Example #26
0
        private void OnStaticContent(HttpEntityManager http, UriTemplateMatch match)
        {
            var contentLocalPath = match.BoundVariables["remaining_path"];

            ReplyWithContent(http, contentLocalPath);
        }
Example #27
0
        private static ClientMessages.NakAction GetNackAction(HttpEntityManager manager, UriTemplateMatch match, NakAction nakAction = NakAction.Unknown)
        {
            var rawValue = match.BoundVariables["action"] ?? string.Empty;

            switch (rawValue.ToLowerInvariant())
            {
            case "park": return(ClientMessages.NakAction.Park);

            case "retry": return(ClientMessages.NakAction.Retry);

            case "skip": return(ClientMessages.NakAction.Skip);

            case "stop": return(ClientMessages.NakAction.Stop);

            default: return(ClientMessages.NakAction.Unknown);
            }
        }
Example #28
0
 private void OnPostViewChangeProof(HttpEntityManager manager, UriTemplateMatch match)
 {
     OnPost(manager, (ElectionMessageDto.ViewChangeProofDto dto) => new ElectionMessage.ViewChangeProof(dto));
 }
Example #29
0
        private void GetNextNMessages(HttpEntityManager http, UriTemplateMatch match)
        {
            if (_httpForwarder.ForwardRequest(http))
            {
                return;
            }
            var groupname = match.BoundVariables["subscription"];
            var stream    = match.BoundVariables["stream"];
            var cnt       = match.BoundVariables["count"];
            var embed     = GetEmbedLevel(http, match);
            int count     = DefaultNumberOfMessagesToGet;

            if (!cnt.IsEmptyString() && (!int.TryParse(cnt, out count) || count > 100 || count < 1))
            {
                SendBadRequest(http, string.Format("Message count must be an integer between 1 and 100 'count' ='{0}'", count));
                return;
            }
            var envelope = new SendToHttpEnvelope(
                _networkSendQueue, http,
                (args, message) => Format.ReadNextNPersistentMessagesCompleted(http, message as ClientMessage.ReadNextNPersistentMessagesCompleted, stream, groupname, count, embed),
                (args, message) =>
            {
                int code;
                var m = message as ClientMessage.ReadNextNPersistentMessagesCompleted;
                if (m == null)
                {
                    throw new Exception("unexpected message " + message);
                }
                switch (m.Result)
                {
                case
                    ClientMessage.ReadNextNPersistentMessagesCompleted.ReadNextNPersistentMessagesResult.Success:
                    code = HttpStatusCode.OK;
                    break;

                case
                    ClientMessage.ReadNextNPersistentMessagesCompleted.ReadNextNPersistentMessagesResult.DoesNotExist:
                    code = HttpStatusCode.NotFound;
                    break;

                case
                    ClientMessage.ReadNextNPersistentMessagesCompleted.ReadNextNPersistentMessagesResult.AccessDenied:
                    code = HttpStatusCode.Unauthorized;
                    break;

                default:
                    code = HttpStatusCode.InternalServerError;
                    break;
                }
                return(new ResponseConfiguration(code, http.ResponseCodec.ContentType,
                                                 http.ResponseCodec.Encoding));
            });

            var cmd = new ClientMessage.ReadNextNPersistentMessages(
                Guid.NewGuid(),
                Guid.NewGuid(),
                envelope,
                stream,
                groupname,
                count,
                http.User);

            Publish(cmd);
        }
 void GivenAMatching(string baseUri, string template, string candidate)
 {
     ThenTheMatch = new UriTemplate(template).Match(baseUri.ToUri(), candidate.ToUri());
 }
Example #31
0
 private void OnPostAccept(HttpEntityManager manager, UriTemplateMatch match)
 {
     OnPost(manager, (ElectionMessageDto.AcceptDto dto) => new ElectionMessage.Accept(dto));
 }