public static void ThrowExceptionIfErrorStatusCode(HttpStatusCode httpStatusCode, string message)
        {
            if (httpStatusCode != HttpStatusCode.OK && httpStatusCode != HttpStatusCode.Created)
            {
                switch (httpStatusCode)
                {
                case HttpStatusCode.Unauthorized:
                    throw new AuthenticationException();

                case HttpStatusCode.Forbidden:
                    throw new AuthorizationException(message);

                case HttpStatusCode.NotFound:
                    throw new NotFoundException();

                case HttpStatusCode.InternalServerError:
                    throw new ServerException();

                case HttpStatusCode.ServiceUnavailable:
                    throw new DownForMaintenanceException();

                case (HttpStatusCode)429:
                    throw new TooManyRequestsException();

                case (HttpStatusCode)426:
                    throw new UpgradeRequiredException();

                default:
                    var exception = new UnexpectedException();
                    exception.Source = "Unexpected HTTP_RESPONSE " + httpStatusCode;
                    throw exception;
                }
            }
        }
Пример #2
0
 private void EnsureRoute(string queue, string exchange, string routingKey)
 {
     try
     {
         this.channel.QueueDeclare(queue: queue, durable: true, exclusive: false, autoDelete: false, arguments: null);
         this.channel.ExchangeDeclare(exchange: exchange, type: "topic");
         this.channel.QueueBind(queue: queue, exchange: exchange, routingKey: routingKey);
     }
     catch (Exception e)
     {
         var custom = new UnexpectedException(e);
         Logger.Fatal("Unexpected error occured while channel create", custom);
         throw custom;
     }
 }
Пример #3
0
        private void PublishMessage <T>(IBasicProperties basicProperties, string exchange, string routingKey, RabbitMQWrapperMessage <T> message)
        {
            var serializer = RabbitMQWrapperConnection.DefaultAdapter;
            var body       = serializer.SerializeBytes(message);

            try
            {
                channel.BasicPublish(exchange: exchange, routingKey: routingKey, basicProperties: basicProperties, body: body);
            }
            catch (Exception e)
            {
                var custom = new UnexpectedException(e);
                Logger.Fatal("Unexpected error occured while publishing the message", custom);
                throw custom;
            }
        }
Пример #4
0
        public ErrorDetails Error()
        {
            var context   = HttpContext.Features.Get <IExceptionHandlerFeature>();
            var exception = context?.Error;

            var code = exception switch
            {
                ValidationException _ => 400,
                ResourcesNotFoundException _ => 404,
                UnexpectedException _ => 500,
                _ => 500,
            };

            Response.StatusCode = code;
            if (code == 500)
            {
                _logger.Error(exception?.Message, exception);
            }
            return(code == 500 ? new ErrorDetails("Unexpected error. Contact with Administrator.", code) : new ErrorDetails(exception, code));
        }
Пример #5
0
        public static void ThrowExceptionIfErrorStatusCode(HttpStatusCode httpStatusCode, string message)
        {
            if (httpStatusCode != HttpStatusCode.OK && httpStatusCode != HttpStatusCode.Created)
            {
                switch ((int)httpStatusCode)
                {
                case 401:
                    throw new AuthenticationException();

                case 403:
                    throw new AuthorizationException(message);

                case 404:
                    throw new NotFoundException();

                case 408:
                    throw new RequestTimeoutException();

                case 426:
                    throw new UpgradeRequiredException();

                case 429:
                    throw new TooManyRequestsException();

                case 500:
                    throw new ServerException();

                case 503:
                    throw new ServiceUnavailableException();

                case 504:
                    throw new GatewayTimeoutException();

                default:
                    var exception = new UnexpectedException();
                    exception.Source = "Unexpected HTTP_RESPONSE " + httpStatusCode;
                    throw exception;
                }
            }
        }
        /// <summary>
        /// Handles remote methods.
        ///
        /// </summary>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: private Object invokeRemoteMethod(Object proxy, Method method, Object[] args) throws Exception
        private Object InvokeRemoteMethod(Object proxy, Method method, Object[] args)
        {
            try
            {
                if (!(proxy is Remote))
                {
                    throw new IllegalArgumentException("proxy not Remote instance");
                }
                return(@ref.Invoke((Remote)proxy, method, args, GetMethodHash(method)));
            }
            catch (Exception e)
            {
                if (!(e is RuntimeException))
                {
                    Class cl = proxy.GetType();
                    try
                    {
                        method = cl.GetMethod(method.Name, method.ParameterTypes);
                    }
                    catch (NoSuchMethodException nsme)
                    {
                        throw (IllegalArgumentException)(new IllegalArgumentException()).InitCause(nsme);
                    }
                    Class thrownType = e.GetType();
                    foreach (Class declaredType in method.ExceptionTypes)
                    {
                        if (thrownType.IsSubclassOf(declaredType))
                        {
                            throw e;
                        }
                    }
                    e = new UnexpectedException("unexpected exception", e);
                }
                throw e;
            }
        }
Пример #7
0
        private async void HandleClient(Socket partner)
        {
            try
            {
                Stream readStream;
                using (var writeStream = MakeSaneNetworkStream(partner, out readStream))
                    using (var reader = new HttpRequestReaderStream(readStream))
                        using (var writer = new StreamWriter(writeStream, new UTF8Encoding(false), 4096)
                        {
                            NewLine = "\r\n", AutoFlush = false
                        })
                        {
                            var headers = new List <HttpHeader>();
                            while (true)
                            {
                                var questing = new StringSegment(await reader.ReadLineAsync());
                                if (questing.Empty)
                                {
                                    break;
                                }

                                headers.Clear();
                                while (true)
                                {
                                    var header = await reader.ReadLineAsync();

                                    if (String.IsNullOrEmpty(header))
                                    {
                                        break;
                                    }

                                    var colon = header.IndexOf(':');
                                    var name  = header.Substring(0, colon);
                                    var value = header.Substring(colon + 2); // skip colon + space

                                    headers.Add(new HttpHeader {
                                        Name = name.ToLowerInvariant(), Value = value
                                    });
                                }

                                var space1 = questing.IndexOf(' ');
                                var space2 = questing.IndexOf(' ', space1 + 1); // if space1 is -1 this is fine as well

                                if ((space1 > 0) && (space2 > 0))
                                {
                                    var method  = questing.Substring(0, space1);
                                    var path    = questing.Substring(space1 + 1, space2 - space1 - 1);
                                    var version = questing.Substring(space2 + 1);
                                    if (version == "HTTP/1.1" && path[0] == '/')
                                    {
                                        path = path.Substring(1);

                                        HttpMethod?prettyMethod = null;
                                        bool       hasBody      = false;
                                        if (method == "GET")
                                        {
                                            prettyMethod = HttpMethod.Get;
                                        }
                                        else if (method == "POST")
                                        {
                                            prettyMethod = HttpMethod.Post;
                                            hasBody      = true;
                                        }

                                        if (prettyMethod.HasValue)
                                        {
                                            var request = new HttpRequest(prettyMethod.Value, path, headers, Encoding.UTF8, this);

                                            bool isWebSocket = false;
                                            if (hasBody)
                                            {
                                                int bodyLength;
                                                if (!int.TryParse(request.GetHeader("content-length"), out bodyLength))
                                                {
                                                    throw new InvalidOperationException("Request has body but no content-length given!");
                                                }

                                                // read body into byte array (not sure about this tho)
                                                var body = new byte[bodyLength];
                                                int read = 1337;
                                                for (int i = 0; (i < body.Length) && (read != 0); i += read)
                                                {
                                                    read = await reader.ReadAsync(body, i, body.Length - i);
                                                }
                                                request.Body = body;
                                            }
                                            else if (prettyMethod == HttpMethod.Get)
                                            {
                                                var connection = request.GetHeader("connection")?.ToLowerInvariant();
                                                isWebSocket = connection == "upgrade" || connection == "websocket";
                                            }

                                            var response = await RoutingManager.DispatchRequest(request);

                                            if (response.WebSocketHandler != null)
                                            {
                                                if (!isWebSocket)
                                                {
                                                    throw new InvalidOperationException("WebSocket provided but not requested.");
                                                }

                                                await HandleWebSocket(partner, readStream, writer, response.WebSocketHandler, request);

                                                return;
                                            }

                                            await writer.WriteLineAsync(StatusStrings[(int)response.Status]);

                                            await writer.WriteLineAsync(ServerHeader);

                                            if (response.ContentType != ContentType.Custom)
                                            {
                                                await writer.WriteAsync("Content-Type: ");

                                                await writer.WriteLineAsync(ContentTypeStrings[(int)response.ContentType]);
                                            }

                                            if (response.ExtraHeaders != null)
                                            {
                                                foreach (var header in response.ExtraHeaders)
                                                {
                                                    await writer.WriteAsync(header.Name);

                                                    await writer.WriteAsync(": ");

                                                    await writer.WriteLineAsync(header.Value);
                                                }
                                            }

                                            await writer.WriteAsync("Content-Length: ");

                                            await writer.WriteLineAsync(response.Content.Count.ToString());

                                            await writer.WriteLineAsync();

                                            // This flushes the BufferedStream as well which is NOT what we want.
                                            // Solving this would require us to either reimplement StreamWriter or
                                            // to wrap the BufferedStream in another Stream (because it's sealed).
                                            // Worth it? I don't know.
                                            await writer.FlushAsync();

                                            await writeStream.WriteAsync(response.Content.Array, response.Content.Offset, response.Content.Count);

                                            await writeStream.FlushAsync();

                                            // All is well - we can loop (keepalive).
                                            continue;
                                        }
                                    }
                                }

                                // If we reach this, something is weird/wrong.
                                // "Bye, have a great day!"
                                await writer.WriteLineAsync(StatusStrings[(int)HttpStatus.BadRequest]);

                                await writer.WriteLineAsync(ServerHeader);

                                await writer.WriteLineAsync("Connection: close");

                                await writer.WriteLineAsync();

                                await writer.FlushAsync();

                                return;
                            }
                        }
            }
            catch (Exception e)
            {
                UnexpectedException?.Invoke(e);
            }
        }
        public static void ThrowExceptionIfErrorStatusCode(HttpStatusCode httpStatusCode, string message)
        {
            if (httpStatusCode != HttpStatusCode.OK && httpStatusCode != HttpStatusCode.Created)
            {
                switch (httpStatusCode)
                {
                    case HttpStatusCode.Unauthorized:
                        throw new AuthenticationException();
                    case HttpStatusCode.Forbidden:
                        throw new AuthorizationException(message);
                    case HttpStatusCode.NotFound:
                        throw new NotFoundException();
                    case HttpStatusCode.InternalServerError:
                        throw new ServerException();
                    case HttpStatusCode.ServiceUnavailable:
                        throw new DownForMaintenanceException();
                    case (HttpStatusCode) 426:
                        throw new UpgradeRequiredException();
                    default:
						var exception = new UnexpectedException();
						exception.Source = "Unexpected HTTP_RESPONSE " + httpStatusCode;
                        throw exception;
                }
            }
        }
Пример #9
0
        /// <summary>
        /// Invokes application defined unexpected exception handler. See <see cref="UnexpectedException"/>
        /// </summary>
        public static bool HandleUnexpectedException(Exception ex)
        {
            UnexpectedException?.Invoke(ex);

            return(false);
        }
Пример #10
0
        private async void HandleClient(Socket partner)
        {
            var receiveTimer = Stopwatch.StartNew();
            var receivedAt   = DateTime.Now;

            try
            {
                Stream readStream;
                using (var writeStream = MakeSaneNetworkStream(partner, out readStream))
                    using (var reader = new HttpRequestReaderStream(readStream))
                        using (var writer = new StreamWriter(writeStream, new UTF8Encoding(false), 4096)
                        {
                            NewLine = "\r\n", AutoFlush = false
                        })
                        {
                            var headers = new List <HttpHeader>();
                            while (true)
                            {
                                var request = await ReadRequestHead(partner, receiveTimer, receivedAt, reader, writer, headers);

                                if (request == null)
                                {
                                    return;
                                }

                                receiveTimer = null;
                                receivedAt   = DateTime.MinValue;

                                var response = await RoutingManager.DispatchRequest(request);

                                using (response.ContentStream)
                                {
                                    try
                                    {
                                        response.ResolveJsonContent(this);
                                    }
                                    catch (Exception e)
                                    {
                                        response = HttpResponse.String("Error serializing JSON: " + e, HttpStatus.InternalServerError);
                                    }

                                    if ((response.WebSocketHandler != null) && request.IsWebSocket)
                                    {
                                        await HandleWebSocket(partner, readStream, writer, response.WebSocketHandler, request);

                                        return;
                                    }

                                    await WriteResponseHead(writer, response);

                                    if (response.ContentStream != null)
                                    {
                                        await WriteChunkedResponse(writeStream, writer, response.ContentStream);
                                    }
                                    else
                                    {
                                        await WriteSimpleResponse(writeStream, writer, response);
                                    }
                                }

                                // All is well - we can loop (keepalive).
                            }
                        }
            }
            catch (Exception e)
            {
                UnexpectedException?.Invoke(e);
            }
        }
Пример #11
0
        private void ChannelRegistration <T>(IBasicProperties basicProperties, string queue, string errorQueue, string exchange, string routingKey, ConsumerResolver <T> resolver)
        {
            var rabbitConsumer = new EventingBasicConsumer(channel);

            rabbitConsumer.Received += (model, ea) =>
            {
                var serializer = RabbitMQWrapperConnection.DefaultAdapter;
                try
                {
                    var message = serializer.DeserializeBytes <RabbitMQWrapperMessage <T> >(ea.Body);

                    AbstractConsumer <T> consumer = null;
                    try
                    {
                        consumer = resolver(message.EventID, message.Event, message.ContractVersion);

                        if (message.Event == "")
                        {
                            consumer.Consume(message.EventID, message.Content, message.ContractVersion);
                        }
                        consumer.Consume(message.Event, message.Content, message.ContractVersion);
                    }
                    catch (Exception e)
                    {
                        Logger.Error("Consumer: " + consumer + " has unexpected error", e);
                        channel.BasicNack(deliveryTag: ea.DeliveryTag, multiple: false, requeue: true);
                        return;
                    }

                    try
                    {
                        channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);
                    }
                    catch (Exception e)
                    {
                        Logger.Error("Connection lost", e);
                        throw e;
                    }
                }
                catch (JsonException e)
                {
                    var customError = new UnexpectedException(e);
                    Logger.Error("Could not deserialize the object: " + ea.Body, customError);
                    try
                    {
                        Logger.Warn("Creating error queue...");
                        this.EnsureRoute(errorQueue, exchange, routingKey);
                        this.channel.BasicPublish(exchange: exchange, routingKey: routingKey, basicProperties: basicProperties, body: ea.Body);
                        channel.BasicNack(deliveryTag: ea.DeliveryTag, multiple: false, requeue: false);
                    }
                    catch (Exception ex)
                    {
                        var custom = new UnexpectedException(ex);
                        Logger.Fatal("Unexpected error occured while publishing items to error queue", custom);
                        throw custom;
                    }
                }
                catch (Exception e)
                {
                    var custom = new UnexpectedException(e);
                    Logger.Fatal("Unexpected error occured while consumer received a message", custom);
                    throw custom;
                }
            };

            try
            {
                channel.BasicConsume(queue: queue, noAck: false, consumer: rabbitConsumer, consumerTag: appKey);
            }
            catch (IOException e)
            {
                if (channel.IsOpen == false)
                {
                    var custom = new ConnectionClosedException(e);
                    Logger.Info("Trying to reconnect again... Queue:" + queue, custom);
                    Thread.Sleep(200);
                    channel.BasicConsume(queue: queue, noAck: false, consumer: rabbitConsumer, consumerTag: appKey);
                }
                else
                {
                    var custom = new AccessDeniedException(e);
                    Logger.Fatal("Access denied. Queue: " + queue, custom);
                    throw custom;
                }
            }
        }