private void MethodNotAllowed(HttpEntity httpEntity, string[] allowed)
        {
            var entity = httpEntity.CreateManager(Codec.NoCodec, Codec.NoCodec, allowed, _ => { });

            entity.ReplyStatus(HttpStatusCode.MethodNotAllowed, "Method Not Allowed",
                               e => Log.ErrorException(e, "Error while closing http connection (http service core)."));
        }
Example #2
0
            public static string ReadStreamEventsBackwardCompletedFeed(HttpEntity entity, Message message, int start, int count)
            {
                Debug.Assert(message.GetType() == typeof(ClientMessage.ReadStreamEventsBackwardCompleted));

                var completed = message as ClientMessage.ReadStreamEventsBackwardCompleted;

                if (completed != null)
                {
                    switch (completed.Result)
                    {
                    case RangeReadResult.Success:
                        var updateTime = completed.Events.Length != 0
                                                 ? completed.Events[0].Event.TimeStamp
                                                 : DateTime.MinValue.ToUniversalTime();
                        //TODO TR: avoid completed.Events copying ToArray
                        return(entity.ResponseCodec.To(Convert.ToFeed(completed.EventStreamId,
                                                                      start,
                                                                      count,
                                                                      updateTime,
                                                                      completed.Events.Select(x => x.Event).ToArray(),
                                                                      Convert.ToEntry,
                                                                      entity.UserHostName)));

                    case RangeReadResult.NoStream:
                    case RangeReadResult.StreamDeleted:
                        return(string.Empty);

                    default:
                        throw new ArgumentOutOfRangeException();
                    }
                }
                return(string.Empty);
            }
        private void BadCodec(HttpEntity httpEntity, string reason)
        {
            var entity = httpEntity.CreateManager();

            entity.ReplyStatus(HttpStatusCode.NotAcceptable, reason,
                               e => Log.Debug("Error while closing HTTP connection (HTTP service core): {e}.", e.Message));
        }
        private void NotFound(HttpEntity httpEntity)
        {
            var entity = httpEntity.CreateManager();

            entity.ReplyStatus(HttpStatusCode.NotFound, "Not Found",
                               e => Log.Debug("Error while closing HTTP connection (HTTP service core): {e}.", e.Message));
        }
        private void InternalServerError(HttpEntity httpEntity)
        {
            var entity = httpEntity.CreateManager();

            entity.ReplyStatus(HttpStatusCode.InternalServerError, "Internal Server Error",
                               e => Log.Debug("Error while closing HTTP connection (HTTP service core): {e}.", e.Message));
        }
        private void RespondWithOptions(HttpEntity httpEntity, string[] allowed)
        {
            var entity = httpEntity.CreateManager(Codec.NoCodec, Codec.NoCodec, allowed, _ => { });

            entity.ReplyStatus(HttpStatusCode.OK, "OK",
                               e => Log.Debug("Error while closing HTTP connection (http service core): {e}.", e.Message));
        }
        private void MethodNotAllowed(HttpEntity httpEntity, string[] allowed)
        {
            var entity = httpEntity.CreateManager(Codec.NoCodec, Codec.NoCodec, allowed, _ => { });

            entity.ReplyStatus(HttpStatusCode.MethodNotAllowed, "Method Not Allowed",
                               e => Log.Debug("Error while closing HTTP connection (HTTP service core): {e}.", e.Message));
        }
Example #8
0
        private void OnGetFreshStats(HttpEntity entity, UriTemplateMatch match)
        {
            var envelope = new SendToHttpEnvelope(
                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))
            {
                base.SendBadRequest(entity, "Dynamic stats selection works only with grouping enabled");
                return;
            }

            Publish(new MonitoringMessage.GetFreshStats(envelope, statSelector, useMetadata, useGrouping));
        }
Example #9
0
        /// <summary>Read the contents of an entity and return it as a byte array.</summary>
        /// <remarks>Read the contents of an entity and return it as a byte array.</remarks>
        /// <param name="entity">the entity to read from=</param>
        /// <returns>
        /// byte array containing the entity content. May be null if
        /// <see cref="Org.Apache.Http.HttpEntity.GetContent()">Org.Apache.Http.HttpEntity.GetContent()
        ///     </see>
        /// is null.
        /// </returns>
        /// <exception cref="System.IO.IOException">if an error occurs reading the input stream
        ///     </exception>
        /// <exception cref="System.ArgumentException">if entity is null or if content length &gt; Integer.MAX_VALUE
        ///     </exception>
        public static byte[] ToByteArray(HttpEntity entity)
        {
            Args.NotNull(entity, "Entity");
            InputStream instream = entity.GetContent();

            if (instream == null)
            {
                return(null);
            }
            try
            {
                Args.Check(entity.GetContentLength() <= int.MaxValue, "HTTP entity too large to be buffered in memory"
                           );
                int i = (int)entity.GetContentLength();
                if (i < 0)
                {
                    i = 4096;
                }
                ByteArrayBuffer buffer = new ByteArrayBuffer(i);
                byte[]          tmp    = new byte[4096];
                int             l;
                while ((l = instream.Read(tmp)) != -1)
                {
                    buffer.Append(tmp, 0, l);
                }
                return(buffer.ToByteArray());
            }
            finally
            {
                instream.Close();
            }
        }
Example #10
0
 private void OnPostShutdown(HttpEntity entity, UriTemplateMatch match)
 {
     Publish(new ClientMessage.RequestShutdown());
     entity.Manager.Reply(HttpStatusCode.OK,
                          "OK",
                          e => Log.ErrorException(e, "Error while closing http connection (admin controller)"));
 }
Example #11
0
        private void RequestReceived(HttpAsyncServer sender, HttpListenerContext context)
        {
            var entity = new HttpEntity(context.Request, context.Response, context.User, _logHttpRequests,
                                        _advertiseAsAddress, _advertiseAsPort);

            _requestsMultiHandler.Handle(new IncomingHttpRequestMessage(this, entity, _requestsMultiHandler));
        }
Example #12
0
        //$ALL

        private void OnGetAllBefore(HttpEntity entity, UriTemplateMatch match)
        {
            var p = match.BoundVariables["pos"];
            var c = match.BoundVariables["count"];

            TFPos position;
            int   count;

            if (!string.IsNullOrEmpty(p))
            {
                if (!TFPos.TryParse(p, out position))
                {
                    SendBadRequest(entity, string.Format("Invalid position argument : {0}", p));
                }
            }
            else
            {
                position = TFPos.Invalid;
            }

            if (!string.IsNullOrEmpty(c))
            {
                if (!int.TryParse(c, out count))
                {
                    SendBadRequest(entity, string.Format("Invalid count argument : {0}", c));
                }
            }
            else
            {
                count = AtomSpecs.FeedPageSize;
            }

            _allEventsController.GetAllBefore(entity, position, count);
        }
        private void BadContentType(HttpEntity httpEntity, string reason)
        {
            var entity = httpEntity.CreateManager();

            entity.ReplyStatus(HttpStatusCode.UnsupportedMediaType, reason,
                               e => Log.Debug("Error while closing HTTP connection (HTTP service core): {e}.", e.Message));
        }
 private IEnvelope ErrorsEnvelope(HttpEntity http)
 {
     return(new SendToHttpEnvelope <ProjectionManagementMessage.NotFound>(
                http, NotFoundFormatter, NotFoundConfigurator,
                new SendToHttpEnvelope <ProjectionManagementMessage.OperationFailed>(
                    http, OperationFailedFormatter, OperationFailedConfigurator, null)));
 }
        private void NotFound(HttpEntity httpEntity)
        {
            var entity = httpEntity.CreateManager();

            entity.ReplyStatus(HttpStatusCode.NotFound, "Not Found",
                               e => Log.ErrorException(e, "Error while closing http connection (http service core)."));
        }
        private void RespondWithOptions(HttpEntity httpEntity, string[] allowed)
        {
            var entity = httpEntity.CreateManager(Codec.NoCodec, Codec.NoCodec, allowed, _ => { });

            entity.ReplyStatus(HttpStatusCode.OK, "OK",
                               e => Log.ErrorException(e, "Error while closing http connection (http service core)."));
        }
Example #17
0
 public SendToHttpWithConversionEnvelope(HttpEntity entity, Func <ICodec, TExpectedHttpFormattedResponseMessage, string> formatter, Func <ICodec, TExpectedHttpFormattedResponseMessage, ResponseConfiguration> configurator, Func <TExpectedResponseMessage, TExpectedHttpFormattedResponseMessage> convertor, IEnvelope nonMatchingEnvelope = null)
 {
     _formatter    = formatter;
     _configurator = configurator;
     _convertor    = convertor;
     _httpEnvelope = new SendToHttpEnvelope <TExpectedResponseMessage>(entity, Formatter, Configurator, nonMatchingEnvelope);
 }
        private void OnProjectionStateGet(HttpEntity http, UriTemplateMatch match)
        {
            var envelope = new SendToHttpEnvelope <ProjectionManagementMessage.ProjectionState>(
                http, StateFormatter, StateConfigurator, ErrorsEnvelope(http));

            this.Publish(new ProjectionManagementMessage.GetState(envelope, match.BoundVariables["name"]));
        }
Example #19
0
		public override void SendRequestHeaderAndEntity(HttpRequest request, HttpEntity httpEntity, bool expectContinue)
		{
			RequestInitiated = request.Initiated;
			RequestTimeout = request.Timeout;

			if (!this.IsConnected())
			{
				throw new HttpNetworkException("Tls client is closed or not ready (SendRequestHeaderAndEntity)");
			}
			byte[] header = Encoding.ASCII.GetBytes(GetRequestHeader(request).ToString());

			_tlsClient.Send(header);

			if (expectContinue)
			{
				WaitForDataToArrive(2 * 1000);
				if (_tlsClient.Available > 0)
				{
					// now read the 100-continue response
					HttpResponse response = ReceiveResponseHeaders();
					if (response.ResponseCode != 100)
					{
						throw new HttpNetworkException("response returned before entity was sent, but it is not 100-continue");
					}
				}
			}

			byte[] body = httpEntity.Content;
			_tlsClient.Send(body);
		}
        private void OnGetFeedPage(HttpEntity entity, UriTemplateMatch match)
        {
            var stream = match.BoundVariables["stream"];
            var start  = match.BoundVariables["start"];
            var count  = match.BoundVariables["count"];

            int startIdx;
            int cnt;

            if (string.IsNullOrEmpty(stream))
            {
                SendBadRequest(entity, String.Format("Invalid stream name '{0}'", stream));
                return;
            }
            if (!int.TryParse(start, out startIdx) || startIdx < -1)
            {
                SendBadRequest(entity, String.Format("'{0}' is not valid start index", start));
                return;
            }
            if (!int.TryParse(count, out cnt) || cnt <= 0)
            {
                SendBadRequest(entity, String.Format("'{0}' is not valid count. Should be positive integer", count));
                return;
            }

            OnGetFeedCore(entity, stream, startIdx, cnt);
        }
        private void OnProjectionDelete(HttpEntity http, UriTemplateMatch match)
        {
            var envelope = new SendToHttpEnvelope <ProjectionManagementMessage.Updated>(
                http, DefaultFormatter, OkResponseConfigurator, ErrorsEnvelope(http));

            this.Publish(new ProjectionManagementMessage.Delete(envelope, match.BoundVariables["name"]));
        }
Example #22
0
        public static ResponseConfiguration ReadEventCompleted(HttpEntity entity, Message message)
        {
            Debug.Assert(message.GetType() == typeof(ClientMessage.ReadEventCompleted));

            var completed = message as ClientMessage.ReadEventCompleted;

            if (completed == null)
            {
                return(InternalServerEror(entity, message));
            }

            switch (completed.Result)
            {
            case SingleReadResult.Success:
                return(new ResponseConfiguration(HttpStatusCode.OK,
                                                 "OK",
                                                 entity.ResponseCodec.ContentType,
                                                 new KeyValuePair <string, string>(
                                                     "Cache-Control",
                                                     string.Format("max-age={0}", MaxPossibleAge))));

            case SingleReadResult.NotFound:
            case SingleReadResult.NoStream:
                return(NotFound(entity, completed));

            case SingleReadResult.StreamDeleted:
                return(Gone(entity, completed));

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Example #23
0
        public static ResponseConfiguration ReadEventsFromEndCompleted(HttpEntity entity, Message message)
        {
            Debug.Assert(message.GetType() == typeof(ClientMessage.ReadEventsBackwardsCompleted));

            var completed = message as ClientMessage.ReadEventsBackwardsCompleted;

            if (completed == null)
            {
                return(InternalServerEror(entity, message));
            }

            var startIdx = (int)entity.Manager.AsyncState;
            var age      = startIdx < AtomSpecs.FeedPageSize ? MinPossibleAge : MaxPossibleAge;

            switch (completed.Result)
            {
            case RangeReadResult.Success:
                return(new ResponseConfiguration(HttpStatusCode.OK,
                                                 "OK",
                                                 entity.ResponseCodec.ContentType,
                                                 new KeyValuePair <string, string>(
                                                     "Cache-Control",
                                                     string.Format("max-age={0}", age))));

            case RangeReadResult.NoStream:
                return(NotFound(entity, completed));

            case RangeReadResult.StreamDeleted:
                return(Gone(entity, completed));

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Example #24
0
        public static ResponseConfiguration ReadEventCompleted(HttpEntity entity, Message message)
        {
            Debug.Assert(message.GetType() == typeof(ClientMessage.ReadEventCompleted));

            var completed = message as ClientMessage.ReadEventCompleted;

            if (completed == null)
            {
                return(InternalServerEror(entity, message));
            }

            switch (completed.Result)
            {
            case SingleReadResult.Success:
                return(OkCache(entity, message, MaxPossibleAge));

            case SingleReadResult.NotFound:
            case SingleReadResult.NoStream:
                return(NotFound(entity, completed));

            case SingleReadResult.StreamDeleted:
                return(Gone(entity, completed));

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Example #25
0
        public static ResponseConfiguration DeleteStreamCompleted(HttpEntity entity, Message message)
        {
            Debug.Assert(message.GetType() == typeof(ClientMessage.DeleteStreamCompleted));

            var completed = message as ClientMessage.DeleteStreamCompleted;

            if (completed == null)
            {
                return(InternalServerEror(entity, message));
            }

            switch (completed.ErrorCode)
            {
            case OperationErrorCode.Success:
                return(new ResponseConfiguration(HttpStatusCode.NoContent, "Stream deleted", null));

            case OperationErrorCode.PrepareTimeout:
            case OperationErrorCode.CommitTimeout:
            case OperationErrorCode.ForwardTimeout:
                return(new ResponseConfiguration(HttpStatusCode.InternalServerError, "Delete timeout", null));

            case OperationErrorCode.WrongExpectedVersion:
            case OperationErrorCode.StreamDeleted:
            case OperationErrorCode.InvalidTransaction:
                return(new ResponseConfiguration(HttpStatusCode.BadRequest,
                                                 string.Format("Error code : {0}. Reason : {1}", completed.ErrorCode, completed.Error),
                                                 null));

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
        private void ProjectionsPost(HttpEntity http, UriTemplateMatch match, ProjectionMode mode, string name)
        {
            var envelope = new SendToHttpEnvelope <ProjectionManagementMessage.Updated>(
                http, DefaultFormatter, (codec, message) =>
            {
                var localPath = string.Format("/projection/{0}", message.Name);
                var url       = MakeUrl(match, localPath);
                return(new ResponseConfiguration(
                           201, "Created", codec.ContentType, new KeyValuePair <string, string>("Location", url)));
            }, ErrorsEnvelope(http));

            http.Manager.ReadRequestAsync(
                (o, s) =>
            {
                ProjectionManagementMessage.Post postMessage;
                string handlerType = match.BoundVariables["type"] ?? "JS";
                if ((mode == ProjectionMode.OneTime || mode == ProjectionMode.AdHoc) &&
                    string.IsNullOrEmpty(name))
                {
                    postMessage = new ProjectionManagementMessage.Post(
                        envelope, mode, Guid.NewGuid().ToString("D"), handlerType, s, enabled: true);
                }
                else
                {
                    postMessage = new ProjectionManagementMessage.Post(envelope, mode, name, handlerType, s, enabled: true);
                }
                this.Publish(postMessage);
            }, Console.WriteLine);
        }
Example #27
0
        public AspNetResponse(HttpContext context)
        {
            NativeContext = context;
            Headers       = new HttpHeaderDictionary();
            Entity        = new HttpEntity(Headers, NativeContext.Response.OutputStream);
//      context.Response.AddOnSendingHeaders(httpContext => _nativeHeadersSent = true);
        }
        private void BadContentType(HttpEntity httpEntity, string reason)
        {
            var entity = httpEntity.CreateManager();

            entity.ReplyStatus(HttpStatusCode.UnsupportedMediaType, reason,
                               e => Log.ErrorException(e, "Error while closing http connection (http service core)."));
        }
        private void BadCodec(HttpEntity httpEntity, string reason)
        {
            var entity = httpEntity.CreateManager();

            entity.ReplyStatus(HttpStatusCode.NotAcceptable, reason,
                               e => Log.ErrorException(e, "Error while closing http connection (http service core)."));
        }
        private void InternalServerError(HttpEntity httpEntity)
        {
            var entity = httpEntity.CreateManager();

            entity.ReplyStatus(HttpStatusCode.InternalServerError, "Internal Server Error",
                               e => Log.ErrorException(e, "Error while closing http connection (http service core)."));
        }
Example #31
0
        public Ret <Entity> ExecuteAndRenderResult(HttpContext httpContext)
        {
            var action = (string)httpContext.Request.Query["action"];

            if (string.IsNullOrWhiteSpace(action))
            {
                var self   = httpContext.Request.GetRequestUri();
                var entity = HttpEntity.Create(self, HttpStatusCode.BadRequest,
                                               $"Nenhuma ação foi indicada. Faltou definir o parâmetro \"action\"?"
                                               );
                return(entity);
            }

            var method = PaperType.GetMethodIgnoreCase(action);

            if (method == null)
            {
                var self   = httpContext.Request.GetRequestUri();
                var entity = HttpEntity.Create(self, HttpStatusCode.NotImplemented,
                                               $"A ação solicitada não está disponível: \"{action}\""
                                               );
                return(entity);
            }

            return(ExecuteMethod(httpContext, method));
        }
 public static string ToString(HttpEntity entity)
 {
     if (entity != null
         && entity.Content != null)
     {
         return HTTPProtocol.GetEncoding(entity.ContentType).GetString(entity.Content);
     }
     else
         return string.Empty;
 }
Example #33
0
		public abstract void SendRequestHeaderAndEntity(HttpRequest request, HttpEntity httpEntity, bool expectContinue);
        public void PostJsonForMessage()
        {
            template.MessageConverters.Add(new StringHttpMessageConverter());

            HttpEntity entity = new HttpEntity("{\"Name\":\"Lisa Baia\"}");
            entity.Headers.ContentType = MediaType.APPLICATION_JSON;

            HttpResponseMessage result = template.PostForMessage("user", entity);
            Assert.AreEqual(new Uri(new Uri(uri), "/user/3"), result.Headers.Location, "Invalid location");
            Assert.AreEqual(HttpStatusCode.Created, result.StatusCode, "Invalid status code");
            Assert.AreEqual("User id '3' created with 'Lisa Baia'", result.StatusDescription, "Invalid status description");
        }
        public void WriteMultipartWithIResource()
        {
            string fileToUpload = Path.Combine(Environment.CurrentDirectory, @"Http\Converters\FileToUpload.png");

            IDictionary<string, object> parts = new Dictionary<string, object>();
            parts.Add("name 1", "value 1");
            parts.Add("name 2", "value 2+1");
            HttpEntity entity = new HttpEntity("<root><child/></root>");
            entity.Headers.ContentType = MediaType.TEXT_XML;
            parts.Add("xml", entity);
            parts.Add("logo", new FileResource(fileToUpload));

            MockHttpOutputMessage message = new MockHttpOutputMessage();

            converter.Write(parts, MediaType.MULTIPART_FORM_DATA, message);

            MediaType contentType = message.Headers.ContentType;
            Assert.IsNotNull(contentType, "Invalid content-type");
            Assert.AreEqual("multipart", contentType.Type, "Invalid content-type");
            Assert.AreEqual("form-data", contentType.Subtype, "Invalid content-type");
            string boundary = contentType.GetParameter("boundary");
            Assert.IsNotNull(boundary, "Invalid content-type");

            string result = message.GetBodyAsString(Encoding.UTF8);
            Assert.IsTrue(result.Contains("--" + boundary + "\r\nContent-Disposition: form-data; name=\"name 1\"\r\nContent-Type: text/plain;charset=ISO-8859-1\r\n\r\nvalue 1\r\n"), "Invalid content-disposition");
            Assert.IsTrue(result.Contains("--" + boundary + "\r\nContent-Disposition: form-data; name=\"name 2\"\r\nContent-Type: text/plain;charset=ISO-8859-1\r\n\r\nvalue 2+1\r\n"), "Invalid content-disposition");
            Assert.IsTrue(result.Contains("--" + boundary + "\r\nContent-Disposition: form-data; name=\"xml\"\r\nContent-Type: text/xml\r\n\r\n<root><child/></root>\r\n"), "Invalid content-disposition");
            Assert.IsTrue(result.Contains("--" + boundary + "\r\nContent-Disposition: form-data; name=\"logo\"; filename=\"FileToUpload.png\"\r\nContent-Type: image/png\r\n\r\n"), "Invalid content-disposition");
        }
        public void SendRequestHeaderAndEntity(HttpRequest request, HttpEntity httpEntity, bool expectContinue)
        {
            if (!this.IsConnected())
            {
                throw new HttpNetworkException("Socket is closed or not ready");
            }
            byte[] header = Encoding.ASCII.GetBytes(GetRequestHeader(request).ToString());
            byte[] body = httpEntity.Content;

            // first send the headers
            Send(header, 0, header.Length, this.m_timeout);

            // then look for 100-continue response for no more than 2 seconds
            if (expectContinue)
            {
                // 2 seconds timeout for 100-continue
                WaitForDataToArriveAtSocket(2 * 1000);
                if (this.m_socket.Available > 0)
                {
                    // now read the 100-continue response
                    HttpResponse response = ReceiveResponseHeaders();
                    if (response.ResponseCode != 100)
                    {
                        throw new HttpNetworkException("reponse returned before entity was sent, but it is not 100-continue");
                    }
                }
            }

            byte[] message = body;

            int sendBufferSize = this.m_socket.SendBufferSize;
            int size = (message.Length > sendBufferSize) ? sendBufferSize : message.Length;
            for (int i = 0; i < message.Length; i = i + size)
            {
                int remaining = (size < (message.Length - i)) ? size : (message.Length - i);
                Send(message, i, remaining, this.m_timeout);
            }
        }