예제 #1
3
        public void Should_get_a_messagge()
        {
            var contentType = "text/text";
            var payload = "Hello!";
            var message = new Message()
            {
                Id = Identity.Random(),
                TopicId = Identity.Random(),
                Payload = Encoding.ASCII.GetBytes(payload),
                UtcReceivedOn = DateTime.UtcNow
            };

            message.Headers.Add("Content-Type", new[] { contentType });

            var key = new MessageKey { MessageId = message.Id.Value, TopicId = message.TopicId };

            messageByMessageKey
                .Setup(r => r.Get(It.Is<MessageKey>(k => k.TopicId == key.TopicId && k.MessageId == key.MessageId)))
                .Returns(message);

            var client = new HttpClient(baseUri);
            var url = baseUri + message.Id.Value.ToString() + "/topic/" + message.TopicId;
            var result = client.Get(url);

            messageByMessageKey.Verify(r => r.Get(It.Is<MessageKey>(k => k.TopicId == key.TopicId && k.MessageId == key.MessageId)));

            Assert.IsNotNull(result);
            Assert.AreEqual(HttpStatusCode.OK, result.StatusCode);
            Assert.AreEqual(payload, result.Content.ReadAsString());
            Assert.AreEqual(contentType, result.Content.Headers.ContentType.MediaType);
        }
예제 #2
0
        private static void PopulateWithMessage(this HttpRequestMessage request, Message message)
        {
            var req = request;
            Guard.Instance
                .ArgumentNotNull(() => req, request)
                .ArgumentNotNull(() => message, message);

            request.Content = new ByteArrayContent(message.Payload ?? new byte[0]);

            var headersToIgnore = Constants.HttpResponseHeaders.Union(Constants.HttpHeadersToIgnoreOnPush);

            var validHeaders = message.Headers.Where(h => !headersToIgnore.Contains(h.Key, StringComparer.CurrentCultureIgnoreCase));

            foreach (var header in validHeaders)
            {
                if (Constants.HttpContentHeaders.Contains(header.Key))
                {
                    request.Content.Headers.Add(header.Key, header.Value);
                }
                else
                {
                    request.Headers.Add(header.Key, header.Value);
                }
            }
        }
예제 #3
0
        public static Uri OfMessageByTopic(Message message)
        {
            Guard.Instance
                .ArgumentNotNull(() => message, message)
                .ArgumentNotNull(() => message.Id, message.Id);

            return OfMessageByTopic(message.TopicId, message.Id.Value);
        }
예제 #4
0
        public static string LinkToMessage(Message message)
        {
            Guard.Instance.ArgumentNotNull(() => message, message)
                .ArgumentNotNull(() => message.Id, message.Id)
                .ArgumentNotNull(() => message.TopicId, message.TopicId);

            return LinkToMessage(message.TopicId, message.Id.Value);
        }
예제 #5
0
 static public Facade.Link ToLink(this Model.Message from)
 {
     if (from == null)
     {
         return(null);
     }
     return(new Facade.Link(ResourceLocation.OfMessageByTopic(from).ToString(), Constants.Relationships.Message));
 }
예제 #6
0
        public virtual void Execute(Message instance)
        {
            if (instance.UtcReceivedOn == default(DateTime)) throw new ValidationException(Texts.ReceivedOnMustBeSetted);
            if (!entityById.Exist<Topic>(instance.TopicId)) throw new EntityNotFoundException(typeof(Topic), instance.TopicId);

            repository.MakePersistent(instance);

            eventAggregator.Raise(new NewMessageEvent {Message = instance});
        }
        public void WhenEverythingIsOK_ThenInsertTheMessage()
        {
            var stubRepository = new StubMessageRepository();
            var topicId = Identity.Random();
            var command = CreateCreateMessageCommand(Mock.Of<IEntityById>(q => q.Exist<Topic>(topicId) == true), stubRepository);

            var message = new Message
            {
                UtcReceivedOn = DateTime.UtcNow,
                TopicId = topicId
            };

            command.Execute(message);

            stubRepository.Entities.Should().Contain(message);
        }
        public void WhenTopicIdIsInvalid_ThenThrowValidateException()
        {
            var topicId = Identity.Random();
            var command = CreateCreateMessageCommand( Mock.Of<IEntityById>(q => q.Exist<Topic>(topicId) == false));

            var message = new Message
            {
                UtcReceivedOn = DateTime.UtcNow,
                TopicId = topicId
            };

            command.Executing(gc => gc.Execute(message))
                                    .Throws<EntityNotFoundException>()
                                    .And
                                    .Exception.Message.Should().Be.EqualTo(string.Format(Texts.EntityNotFound, typeof(Topic).Name, topicId));
        }
예제 #9
0
        public void Post_of_a_valid_message()
        {
            var client = new HttpClient(baseUri);
            var content = new StringContent("sample");

            var topicId = Identity.Random();
            var response = new Message {Id = Identity.Random() };

            createMessageCommand
                .Setup(s => s.Execute(It.Is<Message>(m => m != null && m.TopicId == topicId)))
                .Callback<Message>(m => m.Id = Identity.Random()); ;

            var httpResponse = client.Post(baseUri+"/topic/" + topicId, content);

            var contentStr = httpResponse.Content.ReadAsString();
        }
예제 #10
0
        public void WhenThereIsNotAchievedFeed_ThenCreateANewOneWithMessage()
        {
            var topicId = Identity.Random();
            var feed = new Feed { TopicId = topicId };
            var query = Mock.Of<IGetWorkingFeedForTopic>(q => q.Execute(topicId) == feed);

            var repository = new StubRepository<Feed>();

            var handler = CreateHandler(repository, query);
            var message = new Message  { Id = Identity.Random(), TopicId = topicId};

            handler.Handle(new NewMessageEvent { Message = message });

            repository.Updates
                .Satisfy(es => es.Count == 1
                            && es.First() == feed
                            && es.First().Entries.Any(e => e.MessageId == message.Id));
        }
예제 #11
0
        public void WhenMessageDoesNotExist_MustReturnNull()
        {
            var col = base.mongoDb.GetCollection<Message>(MongoDbConstants.GetCollectionNameForMessage(topicId));
            var msg = new Message
                          {
                              UtcReceivedOn = DateTime.UtcNow,
                              TopicId = topicId,
                              Payload = new byte[] { 1, 2, 3, 4, 5 }
                          };
            col.Save(msg);

            Assert.IsNotNull(msg.Id);

            var key = new MessageKey { MessageId = Identity.Random(12), TopicId = topicId };
            var query = new MessageByMessageKey(base.connectionString);
            var result = query.Get(key);
            Assert.IsNull(result);
        }
예제 #12
0
        public void Setup()
        {
            topicId = Identity.Random(12);
            var col = base.mongoDb.GetCollection<Message>(MongoDbConstants.GetCollectionNameForMessage(topicId));

            var ids = new List<Identity>();
            for (int i=0; i<3;i++)
            {
                var msg = new Message
                              {
                                  UtcReceivedOn = DateTime.UtcNow,
                                  TopicId = topicId,
                                  Payload = new byte[] {1, 2, 3, 4, 5}
                              };
                col.Save(msg);
                ids.Add(msg.Id.Value);
            }

            msgIds = ids.ToArray();
        }
예제 #13
0
        public void Nontext_message_is_linked_with_the_correct_content_type()
        {
            const string contentType = "application/json";
            const string payload = @"{""Hello"":""World!""}";
            var messageId = Identity.Random();
            var topicId = Identity.Random();
            var message = new Message()
            {
                Id = messageId,
                TopicId = topicId,
                Payload = Encoding.ASCII.GetBytes(payload),
                UtcReceivedOn = DateTime.UtcNow
            };
            message.Headers.Add("Content-Type", new[] { contentType });

            var feed = GetFeedForMessage(message);

            var entry = feed.Items.Single();

            Assert.AreEqual(contentType, entry.Content.Type);
        }
예제 #14
0
        public void Text_message_with_charset_is_included_as_text()
        {
            const string contentType = "text/plain;charset=UTF-8";
            const string payload = "Hello!";
            var messageId = Identity.Random();
            var topicId = Identity.Random();
            var message = new Message()
            {
                Id = messageId,
                TopicId = topicId,
                Payload = Encoding.ASCII.GetBytes(payload),
                UtcReceivedOn = DateTime.UtcNow
            };
            message.Headers.Add("Content-Type", new[] { contentType });

            var feed = GetFeedForMessage(message);

            var entry = feed.Items.Single();

            Assert.AreEqual(contentType, entry.Content.Type);
        }
예제 #15
0
        private static void PopulateHttpResponseMessage(ref HttpResponseMessage response, Message message)
        {
            Guard.Instance.ArgumentNotNull(()=>message, message);

            response.Content = new ByteArrayContent(message.Payload ?? new byte[0]);
            var headerName = string.Empty;
            var headerValues = new string[0];
            try
            {
                foreach (var header in message.Headers)
                {
                    headerName = header.Key;
                    headerValues = header.Value;

                    if (Constants.HttpContentHeaders.Contains(header.Key, StringComparer.CurrentCultureIgnoreCase))
                    {
                        response.Content.Headers.Add(header.Key, header.Value);
                    }
                    else if (Constants.HttpResponseHeaders.Contains(header.Key, StringComparer.CurrentCultureIgnoreCase))
                    {
                        response.Headers.Add(header.Key, header.Value);
                    }
                    else if (Constants.HttpRequestHeaders.Contains(header.Key, StringComparer.CurrentCultureIgnoreCase))
                    {
                        // ignore header
                    }
                    else
                    {
                        // Custom header
                        response.Headers.Add(header.Key, header.Value);
                    }
                }
            }
            catch (Exception e)
            {
                var name = headerName ?? "The header's name is null.";
                var value = headerValues == null ? "The header's value is null." : headerValues.Aggregate((a,b)=> a + "; " + b);
                throw new ApplicationException(string.Format(Messages.InvalidHeader, name, value), e);
            }
        }
예제 #16
0
        public void WhenMessageExists_MustReturnMessage()
        {
            var col = base.mongoDb.GetCollection<Message>(MongoDbConstants.GetCollectionNameForMessage(topicId));
            var msg = new Message
                          {
                              UtcReceivedOn = DateTime.UtcNow,
                              TopicId = topicId,
                              Payload = new byte[] { 1, 2, 3, 4, 5 }
                          };
            col.Save(msg);

            Assert.IsNotNull(msg.Id);

            var key = new MessageKey { MessageId = msg.Id.Value, TopicId = topicId };
            var query = new MessageByMessageKey(base.connectionString);
            var result = query.Get(key);
            Assert.IsNotNull(result);
            Assert.AreEqual(msg.Id, result.Id);
            Assert.AreEqual(msg.UtcReceivedOn.Date, result.UtcReceivedOn.Date);
            Assert.AreEqual(msg.TopicId, result.TopicId);
            CollectionAssert.AreEqual(msg.Payload, result.Payload);
        }
예제 #17
0
 public void Update(Message entity)
 {
     Updates.Add(entity);
 }
예제 #18
0
 public void MakePersistent(Message entity)
 {
     Entities.Add(entity);
 }
예제 #19
0
 public void Update(Message entity)
 {
     MongoCollection<Message> collection =
         DB.GetCollection<Message>(MongoDbConstants.GetCollectionNameForMessage(entity.TopicId));
     collection.Save(entity);
 }
예제 #20
0
        private static Message Create(HttpRequestMessage request)
        {
            var message = new Message
                              {
                                  // Populate system properties
                                  UtcReceivedOn = DateTime.UtcNow,

                                  // Populate post's body
                                  Payload = request.Content.ReadAsByteArray()
                              };

            // Populate headers
            request.Headers
                .Where(h => !h.Key.StartsWith(Constants.PrivateHeaders.Prefix))
                .Union(request.Content.Headers)
                .ForEach(h => message.Headers.Add(h.Key, h.Value.ToArray()));

            // Invokes repository
            return message;
        }
예제 #21
0
        private SyndicationFeed GetFeedForMessage(Message message)
        {
            var messageId = message.Id.Value;
            var topicId = message.TopicId;

            var feedEntry = new FeedEntry() { MessageId = messageId, TimeStamp = DateTime.UtcNow };
            var feed = new Feed()
            {
                Entries = new List<FeedEntry>(new[] { feedEntry }),
                Id = Identity.Random(),
                TopicId = topicId,
                Updated = DateTime.UtcNow
            };

            var topic = new Topic()
            {
                Id = topicId,
                Name = "Topic Name",
                Description = "Topic Description",
                GroupId = Identity.Random()
            };

            var key = new MessageKey { MessageId = messageId, TopicId = topicId };

            messageByMessageKey
                .Setup(r => r.Get(It.Is<MessageKey>(k => k.TopicId == key.TopicId && k.MessageId == key.MessageId)))
                .Returns(message);

            getWorkingFeedForTopic
                .Setup(r => r.Execute(topicId))
                .Returns(feed);

            entityById
                .Setup(r => r.Get<Topic>(topicId))
                .Returns(topic);

            var client = new HttpClient(baseUri);

            var response = client.Get(topicId.ToString());
            var formatter = new Atom10FeedFormatter();

            using (var rdr = XmlReader.Create(response.Content.ContentReadStream))
            {
                formatter.ReadFrom(rdr);
                return formatter.Feed;
            }
        }