public void OnRequest(HttpRequestHead head, IDataProducer body, IHttpResponseDelegate response) { var env = new Dictionary<string, object>(); var request = new RequestEnvironment(env); if (context != null) foreach (var kv in context) env[kv.Key] = kv.Value; if (head.Headers == null) request.Headers = new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase); else request.Headers = head.Headers.ToDictionary(kv => kv.Key, kv => new[] { kv.Value }, StringComparer.OrdinalIgnoreCase); request.Method = head.Method ?? ""; request.Path = head.Path ?? ""; request.PathBase = ""; request.QueryString = head.QueryString ?? ""; request.Scheme = "http"; // XXX request.Version = "1.0"; if (body == null) request.BodyDelegate = null; else request.BodyDelegate = (write, end, cancellationToken) => { var d = body.Connect(new DataConsumer( write, end, () => end(null))); cancellationToken.Register(d.Dispose); }; appDelegate(env, HandleResponse(response), HandleError(response)); }
private void RequestReadCompleted(HttpRequestHead head, Stream requestStream, IHttpResponseDelegate response) { Uri baseUri = new Uri("http://localhost/"); Uri requestUrl = new Uri(baseUri, head.Uri); Url nancyUrl = new Url { Scheme = requestUrl.Scheme, HostName = requestUrl.Host, Port = requestUrl.IsDefaultPort ? null : (int?)requestUrl.Port, BasePath = baseUri.AbsolutePath.TrimEnd('/'), Path = HttpUtility.UrlDecode(head.Uri), Query = requestUrl.Query, Fragment = requestUrl.Fragment, }; Dictionary<string, IEnumerable<string>> headers = new Dictionary<string, IEnumerable<string>>(); foreach (var kvp in head.Headers) headers[kvp.Key] = new List<string> { kvp.Value }; Request req = new Request( head.Method, nancyUrl, Nancy.IO.RequestStream.FromStream(requestStream, requestStream.Length), headers, null); m_Engine.HandleRequest(req, context => RequestProcessingCompleted(context, response), ex => RequestProcessingError(ex, response)); }
public void OnRequest(HttpRequestHead request, IDataProducer requestBody, IHttpResponseDelegate response) { if (request.Uri.StartsWith("/feed.xml")) { var body = new FeedBuilder(Port).Generate(FeedTitle, FilePaths, ImagePath); var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary<string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", body.Length.ToString() }, } }; response.OnResponse(headers, new SimpleProducer(body)); return; } // deal with request for file content string uri = request.Uri.Replace("%20", " ").Replace("/", "\\"); string filePath = FilePaths.Where(d => d.Contains(uri)).FirstOrDefault(); if (filePath != null) { FileInfo fi = new FileInfo(filePath); string mimeType = GetMimeType(filePath); var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary<string, string>() { { "Content-Type", mimeType }, { "Content-Length", fi.Length.ToString() }, } }; response.OnResponse(headers, new FileProducer(filePath)); return; } else { var responseBody = "The resource you requested ('" + request.Uri + "') could not be found."; var headers = new HttpResponseHead() { Status = "404 Not Found", Headers = new Dictionary<string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", responseBody.Length.ToString() } } }; var body = new SimpleProducer(responseBody); response.OnResponse(headers, body); return; } }
internal static void SerializeResponse(Object o, IHttpResponseDelegate response) { var s = new JavaScriptSerializer(); string json = s.Serialize(o); var headers = GetOkHeaders(json.Length); response.OnResponse(headers, new BufferedProducer(json)); }
public void OnRequest(HttpRequestHead head, IDataProducer body, IHttpResponseDelegate response) { var env = new Environment(); if (context != null) foreach (var kv in context) env[kv.Key] = kv.Value; env.Headers = head.Headers ?? new Dictionary<string, string>(); env.Method = head.Method ?? ""; env.Path = head.Path ?? ""; env.PathBase = ""; env.QueryString = head.QueryString ?? ""; env.Scheme = "http"; // XXX env.Version = "1.0"; if (body == null) env.Body = null; else env.Body = (onData, onError, onEnd) => { var d = body.Connect(new DataConsumer(onData, onError, onEnd)); return () => { if (d != null) d.Dispose(); }; }; appDelegate(env, HandleResponse(response), HandleError(response)); }
public void OnRequest(HttpRequestHead head, IDataProducer body, IHttpResponseDelegate response) { if (head.Method.ToUpperInvariant() == "POST") { ProcessPOSTRequest(body, response); } else if (head.Method.ToUpperInvariant() == "GET" && head.Uri == "/crossdomain.xml") { ProcessCrossDomainRequest(body, response); } else if (head.Method.ToUpperInvariant() == "GET" && head.QueryString.Contains("metrics")) { ProcessGETRequest(body, head, response); } else if (head.Method.ToUpperInvariant() == "GET" && head.Uri == "/") { ProcessLoadBalancerRequest(body, response); } else { ProcessFileNotFound(body, response); } }
private static void TurnOnElement(HttpRequestHead request, IHttpResponseDelegate response) { var status = new Status(); NameValueCollection parms = GetParameters(request); if (!parms.HasKeys() && parms["id"] != null && parms["time"] != null && parms["color"]!=null) { HttpResponseHead headers = GetHeaders(0, HttpStatusCode.BadRequest.ToString()); response.OnResponse(headers, new BufferedProducer("")); return; } if (parms["color"].Length != 7 || !parms["color"].StartsWith("#")) { status.Message = "Invalid color. Must be Hex."; SerializeResponse(status,response); return; } Guid elementId = Guid.Empty; bool allElements = false; int seconds; if ("all".Equals(parms["id"])) { allElements = true; } else { Guid.TryParse(parms["id"], out elementId); } if (!int.TryParse(parms["time"], out seconds)) { status.Message = "Time must be numeric."; SerializeResponse(status,response); return; } Color elementColor = ColorTranslator.FromHtml(parms["color"]); //TODO the following logic for all does not properly deal with discrete color elements when turning all on //TODO they will not respond to turning on white if they are set up with a filter. //TODO enhance this to figure out what colors there are and turn them all on when we are turning all elements on. var effect = new SetLevel { TimeSpan = TimeSpan.FromSeconds(seconds), Color = elementColor, IntensityLevel = 1, TargetNodes = allElements ? VixenSystem.Nodes.GetRootNodes().ToArray() : new[] {VixenSystem.Nodes.GetElementNode(elementId)} }; Module.LiveSystemContext.Execute(new EffectNode(effect, TimeSpan.Zero)); status.Message = string.Format("{0} element(s) turned on for {1} seconds at 100% intensity.", allElements?"All":VixenSystem.Nodes.GetElementNode(elementId).Name, seconds); SerializeResponse(status,response); }
private void GetSequences(HttpRequestHead request, IHttpResponseDelegate response) { var sequenceNames = SequenceService.Instance.GetAllSequenceFileNames().Select(Path.GetFileName); var sequences = sequenceNames.Select(sequenceName => new Sequence { Name = Path.GetFileNameWithoutExtension(sequenceName), FileName = sequenceName }).ToList(); SerializeResponse(sequences,response); }
public override void ProcessPost(HttpRequestHead request, IDataProducer requestBody, IHttpResponseDelegate response) { //Figure out how to get the post params from within Kayak so some of these operations that //should be a post can be. Right now I am limited to just post based on verbs on the url. if (request.Uri.StartsWith("/api/play/stopSequence")) { StopSequence(request, response); return; } UnsupportedOperation(request,response); }
internal static HttpRequestHead UnsupportedOperation(HttpRequestHead request, IHttpResponseDelegate response) { var serializer = new JavaScriptSerializer(); string json = serializer.Serialize(new Status { Message = "Unknown request" }); HttpResponseHead headers = GetOkHeaders(json.Length); headers.Status = HttpStatusCode.BadRequest.ToString(); response.OnResponse(headers, new BufferedProducer(json)); return request; }
ResultDelegate BufferBody(IHttpResponseDelegate response) { return (status, headers, body) => { var buffer = new LinkedList<ArraySegment<byte>>(); body((data, continuation) => { var copy = new byte[data.Count]; Buffer.BlockCopy(data.Array, data.Offset, copy, 0, data.Count); buffer.AddLast(new ArraySegment<byte>(copy)); return false; }, HandleError(response), () => { var contentLength = buffer.Aggregate(0, (r, i) => r + i.Count); IDataProducer responseBody = null; if (contentLength > 0) { headers["Content-Length"] = contentLength.ToString(); responseBody = new DataProducer((onData, onError, onComplete) => { bool cancelled = false; while (!cancelled && buffer.Count > 0) { var next = buffer.First; buffer.RemoveFirst(); onData(next.Value, null); } onComplete(); buffer = null; return () => cancelled = true; }); } response.OnResponse(new HttpResponseHead() { Status = status, Headers = headers }, responseBody); }); }; }
public void Handle(string appname, string[] components, HttpRequestHead head, IDataProducer body, IHttpResponseDelegate response) { // Look inside the cache for the specified file. Cache c = new Cache(false); string path = HttpUtility.UrlDecode(components.Where((value, row) => row >= 2).Aggregate((a, b) => a + "/" + b)); if (!c.Exists("server/" + appname + "/store/" + path)) { response.OnResponse(HttpErrorResponseHead.Get(), new HttpErrorDataProducer()); return; } // Calculate patch path from source to destination. string result = ""; Hash source = Hash.FromString(components[0]); Hash destination = Hash.FromString(components[1]); while (source != destination) { // Find the patch in the patches that will turn source // into the next patch. IEnumerable<string> patches = c.List("server/" + appname + "/patches/" + path).Where(v => v.StartsWith(source.ToString() + "-")); if (patches.Count() != 1) { response.OnResponse(HttpErrorResponseHead.Get(), new HttpErrorDataProducer()); return; } string next = patches.First(); source = Hash.FromString(next.Substring((source.ToString() + "-").Length)); using (StreamReader reader = new StreamReader(c.GetFilePath("server/" + appname + "/patches/" + path + "/" + next))) { result += "--- NEXT PATCH (" + reader.BaseStream.Length + ") ---\r\n"; result += reader.ReadToEnd(); result += "\r\n"; } } result += "--- END OF PATCHES ---\r\n"; // Return data. response.OnResponse(new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary<string, string> { { "Content-Type", "text/plain" }, { "Content-Length", result.Length.ToString() }, { "Connection", "close" } } }, new BufferedProducer(result)); }
private static void ApiGet(HttpRequestHead request, IHttpResponseDelegate response) { const string pattern = @"^/api/([A-Za-z]+)/.*$"; Match match = Regex.Match(request.Uri, pattern); if (match.Success) { IController controller = ControllerFactory.Get(match.Groups[1].Value); if (controller != null) { controller.ProcessGet(request, response); return; } } NotFoundResponse(request, response); }
Action<Exception> HandleError(IHttpResponseDelegate response) { return error => { Console.Error.WriteLine("Error from Gate application."); Console.Error.WriteStackTrace(error); response.OnResponse(new HttpResponseHead() { Status = "503 Internal Server Error", Headers = new Dictionary<string, string>() { { "Connection", "close" } } }, null); }; }
public void OnRequest(HttpRequestHead request, IDataProducer body, IHttpResponseDelegate response) { _log.DebugFormat("Start Processing request for : {0}:{1}", request.Method, request.Uri); if (GetHandlerCount() < 1) { ReturnHttpMockNotFound(response); return; } var handler = _requestMatcher.Match(request, _handlers); if (handler == null) { _log.DebugFormat("No Handlers matched"); ReturnHttpMockNotFound(response); return; } HandleRequest(request, body, response, handler); }
public override void ProcessGet(HttpRequestHead request, IHttpResponseDelegate response) { if (request.Uri.StartsWith("/api/element")) { if (request.Uri.StartsWith("/api/element/getElements")) { GetElements(request, response); return; } if (request.Uri.StartsWith("/api/element/on")) { TurnOnElement(request, response); return; } } UnsupportedOperation(request, response); }
private static void Reply(IHttpResponseDelegate response, String contentType, byte[] data, bool allowCache, String status, Dictionary <String, String> headers) { var body = new BufferedBody(data); headers = headers ?? new Dictionary <string, string>(); headers["Content-Type"] = contentType; headers["Content-Length"] = body.Length.ToString(); if (allowCache) { headers["Cache-Control"] = "max-age=31556926"; } response.OnResponse(new HttpResponseHead { Status = status ?? "200 OK", Headers = headers }, body); }
public void Handle(string appname, string[] components, HttpRequestHead head, IDataProducer body, IHttpResponseDelegate response) { // Look inside the cache for a list of files. Cache c = new Cache(false); string s = ""; foreach (string key in c.ListRecursive("server/" + appname + "/hashes")) s += c.Get<Hash>("server/" + appname + "/hashes/" + key) + " " + key + "\r\n"; response.OnResponse(new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary<string, string> { { "Content-Type", "text/plain" }, { "Content-Length", s.Length.ToString() }, { "Connection", "close" } } }, new BufferedProducer(s)); }
public void OnRequest(HttpRequestHead request, IDataProducer requestBody, IHttpResponseDelegate response) { if (request.Method.ToUpperInvariant() == "POST" && request.Uri.ToLower().StartsWith("/api")) { ApiPost(request, requestBody, response); } else if (request.Uri.StartsWith("/api")) { ApiGet(request, response); } else if (request.Uri.StartsWith("/resx")) { GetResource(request, response); } else if (request.Uri.StartsWith("/")) { GetResourceByName("vixen.htm", response); } else { NotFoundResponse(request, response); } }
public void Handle(string appname, string[] components, HttpRequestHead head, IDataProducer body, IHttpResponseDelegate response) { // Look inside the cache for the specified file. Cache c = new Cache(false); string path = HttpUtility.UrlDecode(components.Aggregate((a, b) => a + "/" + b)); if (!c.Exists("server/" + appname + "/store/" + path)) { response.OnResponse(HttpErrorResponseHead.Get(), new HttpErrorDataProducer()); return; } response.OnResponse(new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary<string, string> { { "Connection", "close" } } }, new StreamReaderProducer(c.GetFilePath("server/" + appname + "/store/" + path))); }
public void OnRequest(HttpRequestHead head, IDataProducer body, IHttpResponseDelegate response) { var env = new Dictionary<string, object>(); var request = new RequestEnvironment(env); if (context != null) foreach (var kv in context) env[kv.Key] = kv.Value; if (head.Headers == null) env[OwinConstants.RequestHeaders] = new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase); else env[OwinConstants.RequestHeaders] = head.Headers.ToDictionary(kv => kv.Key, kv => new[] { kv.Value }, StringComparer.OrdinalIgnoreCase); env[OwinConstants.ResponseHeaders] = new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase); request.Method = head.Method ?? ""; request.Path = head.Path ?? ""; request.PathBase = ""; request.QueryString = head.QueryString ?? ""; request.Scheme = "http"; // XXX request.Version = "1.0"; if (body == null) env[OwinConstants.RequestBody] = Stream.Null; /* else request.Body = (write, end, cancellationToken) => { var d = body.Connect(new DataConsumer( write, end, () => end(null))); cancellationToken.Register(d.Dispose); }; */ // TODO: Request body stream appFunc(env) .Then(() => HandleResponse(response, env)) .Catch(errorInfo => HandleError(response, errorInfo)); }
public void OnRequest(HttpRequestHead request, IDataProducer body, IHttpResponseDelegate response) { _log.DebugFormat("Start Processing request for : {0}:{1}", request.Method, request.Uri); if (GetHandlerCount() < 1) { ReturnHttpMockNotFound(response); return; } IRequestHandler handler = null; Guid currentRequestId = Guid.Empty; if (request.Headers == null) { _log.DebugFormat("No header specified"); } else if (request.Headers.ContainsKey(Constants.MockSessionHeaderKey)) { currentRequestId = new Guid(request.Headers[Constants.MockSessionHeaderKey]); } else if (request.Headers.ContainsKey(Constants.CookieHeaderKey) && request.Headers[Constants.CookieHeaderKey].Contains("=")) { var mockSessionId = request.Headers[Constants.CookieHeaderKey].Split("=".ToCharArray()); currentRequestId = new Guid(mockSessionId[1]); } RequestHandlerList requestHandler; if (_handlers.TryGetValue(currentRequestId, out requestHandler)) { lock (requestHandler) { handler = _requestMatcher.Match(request, requestHandler); } } if (handler == null) { _log.DebugFormat("No Handlers matched"); ReturnHttpMockNotFound(response); return; } HandleRequest(request, body, response, handler); }
private void RequestProcessingCompleted(NancyContext context, IHttpResponseDelegate response) { HttpResponseHead responseHead = new HttpResponseHead { Headers = context.Response.Headers, Status = context.Response.StatusCode.ToString() }; byte[] responseBodyData; using (MemoryStream ms = new MemoryStream()) { context.Response.Contents(ms); //ms.Seek(0, SeekOrigin.Begin); responseBodyData = ms.ToArray(); } responseHead.Headers["Content-Type"] = context.Response.ContentType; responseHead.Headers["Content-Length"] = responseBodyData.LongLength.ToString(); BufferedProducer bodyDataProducer = new BufferedProducer (responseBodyData); response.OnResponse(responseHead, bodyDataProducer); }
private void PlaySequence(HttpRequestHead request, IHttpResponseDelegate response) { HttpResponseHead headers; var status = new Status(); NameValueCollection parms = GetParameters(request); if (!parms.HasKeys() && parms["name"] != null) { headers = GetHeaders(0, HttpStatusCode.BadRequest.ToString()); response.OnResponse(headers, new BufferedProducer("")); return; } string fileName = HttpUtility.UrlDecode(parms["name"]); if (_context != null && (_context.IsRunning)) { status.Message = string.Format("Already playing {0}", _context.Sequence.Name); } else { ISequence sequence = SequenceService.Instance.Load(fileName); if (sequence == null) { headers = GetOkHeaders(0); headers.Status = HttpStatusCode.NotFound.ToString(); response.OnResponse(headers, new BufferedProducer("")); return; } Logging.Info(string.Format("Web - Prerendering effects for sequence: {0}", sequence.Name)); Parallel.ForEach(sequence.SequenceData.EffectData.Cast <IEffectNode>(), effectNode => effectNode.Effect.PreRender()); _context = VixenSystem.Contexts.CreateSequenceContext(new ContextFeatures(ContextCaching.NoCaching), sequence); _context.ContextEnded += context_ContextEnded; _context.Play(TimeSpan.Zero, sequence.Length); status.Message = string.Format("Playing sequence {0} of length {1}", sequence.Name, sequence.Length); } SerializeResponse(status, response); }
public void OnRequest(HttpRequestHead request, IDataProducer requestBody, IHttpResponseDelegate response) { var ea = new RequestReceivedEventArgs(); ea.RequestHead = request; ea.ResponseHead = ResponseMessageHelper.GetHttpResponseHead(); string contentType = string.Empty; if(ea.RequestHead.Headers.ContainsKey("Content-Type")) contentType=ea.RequestHead.Headers["Content-Type"]; int contentSize = 0; if(ea.RequestHead.Headers.ContainsKey("Content-Length")) { int.TryParse(ea.RequestHead.Headers["Content-Length"],out contentSize); } BufferedConsumer bc=new BufferedConsumer(bodyContents => { try { ea.RequestBody = bodyContents; //Called when request body is read to end if (RequestReceived != null) { RequestReceived(this, ea); } var bp = ea.ResponseBodyProducer as BufferedProducer; if (bp != null) { ea.ResponseHead.Headers["Content-Length"] = bp.GetContentLength().ToString(); } } finally { response.OnResponse(ea.ResponseHead, ea.ResponseBodyProducer); } }, error => { }, contentType,contentSize); //Gets complete HTTP Request and runs code defined over requestBody.Connect(bc); }
public void OnRequest(HttpRequestHead head, Kayak.IDataProducer body, IHttpResponseDelegate response) { string[] components = head.Uri.Trim('/').Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries); if (components.Length <= 1) { response.OnResponse(HttpErrorResponseHead.Get(), new HttpErrorDataProducer()); return; } foreach (IOperation o in this.m_Operations) { if (o.Handles(components[1].ToLowerInvariant())) { o.Handle(components[0], components.Where((value, row) => row >= 2).ToArray(), head, body, response); return; } } // If all else fails.. response.OnResponse(HttpErrorResponseHead.Get(), new HttpErrorDataProducer()); }
public void OnRequest(HttpRequestHead request, IDataProducer body, IHttpResponseDelegate response) { _log.DebugFormat("Start Processing request for : {0}:{1}", request.Method, request.Uri); if (GetHandlerCount() < 1) { ReturnHttpMockNotFound(response); return; } RequestHandler handler = MatchHandler(request); if (handler == null) { _log.DebugFormat("No Handlers matched"); ReturnHttpMockNotFound(response); return; } _log.DebugFormat("Matched a handler {0},{1}, {2}", handler.Method, handler.Path, DumpQueryParams(handler.QueryParams)); IDataProducer dataProducer = GetDataProducer(request, handler); if (request.HasBody()) { body.Connect(new BufferedConsumer( bufferedBody => { handler.RecordRequest(request, bufferedBody); _log.DebugFormat("Body: {0}", bufferedBody); response.OnResponse(handler.ResponseBuilder.BuildHeaders(), dataProducer); }, error => { _log.DebugFormat("Error while reading body {0}", error.Message); response.OnResponse(handler.ResponseBuilder.BuildHeaders(), dataProducer); } )); } else { response.OnResponse(handler.ResponseBuilder.BuildHeaders(), dataProducer); handler.RecordRequest(request, null); } _log.DebugFormat("End Processing request for : {0}:{1}", request.Method, request.Uri); }
public void OnRequest(HttpRequestHead head, IDataProducer body, IHttpResponseDelegate response) { try { if (head.Method.ToUpperInvariant() == "OPTIONS") { ProcessOPTIONSRequest(head, body, response); } else if (head.Method.ToUpperInvariant() == "POST") { ProcessPOSTRequest(head, body, response); } else if (head.Method.ToUpperInvariant() == "GET" && head.Uri == "/crossdomain.xml") { ProcessCrossDomainRequest(head, body, response); } else if (head.Method.ToUpperInvariant() == "GET" && head.Uri == "/clientaccesspolicy.xml") { ProcessClientAccessPolicyRequest(head, body, response); } else if (head.Method.ToUpperInvariant() == "GET" && head.QueryString?.Contains("metrics") == true) { ProcessGETRequest(head, body, response); } else if (head.Method.ToUpperInvariant() == "GET" && head.Uri == "/") { ProcessLoadBalancerRequest(head, body, response); } else { ProcessFileNotFound(head, body, response); } } catch (Exception ex) { ProcessInternalServerError(head, body, response); } }
public override void ProcessGet(HttpRequestHead request, IHttpResponseDelegate response) { if (request.Uri.StartsWith("/api/play")) { if (request.Uri.StartsWith("/api/play/getSequences")) { GetSequences(request, response); return; } if (request.Uri.StartsWith("/api/play/playSequence")) { PlaySequence(request, response); return; } if (request.Uri.StartsWith("/api/play/status")) { Status(request, response); return; } } UnsupportedOperation(request, response); }
private static void HandleAPIRequest(Stream stream, string method, IHttpResponseDelegate response) { var hrequest = new HttpRequest(stream, method); var hresponse = new HttpResponse(); var protocol = new NPWebAPIService(); protocol.HandleHttpRequest(hrequest, hresponse); response.OnResponse(new HttpResponseHead() { Status = (hresponse.StatusCode == 200 || hresponse.StatusCode == 0) ? "200 OK" : "405 Method Not Allowed", Headers = new Dictionary <string, string>() { { "Content-Length", hresponse.ContentLength.ToString() }, { "Content-Type", hresponse.ContentType } } }, new BufferedProducer(((MemoryStream)hresponse.OutputStream).GetBuffer())); }
private static void HandleStatusRequest(IHttpResponseDelegate response) { var responseText = ""; responseText += "Clients: " + NPSocket.NumClients + "\r\n"; responseText += "Packet queue size: " + NPHandler.PacketQueueSize + "\r\n"; var responseBytes = Encoding.ASCII.GetBytes(responseText); response.OnResponse(new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary <string, string>() { { "Content-Length", responseBytes.Length.ToString() }, { "Content-Type", "text/plain" } } }, new BufferedProducer(responseBytes)); }
private static void HandleFlagRequest(string path, IHttpResponseDelegate response) { var comp = path.Split('/').Last(); var result = DebugFlags.Toggle(comp); var responseText = string.Format("{0} is now {1}.", comp, result); var responseBytes = Encoding.ASCII.GetBytes(responseText); response.OnResponse(new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary <string, string>() { { "Content-Length", responseBytes.Length.ToString() }, { "Content-Type", "text/plain" } } }, new BufferedProducer(responseBytes)); }
private static HttpRequestHead EchoPost(HttpRequestHead request, IDataProducer requestBody, IHttpResponseDelegate response) { var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary <string, string>() { { "Content-Type", "text/plain" }, { "Connection", "close" } } }; if (request.Headers.ContainsKey("Content-Length")) { headers.Headers["Content-Length"] = request.Headers["Content-Length"]; } // if you call OnResponse before subscribing to the request body, // 100-continue will not be sent before the response is sent. // per rfc2616 this response must have a 'final' status code, // but the server does not enforce it. response.OnResponse(headers, requestBody); return(request); }
private static void GetResource(HttpRequestHead request, IHttpResponseDelegate response) { var contentRequest = request.Uri.ToString().ToLower().Replace("/resx/", string.Empty).Replace('/', '.'); GetResourceByName(contentRequest, response); }
private static void ApiPost(HttpRequestHead request, IDataProducer requestBody, IHttpResponseDelegate response) { const string pattern = @"^/api/([A-Za-z]+)/.*$"; Match match = Regex.Match(request.Uri, pattern); if (match.Success) { IController controller = ControllerFactory.Get(match.Groups[1].Value); if (controller != null) { controller.ProcessPost(request, requestBody, response); return; } } NotFoundResponse(request, response); }
public void SetUp() { _processor = new RequestProcessor(_ruleThatReturnsFirstHandler, new RequestHandlerList()); _requestHandlerFactory = new RequestHandlerFactory(_processor); _dataProducer = MockRepository.GenerateStub<IDataProducer>(); _httpResponseDelegate = MockRepository.GenerateStub<IHttpResponseDelegate>(); _ruleThatReturnsFirstHandler = MockRepository.GenerateStub<IMatchingRule>(); _ruleThatReturnsFirstHandler.Stub(x => x.IsEndpointMatch(null, new HttpRequestHead())).IgnoreArguments().Return(true).Repeat.Once(); _ruleThatReturnsNoHandlers = MockRepository.GenerateStub<IMatchingRule>(); _ruleThatReturnsNoHandlers.Stub(x => x.IsEndpointMatch(null, new HttpRequestHead())).IgnoreArguments().Return(false); }
public void OnRequest(HttpRequestHead request, IDataProducer requestBody, IHttpResponseDelegate response) { if (request.Method.ToUpperInvariant() == "POST" && request.Uri.StartsWith("/bufferedecho")) { // when you subecribe to the request body before calling OnResponse, // the server will automatically send 100-continue if the client is // expecting it. requestBody.Connect(new BufferedConsumer(bufferedBody => { var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary<string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", request.Headers["Content-Length"] }, { "Connection", "close" } } }; response.OnResponse(headers, new BufferedProducer(bufferedBody)); }, error => { // XXX // uh oh, what happens? })); } else if (request.Method.ToUpperInvariant() == "POST" && request.Uri.StartsWith("/echo")) { var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary<string, string>() { { "Content-Type", "text/plain" }, { "Connection", "close" } } }; if (request.Headers.ContainsKey("Content-Length")) headers.Headers["Content-Length"] = request.Headers["Content-Length"]; // if you call OnResponse before subscribing to the request body, // 100-continue will not be sent before the response is sent. // per rfc2616 this response must have a 'final' status code, // but the server does not enforce it. response.OnResponse(headers, requestBody); } else if (request.Uri.StartsWith("/")) { var body = string.Format( "Hello world.\r\nHello.\r\n\r\nUri: {0}\r\nPath: {1}\r\nQuery:{2}\r\nFragment: {3}\r\n", request.Uri, request.Path, request.QueryString, request.Fragment); var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary<string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", body.Length.ToString() }, } }; response.OnResponse(headers, new BufferedProducer(body)); } else { var responseBody = "The resource you requested ('" + request.Uri + "') could not be found."; var headers = new HttpResponseHead() { Status = "404 Not Found", Headers = new Dictionary<string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", responseBody.Length.ToString() } } }; var body = new BufferedProducer(responseBody); response.OnResponse(headers, body); } }
private void ProcessClientAccessPolicyRequest(HttpRequestHead head, IDataProducer body, IHttpResponseDelegate response) { var silverlightCrossdomain = _corsValidator.GetSilverlightCrossDomainPolicy(); var responseHead = new HttpResponseHead() { Status = "200 OK", Headers = _corsValidator.AppendCorsHeaderDictionary( head, new Dictionary <string, string> { { "Content-Type", "text/xml" }, { "Content-Length", Encoding.UTF8.GetByteCount(silverlightCrossdomain).ToString() } } ) }; response.OnResponse(responseHead, new BufferedProducer(silverlightCrossdomain)); }
public void OnRequest(HttpRequestHead request, IDataProducer requestBody, IHttpResponseDelegate response) { var verror = "404 Not Found"; var errorString = "Not Found"; try { var path = request.Uri; if (path == "/api") { var method = request.Method; var stream = new MemoryStream(); if (method == "POST") { requestBody.Connect(new BufferedConsumer(bufStream => { HandleAPIRequest(bufStream, method, response); }, error => { Log.Error(error.ToString()); })); } else { HandleAPIRequest(stream, method, response); } return; } else if (path == "/status") { HandleStatusRequest(response); return; } else if (path.StartsWith("/touch/")) { HandleTouchRequest(path, response); return; } else if (path.StartsWith("/flag/")) { HandleFlagRequest(path, response); return; } } catch (Exception ex) { verror = "500 Internal Server Error"; Log.Error(ex.ToString()); errorString = ex.ToString(); } response.OnResponse(new HttpResponseHead() { Status = verror, Headers = new Dictionary <string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", errorString.Length.ToString() } } }, new BufferedProducer(errorString)); }
Action<ResultParameters, Exception> HandleResponse(IHttpResponseDelegate response) { return (result, error) => { if (error != null) { HandleError(response).Invoke(error); return; } if (result.Headers == null) { result.Headers = new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase); } if (result.Body != null && !result.Headers.ContainsKey("Content-Length") && !result.Headers.ContainsKey("Transfer-Encoding")) { // disable keep-alive in this case result.Headers["Connection"] = new[] { "close" }; } response.OnResponse(new HttpResponseHead() { Status = GetStatus(result), Headers = result.Headers.ToDictionary(kv => kv.Key, kv => string.Join("\r\n", kv.Value.ToArray()), StringComparer.OrdinalIgnoreCase), }, result.Body == null ? null : new DataProducer(result.Body)); }; }
public void Handle(string appname, string[] components, HttpRequestHead head, IDataProducer body, IHttpResponseDelegate response) { // Get a list of all of the files in the store for this application. Cache c = new Cache(false); IEnumerable <string> files = c.ListRecursive("server/" + appname + "/store"); // Create ZIP file and copy files into it. using (ZipFile zip = new ZipFile()) { // Add the files. foreach (string s in files) { ZipEntry e = zip.AddFile(c.GetFilePath("server/" + appname + "/store/" + s), this.GetDirectoryName(s)); e.Comment = "Added by Pivot.Server."; } // Add the README-UPDATES.txt file. zip.AddEntry("README-UPDATES.txt", @"About =============== This ZIP file was automatically generated by the Pivot.Update server. Refer to https://github.com/hach-que/Pivot.Update/ for more information. Usage Notice =============== The software contained in this ZIP file may use Pivot.Update to automatically update itself when new versions are released. In the event that it does, a UAC prompt may appear when the related Windows service first needs to be installed. This Windows service is responsible for automatically updating applications on a periodic basis; without this service, the associated software will not automatially update. "); zip.Comment = "ZIP file automatically generated by Pivot.Server."; using (MemoryStream output = new MemoryStream()) { zip.Save(output); // Send the ZIP file. response.OnResponse(new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary <string, string> { { "Content-Type", "application/zip" }, { "Content-Length", output.Length.ToString() }, { "Content-Disposition", "attachment; filename=\"" + appname + ".zip\"" }, { "Connection", "close" } } }, new BufferedProducer(output.ToArray())); } } }
public override void ProcessPost(HttpRequestHead request, IDataProducer requestBody, IHttpResponseDelegate response) { throw new NotImplementedException(); }
public void OnRequest(HttpRequestHead head, IDataProducer body, IHttpResponseDelegate response) { var kayak = new UserKayakAdapter(userCode, body, response); userCode.OnRequest(kayak, head); }
private static async void HandleRequest(HttpRequestHead request, IDataProducer body, IHttpResponseDelegate response, IRequestHandler handler) { _log.DebugFormat("Matched a handler {0}:{1} {2}", handler.Method, handler.Path, DumpQueryParams(handler.QueryParams)); if (handler.ResponseDelay > TimeSpan.Zero) { await Task.Delay(handler.ResponseDelay); } IDataProducer dataProducer = GetDataProducer(request, handler); if (request.HasBody()) { body.Connect(new BufferedConsumer( bufferedBody => { handler.RecordRequest(request, bufferedBody); _log.DebugFormat("Body: {0}", bufferedBody); response.OnResponse(handler.ResponseBuilder.BuildHeaders(), dataProducer); }, error => { _log.DebugFormat("Error while reading body {0}", error.Message); response.OnResponse(handler.ResponseBuilder.BuildHeaders(), dataProducer); } )); } else { response.OnResponse(handler.ResponseBuilder.BuildHeaders(), dataProducer); handler.RecordRequest(request, null); } _log.DebugFormat("End Processing request for : {0}:{1}", request.Method, request.Uri); }
private void ProcessFileNotFound(HttpRequestHead head, IDataProducer body, IHttpResponseDelegate response) { _parent._systemMetrics.LogCount("listeners.http.404"); var headers = new HttpResponseHead() { Status = "404 Not Found", Headers = _corsValidator.AppendCorsHeaderDictionary( head, new Dictionary <string, string> { { "Content-Type", "text/plain" }, { "Content-Length", Encoding.UTF8.GetByteCount("not found").ToString() } } ) }; response.OnResponse(headers, new BufferedProducer("not found")); }
public void OnRequest(HttpRequestHead request, IDataProducer requestBody, IHttpResponseDelegate response) { var status = "404 Not Found"; var body = new BufferedProducer($"The resource you requested ('{request.Uri}') could not be found."); try { foreach (var route in _routes) { if (request.Path == route.Key) { body = route.Value.Execute(request.QueryString); status = "200 OK"; break; } } } catch (Exception e) { status = "500 Internal Server Error"; var responseBody = $"The resource you requested ('{request.Uri}') produced an error: {e.Message}"; body = new BufferedProducer(responseBody); } var headers = new HttpResponseHead() { Status = status, Headers = new Dictionary <string, string>() { { "Content-Type", body.MimeType }, { "Content-Length", body.Size.ToString() }, } }; response.OnResponse(headers, body); }
public void OnRequest(HttpRequestHead request, IDataProducer requestBody, IHttpResponseDelegate response) { if (request.Uri == "/") { var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary<string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", "20" }, } }; var body = new BufferedProducer("Hello world.\r\nHello."); response.OnResponse(headers, body); } else if (request.Uri == "/bufferedecho") { // when you subecribe to the request body before calling OnResponse, // the server will automatically send 100-continue if the client is // expecting it. requestBody.Connect(new BufferedConsumer(bufferedBody => { var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary<string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", request.Headers["Content-Length"] }, { "Connection", "close" } } }; response.OnResponse(headers, new BufferedProducer(bufferedBody)); }, error => { // XXX // uh oh, what happens? })); } else if (request.Uri == "/echo") { var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary<string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", request.Headers["Content-Length"] }, { "Connection", "close" } } }; // if you call OnResponse before subscribing to the request body, // 100-continue will not be sent before the response is sent. // per rfc2616 this response must have a 'final' status code, // but the server does not enforce it. response.OnResponse(headers, requestBody); } else { var responseBody = "The resource you requested ('" + request.Uri + "') could not be found."; var headers = new HttpResponseHead() { Status = "404 Not Found", Headers = new Dictionary<string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", responseBody.Length.ToString() } } }; var body = new BufferedProducer(responseBody); response.OnResponse(headers, body); } }
public UserKayakAdapter(User userCode, IDataProducer requestBody, IHttpResponseDelegate responseDelegate) { this.userCode = userCode; this.requestBody = requestBody; this.responseDelegate = responseDelegate; }
private void ProcessOPTIONSRequest(HttpRequestHead head, IDataProducer body, IHttpResponseDelegate response) { var responseHead = new HttpResponseHead() { Status = "200 OK", Headers = _corsValidator.AppendCorsHeaderDictionary( head, new Dictionary <string, string> { { "Content-Type", "text/plain" }, { "Content-Length", "0" } }) }; response.OnResponse(responseHead, new EmptyResponse()); }
public void OnRequest(HttpRequestHead request, IDataProducer requestBody, IHttpResponseDelegate response) { if (request.Method.ToUpperInvariant() == "GET" && request.Uri.StartsWith("/next")) { // when you subscribe to the request body before calling OnResponse, // the server will automatically send 100-continue if the client is // expecting it. bool ret = MainWindow.Next(); var body = ret ? "Successfully skipped." : "You have to wait for 20 seconds to skip again."; var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary <string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", body.Length.ToString() }, } }; response.OnResponse(headers, new BufferedProducer(body)); } else if (request.Method.ToUpperInvariant() == "GET" && request.Uri.StartsWith("/pause")) { MainWindow.Pause(); var body = "Paused."; var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary <string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", body.Length.ToString() }, } }; response.OnResponse(headers, new BufferedProducer(body)); } else if (request.Method.ToUpperInvariant() == "GET" && request.Uri.StartsWith("/play")) { MainWindow.Play(); var body = "Playing."; var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary <string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", body.Length.ToString() }, } }; response.OnResponse(headers, new BufferedProducer(body)); } else if (request.Method.ToUpperInvariant() == "GET" && request.Uri.StartsWith("/toggleplaypause")) { var body = ""; if (MainWindow._player.Playing) { body = "Paused."; } else { body = "Playing."; } MainWindow.PlayPauseToggle(); var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary <string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", body.Length.ToString() }, } }; response.OnResponse(headers, new BufferedProducer(body)); } else if (request.Method.ToUpperInvariant() == "GET" && request.Uri.StartsWith("/like")) { MainWindow.Like(); var body = "Like"; if (MainWindow.GetCurrentSong().Loved) { body = "Liked"; } var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary <string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", body.Length.ToString() }, } }; response.OnResponse(headers, new BufferedProducer(body)); } else if (request.Method.ToUpperInvariant() == "GET" && request.Uri.StartsWith("/dislike")) { MainWindow.Dislike(); var body = "Disliked."; var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary <string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", body.Length.ToString() }, } }; response.OnResponse(headers, new BufferedProducer(body)); } else if (request.Method.ToUpperInvariant() == "GET" && request.Uri.StartsWith("/currentsong")) { Song s = MainWindow.GetCurrentSong(); var body = JsonConvert.SerializeObject(s); var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary <string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", body.Length.ToString() }, } }; response.OnResponse(headers, new BufferedProducer(body)); } else if (request.Method.ToUpperInvariant() == "GET" && request.Uri.StartsWith("/connect")) { var body = "true"; var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary <string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", body.Length.ToString() }, } }; response.OnResponse(headers, new BufferedProducer(body)); } else if (request.Uri.StartsWith("/")) { var body = string.Format( "Hello world.\r\nHello.\r\n\r\nUri: {0}\r\nPath: {1}\r\nQuery:{2}\r\nFragment: {3}\r\n", request.Uri, request.Path, request.QueryString, request.Fragment); var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary <string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", body.Length.ToString() }, } }; response.OnResponse(headers, new BufferedProducer(body)); } else { var responseBody = "The resource you requested ('" + request.Uri + "') could not be found."; var headers = new HttpResponseHead() { Status = "404 Not Found", Headers = new Dictionary <string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", responseBody.Length.ToString() } } }; var body = new BufferedProducer(responseBody); response.OnResponse(headers, body); } }
private void ProcessInternalServerError(HttpRequestHead head, IDataProducer body, IHttpResponseDelegate response) { _parent._systemMetrics.LogCount("listeners.http.500"); Respond(head, response, "500 Internal server error"); }
public void OnRequest(HttpRequestHead request, IDataProducer requestBody, IHttpResponseDelegate response) { var verror = "404 Not Found"; var errorString = "Not Found"; try { var path = request.Uri; if (path == "/servers") { HandleServersRequest(response); return; } if (path == "/api") { var method = request.Method; var stream = new MemoryStream(); if (method == "POST") { requestBody.Connect(new BufferedConsumer(bufferedBody => { var data = Encoding.UTF8.GetBytes(Encoding.UTF8.GetString(bufferedBody).Split(new[] { "\r\n\r\n" }, 2, StringSplitOptions.RemoveEmptyEntries)[1]); stream.Write(data, 0, data.Length); stream.Position = 0; HandleAPIRequest(stream, method, response); }, error => { Log.Error(error.ToString()); })); } else { HandleAPIRequest(stream, method, response); } return; } } catch (Exception ex) { verror = "500 Internal Server Error"; Log.Error(ex.ToString()); errorString = ex.ToString(); } response.OnResponse(new HttpResponseHead() { Status = verror, Headers = new Dictionary <string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", errorString.Length.ToString() } } }, new BufferedProducer(errorString)); }
private void ProcessPOSTRequest(HttpRequestHead head, IDataProducer body, IHttpResponseDelegate response) { body.Connect(new BufferedConsumer( (payload) => { try { _parent._systemMetrics.LogCount("listeners.http.bytes", Encoding.UTF8.GetByteCount(payload)); // Further split by ',' to match the GET while keeping backward compatibility and allowing you to use the join for both methods. var lines = payload.Replace("\r", "") .Split(new char[] { '\n', ',' }, StringSplitOptions.RemoveEmptyEntries); for (var index = 0; index < lines.Length; index++) { _parent._target.Post(lines[index]); } _parent._systemMetrics.LogCount("listeners.http.lines", lines.Length); Respond(head, response, "200 OK"); } catch { Respond(head, response, "400 bad request"); } }, (error) => { Respond(head, response, "500 Internal server error"); })); }
private void ProcessLoadBalancerRequest(IDataProducer body, IHttpResponseDelegate response) { _parent._systemMetrics.LogCount("listeners.http.loadbalancer"); Respond(response, "200 OK"); }
ResultDelegate HandleResponse(IHttpResponseDelegate response) { return (status, headers, body) => { if (headers == null) headers = new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase); if (body != null && !headers.ContainsKey("Content-Length") && !headers.ContainsKey("Transfer-Encoding")) { // disable keep-alive in this case headers["Connection"] = new[] {"close"}; } response.OnResponse(new HttpResponseHead() { Status = status, Headers = headers.ToDictionary(kv => kv.Key, kv => string.Join("\r\n", kv.Value.ToArray()), StringComparer.OrdinalIgnoreCase), }, body == null ? null : new DataProducer(body)); }; }