コード例 #1
0
        public ICompletes <string> SeekTo(string id)
        {
            string currentId;

            switch (id)
            {
            case EntryReader.Beginning:
                Rewind();
                currentId = ReadCurrentId();
                break;

            case EntryReader.End:
                EndInternal();
                currentId = ReadCurrentId();
                break;

            case EntryReader.Query:
                currentId = ReadCurrentId();
                break;

            default:
                To(id);
                currentId = ReadCurrentId();
                break;
            }

            return(Completes.WithSuccess(currentId));
        }
コード例 #2
0
        public void ActionSignatureWithBlankParamNameThrowsException()
        {
            var exception = Assert.Throws <ArgumentException>(() => CreateRequestHandler(Method.Get, "/posts/{ }", ParameterResolver.Path <string>(0))
                                                              .Handle(postId => Completes.WithSuccess(Response.Of(Response.ResponseStatus.Ok, JsonSerialization.Serialized(postId)))));

            Assert.Equal("Empty path parameter name for GET /posts/{ }", exception.Message);
        }
コード例 #3
0
    public void HandlerWithOneParam()
    {
        var handler = CreateRequestHandler(
            Method.Get,
            "/posts/{postId}/comment/{commentId}/user/{userId}/contact/{contactId}",
            ParameterResolver.Path <string>(0),
            ParameterResolver.Path <string>(1),
            ParameterResolver.Path <string>(2),
            ParameterResolver.Path <string>(3),
            ParameterResolver.Query("page", 10),
            ParameterResolver.Query("pageSize", 10))
                      .Handle((postId, commentId, userId, contactId, page, pageSize) =>
                              Completes.WithSuccess(Response.Of(ResponseStatus.Ok, JsonSerialization.Serialized(
                                                                    $"{postId} {commentId}"))));

        var response = handler
                       .Execute(Request.WithMethod(Method.Get), "my-post", "my-comment", "admin", "c1", 10, 10, Logger).Outcome;

        Assert.NotNull(handler);
        Assert.Equal(Method.Get, handler.Method);
        Assert.Equal("/posts/{postId}/comment/{commentId}/user/{userId}/contact/{contactId}", handler.Path);
        Assert.Equal(typeof(string), handler.ResolverParam1.ParamClass);
        Assert.Equal(typeof(string), handler.ResolverParam2.ParamClass);
        Assert.Equal(typeof(string), handler.ResolverParam3.ParamClass);
        Assert.Equal(typeof(string), handler.ResolverParam4.ParamClass);
        AssertResponsesAreEquals(Response.Of(ResponseStatus.Ok, JsonSerialization.Serialized("my-post my-comment")), response);
    }
コード例 #4
0
        public void ExecuteWithRequestAndMappedParameters()
        {
            var request = Request.Has(Method.Get)
                          .And("/posts/my-post/comments/my-comment".ToMatchableUri())
                          .And(Version.Http1_1);
            var mappedParameters =
                new Action.MappedParameters(1, Method.Get, "ignored", new List <Action.MappedParameter>
            {
                new Action.MappedParameter("string", "my-post"),
                new Action.MappedParameter("string", "my-comment"),
            });
            var handler = CreateRequestHandler(
                Method.Get,
                "/posts/{postId}",
                ParameterResolver.Path <string>(0))
                          .Handle(postId
                                  => Completes.WithSuccess(Response.Of(Response.ResponseStatus.Ok, JsonSerialization.Serialized(
                                                                           $"{postId}"))));

            var response = handler.Execute(request, mappedParameters, Logger).Outcome;

            AssertResponsesAreEquals(
                Response.Of(Response.ResponseStatus.Ok, JsonSerialization.Serialized("my-post")),
                response);
        }
コード例 #5
0
        public void ActionWithoutParamNameShouldNotThrowException()
        {
            var handler = CreateRequestHandler(Method.Post, "/posts", ParameterResolver.Body <string>())
                          .Handle(postId => Completes.WithSuccess(Response.Of(Response.ResponseStatus.Ok, JsonSerialization.Serialized(postId))));

            Assert.Equal("", handler.ActionSignature);
        }
コード例 #6
0
 public void ChangeContact(string userId, ContactData contactData)
 {
     Stage.ActorOf <IUser>(_addressFactory.From(userId))
     .AndThenTo(user => user.WithContact(new Contact(contactData.EmailAddress, contactData.TelephoneNumber)))
     .OtherwiseConsume(noUser => Completes.With(Response.Of(ResponseStatus.NotFound, UserLocation(userId))))
     .AndThenConsume(userState => Response.Of(ResponseStatus.Ok, JsonSerialization.Serialized(UserData.From(userState))));
 }
コード例 #7
0
        public ICompletes <Stream <TEntry> > StreamFor(string streamName, int fromStreamVersion)
        {
            var version = fromStreamVersion;

            if (_snapshotsView.TryGetValue(streamName, out var snapshot))
            {
                if (snapshot.DataVersion > version)
                {
                    version = snapshot.DataVersion;
                }
                else
                {
                    snapshot = null !; // reading from beyond snapshot
                }
            }

            var entries = new List <BaseEntry>();

            if (_streamIndexesView.TryGetValue(streamName, out var versionIndexes))
            {
                while (versionIndexes.TryGetValue(version, out var journalIndex))
                {
                    var entry = _journalView[journalIndex];
                    entries.Add(entry);
                    ++version;
                }
            }
            return(Completes.WithSuccess(new Stream <TEntry>(streamName, version - 1, entries, snapshot)));
        }
コード例 #8
0
 public ICompletes <TEntry> ReadNext()
 {
     if (_currentIndex < _journalView.Count)
     {
         return(Completes.WithSuccess(_journalView[_currentIndex++]));
     }
     return(null !);
 }
コード例 #9
0
        public void UnsubscribeFromStream(string streamName, string id)
        {
            if (Publishers.TryGetValue(streamName, out var publisher))
            {
                publisher.Unsubscribe(new SseSubscriber(streamName, new SseClient(Context?.ClientContext)));
            }

            Completes?.With(Response.Of(Response.ResponseStatus.Ok));
        }
コード例 #10
0
ファイル: Client.cs プロジェクト: Johnny-Bee/vlingo-net-http
        public ICompletes <Response> RequestWith(Request request)
        {
            var completes = _configuration.KeepAlive
                ? Completes.RepeatableUsing <Response>(_configuration.Stage.Scheduler)
                : Completes.Using <Response>(_configuration.Stage.Scheduler);

            _consumer.RequestWith(request, completes);
            return(completes);
        }
コード例 #11
0
        public ICompletes <Response> RequestWith(Request request)
        {
            var completes = _configuration.KeepAlive
                ? Completes.RepeatableUsing <Response>(_configuration.Stage.Scheduler)
                : Completes.Using <Response>(_configuration.Stage.Scheduler);

            request.Headers.And(RequestHeader.Connection, _configuration.KeepAlive ? Header.ValueKeepAlive : Header.ValueClose);
            _consumer.RequestWith(request, completes);
            return(completes);
        }
コード例 #12
0
 public void ChangeName(string userId, NameData nameData)
 {
     Stage.ActorOf <IUser>(_addressFactory.From(userId))
     .AndThenTo(user => user.WithName(new Name(nameData.Given, nameData.Family)))
     .OtherwiseConsume(noUser => Completes.With(Response.Of(ResponseStatus.NotFound, UserLocation(userId))))
     .AndThenConsume(userState => {
         _repository.Save(userState);
         Completes.With(Response.Of(ResponseStatus.Ok, JsonSerialization.Serialized(UserData.From(userState))));
     });
 }
コード例 #13
0
        public void SimpleHandler()
        {
            var handler = new RequestHandler0(Method.Get, "/helloworld")
                          .Handle(() => Completes.WithSuccess(Response.Of(Response.ResponseStatus.Created)));
            var response = handler.Execute(Request.WithMethod(Method.Get), Logger).Outcome;

            Assert.NotNull(handler);
            Assert.Equal(Method.Get, handler.Method);
            Assert.Equal("/helloworld", handler.Path);
            AssertResponsesAreEquals(Response.Of(Response.ResponseStatus.Created), response);
        }
コード例 #14
0
        public void QueryUsers()
        {
            var users = new List <UserData>();

            foreach (var userState in _repository.Users)
            {
                users.Add(UserData.From(userState));
            }

            Completes.With(Response.Of(ResponseStatus.Ok, JsonSerialization.Serialized(users)));
        }
コード例 #15
0
 public void ChangeUser(string userId, UserData userData)
 {
     if (userId.EndsWith("123"))
     {
         Completes.With(Response.Of(ResponseStatus.PermanentRedirect, Headers.Of(ResponseHeader.Of(ResponseHeader.Location, "/"))));
     }
     else
     {
         Completes.With(Response.Of(ResponseStatus.Ok));
     }
 }
コード例 #16
0
        public override ICompletes <IJournalReader?> JournalReader(string name)
        {
            IJournalReader?reader = null;

            if (!_journalReaders.ContainsKey(name))
            {
                reader = new InMemoryJournalReader(_journal, name);
                _journalReaders.Add(name, reader);
            }

            return(Completes.WithSuccess(reader));
        }
コード例 #17
0
        public void SimpleHandlerWithBinaryResponse()
        {
            byte[] body    = { 1, 2, 1, 2 };
            var    handler = new RequestHandler0(Method.Get, "/helloworld")
                             .Handle(() => Completes.WithSuccess(Response.Of(Response.ResponseStatus.Created, Body.From(body, Body.Encoding.None))));
            var response = handler.Execute(Request.WithMethod(Method.Get), Logger).Outcome;

            Assert.NotNull(handler);
            Assert.Equal(Method.Get, handler.Method);
            Assert.Equal("/helloworld", handler.Path);
            Assert.Equal(Body.From(body, Body.Encoding.None).BinaryContent, response.Entity.BinaryContent);
        }
コード例 #18
0
        public void Feed(string feedName, string feedProductId, Type feedProducerClass, int feedProductElements)
        {
            var producer = FeedProducer(feedName, feedProducerClass);

            if (producer == null)
            {
                Completes?.With(Response.Of(ResponseStatus.NotFound, $"Feed '{feedName}' does not exist."));
            }
            else
            {
                producer.ProduceFeedFor(new FeedProductRequest(Context, feedName, feedProductId, feedProductElements));
            }
        }
コード例 #19
0
        public override ICompletes <IJournalReader <TNewEntry>?> JournalReader <TNewEntry>(string name)
        {
            IJournalReader <TNewEntry>?reader = null;

            if (!_journalReaders.ContainsKey(name))
            {
                var entryReader = new InMemoryJournalReader <TEntry>(_journal, name);
                reader = entryReader as IJournalReader <TNewEntry>;
                _journalReaders.Add(name, entryReader);
            }

            return(Completes.WithSuccess(reader));
        }
コード例 #20
0
        public void QueryUser(string userId)
        {
            var userState = _repository.UserOf(userId);

            if (userState.DoesNotExist())
            {
                Completes.With(Response.Of(ResponseStatus.NotFound, UserLocation(userId)));
            }
            else
            {
                Completes.With(Response.Of(ResponseStatus.Ok, JsonSerialization.Serialized(UserData.From(userState))));
            }
        }
コード例 #21
0
        /// <summary>
        /// Completes with <code>Ok</code> and the file content or <code>NotFound</code>.
        /// </summary>
        /// <param name="contentFile">The name of the content file to be served</param>
        /// <param name="root">The root path of the static content</param>
        /// <param name="validSubPaths">The indicating the valid file paths under the root</param>
        public void ServeFile(string contentFile, string root, string validSubPaths)
        {
            if (string.IsNullOrWhiteSpace(_rootPath))
            {
                var slash = root.EndsWith("/") ? "" : "/";
                _rootPath = root + slash;
            }

            var uri         = string.IsNullOrEmpty(contentFile) ? "/index.html" : Context?.Request?.Uri?.AbsolutePath;
            var contentPath = ContentFilePath(_rootPath + uri);

            try
            {
                // try to read from disk first
                if (FileExists(contentFile))
                {
                    var fileContent = ReadFile(contentPath);
                    Completes?.With(Response.Of(ResponseStatus.Ok, Body.From(fileContent, Body.Encoding.UTF8).Content));
                }
                else // than from embedded resource
                {
                    _rootPath = root.EndsWith("/") ? root.Substring(0, root.Length - 1) : root;
                    uri       = string.IsNullOrEmpty(contentFile) ? "/index.html" :  Context?.Request?.Uri?.AbsolutePath;


                    _assembly ??= LoadFromPath(root);

                    var response = new List <string>
                    {
                        $"{_rootPath}{uri}",
                        $"{WithIndexHtmlAppended(_rootPath + uri)}"
                    }
                    .Select(CleanPath)
                    .Where(IsValidFilename)
                    .Take(1)
                    .Select(FileResponse)
                    .DefaultIfEmpty(NotFound());

                    Completes?.With(response.First());
                }
            }
            catch (IOException)
            {
                Completes?.With(Response.Of(ResponseStatus.InternalServerError));
            }
            catch (ArgumentException)
            {
                Completes?.With(Response.Of(ResponseStatus.NotFound));
            }
        }
コード例 #22
0
 internal static ICompletes <Response> ExecuteRequest(
     Func <ICompletes <Response>?> executeAction,
     IErrorHandler errorHandler,
     ILogger logger)
 {
     try
     {
         return(executeAction.Invoke()?
                .RecoverFrom(ex => ResourceErrorProcessor.ResourceHandlerError(errorHandler, logger, ex)) !);
     }
     catch (Exception ex)
     {
         return(Completes.WithFailure(ResourceErrorProcessor.ResourceHandlerError(errorHandler, logger, ex)));
     }
 }
コード例 #23
0
        public void TestThatAlreadyFailedExecutesOtherwise()
        {
            var failureValue = -1;
            var completes    = Completes.WithFailure(100);

            completes
            .AndThen(value => value * value)
            .Otherwise <int>(x => failureValue = x);

            var outcome = completes.Await();

            Assert.True(completes.HasFailed);
            Assert.Equal(100, outcome);
            Assert.Equal(100, failureValue);
        }
コード例 #24
0
        public override ICompletes <IStreamReader?> StreamReader(string name)
        {
            IStreamReader?reader = null;

            if (!_journalReaders.ContainsKey(name))
            {
                var castedDictionary = new Dictionary <string, State <T> >();
                foreach (var snapshotPair in _snapshots)
                {
                    castedDictionary.Add(snapshotPair.Key, (State <T>)snapshotPair.Value);
                }
                reader = new InMemoryStreamReader <T>(_journal.Cast <BaseEntry>().ToList(), _streamIndexes, castedDictionary, name);
                _streamReaders.Add(name, reader);
            }
            return(Completes.WithSuccess(reader));
        }
コード例 #25
0
        public void ExecuteWithRequestAndMappedParametersHasToReturnTheSameAsExecute()
        {
            var request = Request.Has(Method.Get)
                          .And("/hellworld".ToMatchableUri())
                          .And(Version.Http1_1);
            var mappedParameters =
                new Action.MappedParameters(1, Method.Get, "ignored", new List <Action.MappedParameter>());
            var handler = new RequestHandler0(Method.Get, "/helloworld")
                          .Handle(() => Completes.WithSuccess(Response.Of(Response.ResponseStatus.Created)));
            var response = handler.Execute(request, mappedParameters, Logger).Outcome;

            Assert.NotNull(handler);
            Assert.Equal(Method.Get, handler.Method);
            Assert.Equal("/helloworld", handler.Path);
            AssertResponsesAreEquals(Response.Of(Response.ResponseStatus.Created), response);
        }
コード例 #26
0
        public void TestThatNestedRecoverFromWithNoExceptionSetsOutput()
        {
            var failureValue = -1;
            var completes    = new BasicCompletes <int>(_testScheduler);

            completes
            .AndThenTo(42, value => Completes.WithSuccess(value * 2).RecoverFrom(e => 0))
            .RecoverFrom(e => failureValue = int.Parse(e.Message));

            completes.With(2);
            completes.Await();

            Assert.False(completes.HasFailed);
            Assert.Equal(-1, failureValue);
            Assert.Equal(4, completes.Outcome);
        }
コード例 #27
0
        private ICompletes <IOutcome <ArithmeticException, float> > DivZero(float x)
        {
            IOutcome <ArithmeticException, float> outcome;
            var value = x / 0;

            if (float.IsPositiveInfinity(value))
            {
                outcome = Failure.Of <ArithmeticException, float>(new ArithmeticException("division by zero"));
            }
            else
            {
                outcome = Success.Of <ArithmeticException, float>(value);
            }

            return(Completes.WithSuccess(outcome));
        }
コード例 #28
0
 internal static ICompletes <Response> ExecuteRequest(
     Request request,
     MediaTypeMapper mediaTypeMapper,
     Func <ICompletes <IObjectResponse> > executeAction,
     IErrorHandler errorHandler,
     ILogger logger)
 {
     try
     {
         return(executeAction.Invoke()
                .AndThen(objectResponse => ToResponse(objectResponse, request, mediaTypeMapper, errorHandler, logger)));
     }
     catch (Exception ex)
     {
         return(Completes.WithFailure(ResourceErrorProcessor.ResourceHandlerError(errorHandler, logger, ex)));
     }
 }
コード例 #29
0
        public ICompletes <IEnumerable <TEntry> > ReadNext(int maximumEntries)
        {
            var entries = new List <TEntry>();

            for (int count = 0; count < maximumEntries; ++count)
            {
                if (_currentIndex < _journalView.Count)
                {
                    entries.Add(_journalView[_currentIndex++]);
                }
                else
                {
                    break;
                }
            }
            return(Completes.WithSuccess(entries.AsEnumerable()));
        }
コード例 #30
0
        public void ExecuteWithRequestAndMappedParametersWithWrongSignatureType()
        {
            var request = Request.Has(Method.Get)
                          .And("/posts/my-post".ToMatchableUri())
                          .And(Version.Http1_1);
            var mappedParameters =
                new Action.MappedParameters(1, Method.Get, "ignored", new List <Action.MappedParameter>
            {
                new Action.MappedParameter("String", "my-post")
            });
            var handler = CreateRequestHandler(Method.Get, "/posts/{postId}", ParameterResolver.Path <int>(0))
                          .Handle(postId => Completes.WithSuccess(Response.Of(Response.ResponseStatus.Ok, JsonSerialization.Serialized("it is my-post"))));

            var exception = Assert.Throws <ArgumentException>(() => handler.Execute(request, mappedParameters, Logger));

            Assert.Equal("Value my-post is of mimeType String instead of Int32", exception.Message);
        }