private void Test1Handler(HttpEntityManager http, UriTemplateMatch match)
 {
     if (http.User != null) 
         http.Reply("OK", 200, "OK", "text/plain");
     else 
         http.Reply("Please authenticate yourself", 401, "Unauthorized", "text/plain");
 }
        private void TestEncodingHandler(HttpEntityManager http, UriTemplateMatch match)
        {
            var a = match.BoundVariables["a"];
            var b = match.BoundVariables["b"];

            http.Reply(new { a = a, b = b, rawSegment = http.RequestedUrl.Segments[2] }.ToJson(), 200, "OK", "application/json");
        }
 private void TestAnonymousHandler(HttpEntityManager http, UriTemplateMatch match)
 {
     if (http.User != null)
         http.Reply("ERROR", 500, "ERROR", "text/plain");
     else 
         http.Reply("OK", 200, "OK", "text/plain");
 }
 protected RequestParams SendOk(HttpEntityManager httpEntityManager)
 {
     httpEntityManager.ReplyStatus(HttpStatusCode.OK,
                                   "OK",
                                   e => Log.Debug("Error while closing http connection (ok): {0}.", e.Message));
     return new RequestParams(done: true);
 }
 protected RequestParams SendBadRequest(HttpEntityManager httpEntityManager, string reason)
 {
     httpEntityManager.ReplyStatus(HttpStatusCode.BadRequest,
                                   reason,
                                   e => Log.Debug("Error while closing http connection (bad request): {0}.", e.Message));
     return new RequestParams(done: true);
 }
 protected RequestParams SendTooBig(HttpEntityManager httpEntityManager)
 {
     httpEntityManager.ReplyStatus(HttpStatusCode.RequestEntityTooLarge,
                                   "Too large events received. Limit is 4mb",
                                   e => Log.Debug("Too large events received over HTTP"));
     return new RequestParams(done: true);
 }
        public HttpEntity(DateTime timeStamp,
                          ICodec requestCodec,
                          ICodec responseCodec,
                          HttpListenerContext context,
                          string[] allowedMethods,
                          Action<HttpEntity> onRequestSatisfied)
        {
            Ensure.NotNull(requestCodec, "requestCodec");
            Ensure.NotNull(responseCodec, "responseCodec");
            Ensure.NotNull(context, "context");
            Ensure.NotNull(allowedMethods, "allowedMethods");
            Ensure.NotNull(onRequestSatisfied, "onRequestSatisfied");

            TimeStamp = timeStamp;
            UserHostName = context.Request.UserHostName;

            RequestCodec = requestCodec;
            ResponseCodec = responseCodec;
            _context = context;

            Request = context.Request;
            Response = context.Response;

            Manager = new HttpEntityManager(this, allowedMethods, onRequestSatisfied);
        }
        private void OnGetFreshStats(HttpEntityManager entity, UriTemplateMatch match)
        {
            var envelope = new SendToHttpEnvelope(_networkSendQueue,
                                                  entity,
                                                  Format.GetFreshStatsCompleted,
                                                  Configure.GetFreshStatsCompleted);

            var statPath = match.BoundVariables["statPath"];
            var statSelector = GetStatSelector(statPath);

            bool useMetadata;
            if (!bool.TryParse(match.QueryParameters["metadata"], out useMetadata))
                useMetadata = false;

            bool useGrouping;
            if (!bool.TryParse(match.QueryParameters["group"], out useGrouping))
                useGrouping = true;

            if (!useGrouping && !string.IsNullOrEmpty(statPath))
            {
                SendBadRequest(entity, "Dynamic stats selection works only with grouping enabled");
                return;
            }
             
            Publish(new MonitoringMessage.GetFreshStats(envelope, statSelector, useMetadata, useGrouping));
        }
        private void AckMessages(HttpEntityManager http, UriTemplateMatch match)
        {
            var envelope = new NoopEnvelope();
            var groupname = match.BoundVariables["subscription"];
            var stream = match.BoundVariables["stream"];
            var messageIds = match.BoundVariables["messageIds"];
            var ids = new List<Guid>();
            foreach (var messageId in messageIds.Split(new[] { ',' }))
            {
                Guid id;
                if (!Guid.TryParse(messageId, out id))
                {
                    http.ReplyStatus(HttpStatusCode.BadRequest, "messageid should be a properly formed guid", exception => { });
                    return;
                }
                ids.Add(id);
            }

            var cmd = new ClientMessage.PersistentSubscriptionAckEvents(
                                             Guid.NewGuid(),
                                             Guid.NewGuid(),
                                             envelope,
                                             BuildSubscriptionGroupKey(stream, groupname),
                                             ids.ToArray(),
                                             http.User);
            Publish(cmd);
            http.ReplyStatus(HttpStatusCode.Accepted, "", exception => { });
        }
示例#10
0
 private void OnGetTcpConnectionStats(HttpEntityManager entity, UriTemplateMatch match)
 {
     var envelope = new SendToHttpEnvelope(_networkSendQueue,
                                           entity,
                                           Format.GetFreshTcpConnectionStatsCompleted,
                                           Configure.GetFreshTcpConnectionStatsCompleted);
     Publish(new MonitoringMessage.GetFreshTcpConnectionStats(envelope));
 }
示例#11
0
 public HttpSend(
     HttpEntityManager httpEntityManager, ResponseConfiguration configuration, string data, Message message)
     : base(Guid.Empty, null, httpEntityManager)
 {
     Data = data;
     Configuration = configuration;
     Message = message;
 }
示例#12
0
        private void ReplyWithContent(HttpEntityManager http, string contentLocalPath)
        {
            //NOTE: this is fix for Mono incompatibility in UriTemplate behavior for /a/b{*C}
            if (("/" + contentLocalPath).StartsWith(_localWebRootPath))
                contentLocalPath = contentLocalPath.Substring(_localWebRootPath.Length);

            //_logger.Trace("{0} requested from MiniWeb", contentLocalPath);
            try
            {
                var extensionToContentType = new Dictionary<string, string>
                {
                    { ".png",  "image/png"} ,
                    { ".svg",  "image/svg+xml"} ,
                    { ".woff", "application/x-font-woff"} ,
                    { ".woff2", "application/x-font-woff"} ,
                    { ".ttf", "application/font-sfnt"} ,
                    { ".jpg",  "image/jpeg"} ,
                    { ".jpeg", "image/jpeg"} ,
                    { ".css",  "text/css"} ,
                    { ".htm",  "text/html"} ,
                    { ".html", "text/html"} ,
                    { ".js",   "application/javascript"} ,
                    { ".json",   "application/json"} ,
                    { ".ico",  "image/vnd.microsoft.icon"}
                };

                var extension = Path.GetExtension(contentLocalPath);
                var fullPath = Path.Combine(_fileSystemRoot, contentLocalPath);

                string contentType;
                if (string.IsNullOrEmpty(extension)
                    || !extensionToContentType.TryGetValue(extension.ToLower(), out contentType)
                    || !File.Exists(fullPath))
                {
                    _logger.Info("Replying 404 for {0} ==> {1}", contentLocalPath, fullPath);
                    http.ReplyTextContent(
                        "Not Found", 404, "Not Found", "text/plain", null,
                        ex => _logger.InfoException(ex, "Error while replying from MiniWeb"));
                }
                else
                {
                    var config = GetWebPageConfig(contentType);
                    var content = File.ReadAllBytes(fullPath);

                    http.Reply(content,
                                       config.Code,
                                       config.Description,
                                       config.ContentType,
                                       config.Encoding,
                                       config.Headers,
                                       ex => _logger.InfoException(ex, "Error while replying from MiniWeb"));
                }
            }
            catch (Exception ex)
            {
                http.ReplyTextContent(ex.ToString(), 500, "Internal Server Error", "text/plain", null, Console.WriteLine);
            }
        }
示例#13
0
 private void OnGetOptions(HttpEntityManager entity, UriTemplateMatch match)
 {
     entity.ReplyTextContent(Codec.Json.To(GetOptionsInfo(options)),
                             HttpStatusCode.OK,
                             "OK",
                             entity.ResponseCodec.ContentType,
                             null,
                             e => Log.ErrorException(e, "error while writing http response (options)"));
 }
示例#14
0
 private void OnGetPing(HttpEntityManager entity, UriTemplateMatch match)
 {
     var response = new HttpMessage.TextMessage("Ping request successfully handled");
     entity.ReplyTextContent(Format.TextMessage(entity, response),
                             HttpStatusCode.OK,
                             "OK",
                             entity.ResponseCodec.ContentType,
                             null,
                             e => Log.ErrorException(e, "Error while writing HTTP response (ping)"));
 }
示例#15
0
 private void OnListNodeSubsystems(HttpEntityManager http, UriTemplateMatch match)
 {
     http.ReplyTextContent(
     Codec.Json.To(_enabledNodeSubsystems),
     200,
     "OK",
     "application/json",
     null,
     ex => Log.InfoException(ex, "Failed to prepare main menu")
     );
 }
示例#16
0
 private void OnGetInfo(HttpEntityManager entity, UriTemplateMatch match)
 {
     entity.ReplyTextContent(Codec.Json.To(new
                             {
                                 ESVersion = VersionInfo.Version
                             }),
                             HttpStatusCode.OK,
                             "OK",
                             entity.ResponseCodec.ContentType,
                             null,
                             e => Log.ErrorException(e, "Error while writing http response (info)"));
 }
 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;
     }
 }
示例#18
0
 private void OnPostShutdown(HttpEntityManager entity, UriTemplateMatch match)
 {
     if (entity.User != null && entity.User.IsInRole(SystemRoles.Admins))
     {
         Log.Info("Request shut down of node because shutdown command has been received.");
         Publish(new ClientMessage.RequestShutdown(exitProcess: true));
         entity.ReplyStatus(HttpStatusCode.OK, "OK", LogReplyError);
     }
     else
     {
         entity.ReplyStatus(HttpStatusCode.Unauthorized, "Unauthorized", LogReplyError);
     }
 }
示例#19
0
 private void OnPostScavenge(HttpEntityManager entity, UriTemplateMatch match)
 {
     if (entity.User != null && entity.User.IsInRole(SystemRoles.Admins))
     {
         Log.Info("Request scavenging because /admin/scavenge request has been received.");
         Publish(new ClientMessage.ScavengeDatabase(new NoopEnvelope(), Guid.Empty, entity.User));
         entity.ReplyStatus(HttpStatusCode.OK, "OK", LogReplyError);
     }
     else
     {
         entity.ReplyStatus(HttpStatusCode.Unauthorized, "Unauthorized", LogReplyError);
     }
 }
示例#20
0
        private void TestEncodingHandler(HttpEntityManager http, UriTemplateMatch match, string a)
        {
            var b = match.BoundVariables["b"];

            http.Reply(
                new
                    {
                        a = a,
                        b = b,
                        rawSegment = http.RequestedUrl.Segments[1],
                        requestUri = match.RequestUri,
                        rawUrl = http.HttpEntity.Request.RawUrl
                    }.ToJson(), 200, "OK", "application/json");
        }
示例#21
0
 private void OnGetHistogram(HttpEntityManager entity, UriTemplateMatch match)
 {
     var name = match.BoundVariables["name"];
    
     var histogram = Histograms.HistogramService.GetHistogram(name);
     if (histogram == null)
     {
         entity.ReplyStatus(HttpStatusCode.NotFound, "Not found", _ => { });
         return;
     }
     var writer = new StringWriter();
     lock (histogram)
     {
         histogram.outputPercentileDistribution(writer, outputValueUnitScalingRatio: 1000.0*1000.0);
     }
     var response = Encoding.ASCII.GetBytes(writer.ToString());
     entity.Reply(response,
         HttpStatusCode.OK, 
         "OK", 
         ContentType.PlainText, 
         Encoding.ASCII, 
         null,
         _ => { });
 }
        private void ReplayParkedMessages(HttpEntityManager http, UriTemplateMatch match)
        {
            if (_httpForwarder.ForwardRequest(http))
                return;
            var envelope = new SendToHttpEnvelope(
                _networkSendQueue, http,
                (args, message) => http.ResponseCodec.To(message),
                (args, message) =>
                {
                    int code;
                    var m = message as ClientMessage.ReplayMessagesReceived;
                    if (m == null) throw new Exception("unexpected message " + message);
                    switch (m.Result)
                    {
                        case ClientMessage.ReplayMessagesReceived.ReplayMessagesReceivedResult.Success:
                            code = HttpStatusCode.OK;
                            break;
                        case ClientMessage.ReplayMessagesReceived.ReplayMessagesReceivedResult.DoesNotExist:
                            code = HttpStatusCode.NotFound;
                            break;
                        case ClientMessage.ReplayMessagesReceived.ReplayMessagesReceivedResult.AccessDenied:
                            code = HttpStatusCode.Unauthorized;
                            break;
                        default:
                            code = HttpStatusCode.InternalServerError;
                            break;
                    }

                    return new ResponseConfiguration(code, http.ResponseCodec.ContentType,
                        http.ResponseCodec.Encoding);
                });
            var groupname = match.BoundVariables["subscription"];
            var stream = match.BoundVariables["stream"];
            var cmd = new ClientMessage.ReplayAllParkedMessages(Guid.NewGuid(), Guid.NewGuid(), envelope, stream, groupname, http.User);
            Publish(cmd);
        }
 protected void SendOk(HttpEntityManager httpEntityManager)
 {
     httpEntityManager.ReplyStatus(HttpStatusCode.OK,
                                   "OK",
                                   e => Log.Debug("Error while closing http connection (ok): {0}.", e.Message));
 }
 protected static string MakeUrl(HttpEntityManager http, string path)
 {
     var hostUri = http.RequestedUrl;
     return new UriBuilder(hostUri.Scheme, hostUri.Host, hostUri.Port, path).Uri.AbsoluteUri;
 }
示例#25
0
 public static void ReplyStatus(this HttpEntityManager self, int code, string description,
                                Action <Exception> onError, IEnumerable <KeyValuePair <string, string> > headers = null)
 {
     self.Reply(null, code, description, null, null, null, onError);
 }
示例#26
0
 private void OnStaticContent(HttpEntityManager http, UriTemplateMatch match)
 {
     var contentLocalPath = match.BoundVariables["remaining_path"];
     ReplyWithContent(http, contentLocalPath);
 }
示例#27
0
 public static void ReplyStatus(this HttpEntityManager self, int code, string description, Action <Exception> onError)
 {
     self.Reply(null, code, description, null, null, null, onError);
 }
示例#28
0
 public HttpCompleted(Guid correlationId, HttpEntityManager httpEntityManager)
 {
     CorrelationId = correlationId;
     HttpEntityManager = httpEntityManager;
 }
示例#29
0
 /// <param name="correlationId"></param>
 /// <param name="envelope">non-null envelope requests HttpCompleted messages in response</param>
 /// <param name="httpEntityManager"></param>
 protected HttpSendMessage(Guid correlationId, IEnvelope envelope, HttpEntityManager httpEntityManager)
 {
     CorrelationId = correlationId;
     Envelope = envelope;
     HttpEntityManager = httpEntityManager;
 }
示例#30
0
 public HttpEndSend(Guid correlationId, IEnvelope envelope, HttpEntityManager httpEntityManager)
     : base(correlationId, envelope, httpEntityManager)
 {
 }
示例#31
0
 public HttpSendPart(Guid correlationId, IEnvelope envelope, HttpEntityManager httpEntityManager, string data)
     : base(correlationId, envelope, httpEntityManager)
 {
     Data = data;
 }
示例#32
0
 public HttpBeginSend(Guid correlationId, IEnvelope envelope, 
     HttpEntityManager httpEntityManager, ResponseConfiguration configuration)
     : base(correlationId, envelope, httpEntityManager)
 {
     Configuration = configuration;
 }