예제 #1
0
        public async Task CanOvercomeExceptions()
        {
            var receivedStrings = new ConcurrentQueue <string>();
            var topic           = BrokerFactory.GetNewTopic();

            var producer = BrokerFactory.ConfigureProducer()
                           .Topics(m => m.Map <string>(topic))
                           .Create();

            Using(producer);

            var random = new Random(DateTime.Now.GetHashCode());

            var consumer = BrokerFactory.ConfigureConsumer("default-group")
                           .Handle(async(messages, token) =>
            {
                var strings = messages.Select(m => m.Body).Cast <string>();

                if (random.Next(3) == 0)
                {
                    throw new ApplicationException("oh no!");
                }

                receivedStrings.Enqueue(strings);
            })
                           .Topics(t => t.Subscribe(topic))
                           .Positions(p => p.StoreInMemory())
                           .Start();

            Using(consumer);

            await Task.WhenAll(Enumerable.Range(0, 1000).Select(n => producer.Send($"message-{n}", "p100")));

            await receivedStrings.WaitOrDie(c => c.Count == 1000, failExpression : c => c.Count > 1000, timeoutSeconds : 10);
        }
예제 #2
0
        public static void Main(string[] args)
        {
            var broker = BrokerFactory.GetBroker(AirlineType.AIRASIA);

            var a = new Program().Add(1, 2, 3);
            ///var b = new Program().Add(2, 3, 50,34,34,343,43,43,43,4);
        }
        private void CreateBrokerHelper()
        {
            using (MockHttpAndServiceBundle harness = CreateTestHarness())
            {
                AuthenticationRequestParameters parameters = harness.CreateAuthenticationRequestParameters(
                    MsalTestConstants.AuthorityHomeTenant,
                    MsalTestConstants.Scope,
                    new TokenCache(harness.ServiceBundle),
                    extraQueryParameters: MsalTestConstants.ExtraQueryParams,
                    claims: MsalTestConstants.Claims);

                parameters.IsBrokerEnabled = true;

                AcquireTokenInteractiveParameters interactiveParameters = new AcquireTokenInteractiveParameters();

                InteractiveRequest request = new InteractiveRequest(
                    harness.ServiceBundle,
                    parameters,
                    interactiveParameters,
                    new MockWebUI());

                BrokerFactory brokerFactory = new BrokerFactory();
                _brokerInteractiveRequest = new BrokerInteractiveRequest(parameters, interactiveParameters, harness.ServiceBundle, null, brokerFactory.Create(harness.ServiceBundle));
            }
        }
예제 #4
0
        public void TestGetMultipleBrokers()
        {
            var brokerFactory1A = BrokerFactory.Broker(Nyws802);

            Assert.IsNotNull(brokerFactory1A);
            Assert.AreEqual(1, BrokerFactory.Count);

            var brokerFactory1B = BrokerFactory.Broker(Nyws802);

            Assert.IsNotNull(brokerFactory1B);
            Assert.AreEqual(1, BrokerFactory.Count);
            Assert.AreSame(brokerFactory1A, brokerFactory1B);

            // change case to simulate different brokers
            var brokerFactory2 = BrokerFactory.Broker("failover:tcp://NYWS802:60606");

            Assert.IsNotNull(brokerFactory2);
            Assert.AreEqual(2, BrokerFactory.Count);
            Assert.AreNotSame(brokerFactory1A, brokerFactory2);

            BrokerFactory.Remove(Nyws802);
            Assert.AreEqual(1, BrokerFactory.Count);
            BrokerFactory.Remove("failover:tcp://NYWS802:60606");
            Assert.AreEqual(0, BrokerFactory.Count);
        }
예제 #5
0
        public void TestCreatePublisher()
        {
            var brokerFactory = BrokerFactory.Broker("failover:tcp://nyws802:60606");

            Assert.IsNotNull(brokerFactory);
            Assert.IsTrue(brokerFactory.IsStarted);

            var topicMessage = new Dictionary <string, string>();

            topicMessage["Source"]       = "UnitTest";
            topicMessage["SharesSold"]   = "9";
            topicMessage["SharesBought"] = "10";
            topicMessage["Position"]     = "1";

            var publishStatus = brokerFactory.Publish("Test.Topic.One", topicMessage);

            Assert.IsNotNull(publishStatus);
            Assert.IsFalse(publishStatus.StartsWith("Not sent"));

            brokerFactory.Shutdown();
            Assert.IsFalse(brokerFactory.IsStarted);

            var brokerFactoryDup = BrokerFactory.Broker("failover:tcp://nyws802:60606");

            Assert.IsNotNull(brokerFactoryDup);
            Assert.AreNotSame(brokerFactory, brokerFactoryDup);
        }
예제 #6
0
        internal override async Task <AuthenticationResult> ExecuteAsync(CancellationToken cancellationToken)
        {
            await ResolveAuthorityEndpointsAsync().ConfigureAwait(false);
            await AcquireAuthorizationAsync(cancellationToken).ConfigureAwait(false);

            VerifyAuthorizationResult();

            if (AuthenticationRequestParameters.IsBrokerEnabled)
            {
                BrokerFactory brokerFactory            = new BrokerFactory();
                var           brokerInteractiveRequest = new BrokerInteractiveRequest(
                    AuthenticationRequestParameters,
                    _interactiveParameters,
                    ServiceBundle,
                    _authorizationResult,
                    brokerFactory.Create(ServiceBundle));

                if (brokerInteractiveRequest.IsBrokerInvocationRequired())
                {
                    _msalTokenResponse = await brokerInteractiveRequest.SendTokenRequestToBrokerAsync().ConfigureAwait(false);
                }
                else
                {
                    _msalTokenResponse = await SendTokenRequestAsync(GetBodyParameters(), cancellationToken).ConfigureAwait(false);
                }
            }
            else
            {
                _msalTokenResponse = await SendTokenRequestAsync(GetBodyParameters(), cancellationToken).ConfigureAwait(false);
            }

            return(await CacheTokenResponseAndCreateAuthenticationResultAsync(_msalTokenResponse).ConfigureAwait(false));
        }
예제 #7
0
        public void Testubscriber()
        {
            var broker = BrokerFactory.Broker(BrokerFactoryTest.Nyws802);

            _receivedMessage = null;

            var topicSubscriber = broker.TopicSubscriber(TestTopic, OnMessageTestHandler);

            Assert.IsNotNull(topicSubscriber);
            Assert.AreEqual(1, broker.SubscriberCount);

            var topicSubscriberSame = broker.TopicSubscriber(TestTopic, OnMessageTestHandler);

            Assert.IsNotNull(topicSubscriberSame);
            Assert.AreEqual(1, broker.SubscriberCount);

            var topicSubscriber2 = broker.TopicSubscriber("Test.Library.Topic2", OnMessageTestHandler);

            Assert.IsNotNull(topicSubscriber2);
            Assert.AreEqual(2, broker.SubscriberCount);

            Assert.IsNotNull(PublishTestMessage(broker, TestTopic, "FieldName", "FieldValue"));

            WaitFor(HasMessageArrived, this, 10 * 1000);
            Assert.IsNotNull(_receivedMessage);
            Assert.IsTrue(_receivedMessage.Contains("FieldValue"));
            broker.RemoveSubscriber("Test.Library.Topic2");
            Assert.AreEqual(1, broker.SubscriberCount);
        }
예제 #8
0
        public async Task CanStartProducer()
        {
            var producer = BrokerFactory.ConfigureProducer().Create();

            Using(producer);

            await Task.Delay(TimeSpan.FromSeconds(1));
        }
예제 #9
0
        public static void MyTestInitialize(TestContext testContext)
        {
            var _af = new AuthorizersFactory();

            _af.Init();
            var _bf = new BrokerFactory();

            _bf.Init(_af, null);
        }
예제 #10
0
 protected override void ExecuteCommand(TradingInfoRequest request)
 {
     PushResponse(new TradingInfoResponse
     {
         User       = request.User,
         Brokers    = BrokerFactory.GetAvailableBrokers(request.User.Login),
         Portfolios = Core.GetPortfolios(request.User)
     });
 }
        protected override void ExecuteCommand(CreateSimulatedBrokerAccountRequest request)
        {
            var error = BrokerFactory.CreateSimulatedAccount(request.User.Login, request.Account);

            PushResponse(new CreateSimulatedBrokerAccountResponse
            {
                User    = request.User,
                Account = request.Account,
                Error   = error
            });
        }
예제 #12
0
 private void QueueReadCommand(NamedConnection connection)
 {
     lock (_lock)
     {
         _runningCommands.Add(Task.Factory.StartNew(() =>
         {
             var reader      = BrokerFactory.Get <ICommandReader>();
             MqttCommand cmd = reader.Read(connection.Connection);
             return(new CommandRead(cmd, connection));
         }, TaskCreationOptions.LongRunning));
     }
 }
예제 #13
0
        public async Task CanStartConsumer()
        {
            var consumer = BrokerFactory.ConfigureConsumer("default-group")
                           .Handle(async(messages, token) =>
            {
                Console.WriteLine($"Received {messages.Count} msgs");
            })
                           .Positions(p => p.StoreInMemory())
                           .Create();

            Using(consumer);

            await Task.Delay(TimeSpan.FromSeconds(1));
        }
예제 #14
0
        public void TestServerPublish()
        {
            _receivedMessage = null;

            var config = new AppConfiguration {
                MarketDataBrokerUrl = BrokerFactoryTest.Nyws802
            };
            var temp = AppConfiguration.AssemblyPath;

            var publisher = new ActiveMQPublisher(config);

            var testMessageConsumer = StartTestListener(BrokerFactory.Broker(config.MarketDataBrokerUrl), "Test.Topic.Publish");
            var publisherResult     = publisher.AMQPub("Test.Topic.Publish", "FieldName", "FieldValue");

            Assert.IsNotNull(publisherResult);
            Assert.IsTrue(publisherResult.ToString().StartsWith("Submitted"));

            WaitFor(HasMessageArrived, this, 10 * 1000);
            Assert.IsNotNull(_receivedMessage);
            Assert.AreEqual(true, _receivedMessage.Contains("FieldName"));
            _receivedMessage = null;

            var fieldNameRange  = new MockRange("FieldName", 1, 1);
            var fieldValueRange = new MockRange("FieldValueUpdate", 2, 1);

            publisherResult = publisher.AMQPub("Test.Topic.Publish", fieldNameRange, fieldValueRange);
            Assert.IsNotNull(publisherResult);
            Assert.IsTrue(publisherResult.ToString().StartsWith("Submitted"));

            WaitFor(HasMessageArrived, this, 10 * 1000);
            Assert.IsNotNull(_receivedMessage);
            Assert.AreEqual(true, _receivedMessage.Contains("FieldValueUpdate"));


            var fieldNameRange2 = new MockRange(new[] { "FieldName1", "FieldName2" }, 1, 1, true);

            var fieldValueRange2 = new MockRange(new[] { "FieldValueUpdate1", "FieldValueUpdate2" }, 1, 1, true);

            publisherResult = publisher.AMQPub("Test.Topic.Publish", fieldNameRange2, fieldValueRange2);
            Assert.IsNotNull(publisherResult);
            Assert.IsTrue(publisherResult.ToString().StartsWith("Submitted"));

            WaitFor(HasMessageArrived, this, 10 * 1000);
            Assert.IsNotNull(_receivedMessage);
            Assert.AreEqual(true, _receivedMessage.Contains("FieldValueUpdate"));


            StopTestListener(testMessageConsumer);
        }
예제 #15
0
        private static string PublishRecord(string topicName, string brokerUrl, IDictionary <string, string> message)
        {
            // Add some administration values
            message.Add(TextMessageUtil.TopicKeyName, topicName);
            message.Add(TextMessageUtil.TimestampKeyName, GenerateRecordTimestamp());

            var broker    = BrokerFactory.Broker(brokerUrl);
            var publisher = broker.TopicPublisher(topicName);

            publisher.Publish(topicName, message);

            // Use a thread here so we can tell (hopefully) when the broker is down.
            //if (!Connected) return "#PublishError - disconnected";
            return("Submitted " + GenerateResponseTimestamp());
        }
예제 #16
0
        /// <summary>
        /// Remove the Excel topic and clean up the subscribers.
        /// </summary>
        /// <param name="topicId"></param>
        public void DisconnectData(int topicId)
        {
            try {
                _log.Info("Disconnecting Excel topic " + topicId);
                lock (_topicToDetails) {
                    // handle the Topic Id first
                    if (!_topicToDetails.ContainsKey(topicId))
                    {
                        return;
                    }

                    var topicDetails = _topicToDetails[topicId];
                    _topicToDetails.Remove(topicId);

                    if (!_fieldToDetails.ContainsKey(topicDetails.BrokerUrl))
                    {
                        return;
                    }

                    var topics = _fieldToDetails[topicDetails.BrokerUrl];
                    if (!topics.ContainsKey(topicDetails.Topic))
                    {
                        return;
                    }

                    var fields = topics[topicDetails.Topic];
                    if (fields.Contains(topicDetails))
                    {
                        fields.Remove(topicDetails);
                    }
                    if (fields.Count == 0)
                    {
                        topics.Remove(topicDetails.Topic);
                    }
                    // If we have no interested parties, clean up the subscriber
                    if (topics.Count != 0)
                    {
                        return;
                    }

                    _fieldToDetails.Remove(topicDetails.BrokerUrl);
                    var broker = BrokerFactory.Broker(topicDetails.BrokerUrl);
                    broker.RemoveSubscriber(topicDetails.Topic);
                }
            } catch (Exception e) {
                _log.Error("Tried to disconnect Excel topic " + topicId, e);
            }
        }
예제 #17
0
        static void Main(string[] args)
        {
            using (var broker = BrokerFactory.Get <MqttBroker>())
            {
                var endpoint = new IPEndPoint(IPAddress.Any, 1883);
                broker.Listen(endpoint);

                Console.Write("Listening");

                while (true)
                {
                    Console.Write(".");
                    Thread.Sleep(10000);
                }
            }
        }
예제 #18
0
        public void TestServer()
        {
            var config = new AppConfiguration {
                PositionsBrokerUrl = BrokerFactoryTest.Nyws802
            };
            var             server             = new NmsRtdClient(config);
            IRTDUpdateEvent updateEventHandler = new TestEventHandler();
            var             startResult        = server.ServerStart(updateEventHandler);

            Assert.AreEqual(1, startResult);
            Assert.AreEqual(1, server.Heartbeat());
            var client = server.Client;

            var   newValues  = false;
            Array parameters = new[] { "account=Test|securityId=123|level1TagName=UnitTest", "FieldName1" };

            Assert.AreEqual("N/A", server.ConnectData(1, ref parameters, ref newValues));
            Assert.AreEqual(1, server.TopicCount);
            Assert.IsTrue(client.IsConnected());
            Assert.AreEqual("N/A", server.ConnectData(2, ref parameters, ref newValues));
            Assert.AreEqual(2, server.TopicCount);
            server.DisconnectData(2);
            Assert.AreEqual(1, server.TopicCount);

            var position = new Dictionary <string, string> {
                { "account", "Test" },
                { "securityId", "123" },
                { "level1TagName", "UnitTest" },
                { "FieldName1", "FirstTestValue" },
                { "messageType", "BatchPosition" }
            };

            var broker = BrokerFactory.Broker(config.PositionsBrokerUrl);

            Assert.IsNotNull(PublishTestMessage(broker, "position.Test", position));

            WaitFor(PositionMessage, client, 10000);
            var key = client.BuildPositionLookupKey("account=Test|securityId=123|level1TagName=UnitTest", "FieldName1");

            Assert.AreEqual("FirstTestValue", client.LookupValue(key, "FieldName1"));

            server.DisconnectData(1);
            Assert.AreEqual(0, server.TopicCount);

            server.ServerTerminate();
        }
        public void BrokerInteractiveRequest_CreateBrokerParametersTest()
        {
            using (var harness = CreateTestHarness())
            {
                // Arrange
                var parameters = harness.CreateAuthenticationRequestParameters(
                    MsalTestConstants.AuthorityTestTenant,
                    null,
                    null,
                    null,
                    MsalTestConstants.ExtraQueryParams);

                // Act
                BrokerFactory            brokerFactory            = new BrokerFactory();
                BrokerInteractiveRequest brokerInteractiveRequest =
                    new BrokerInteractiveRequest(
                        parameters,
                        null,
                        harness.ServiceBundle,
                        null,
                        brokerFactory.Create(harness.ServiceBundle));

                brokerInteractiveRequest.CreateRequestParametersForBroker();

                // Assert
                Assert.AreEqual(10, brokerInteractiveRequest.BrokerPayload.Count);

                Assert.AreEqual(s_canonicalizedAuthority, brokerInteractiveRequest.BrokerPayload[BrokerParameter.Authority]);
                Assert.AreEqual(MsalTestConstants.ScopeStr, brokerInteractiveRequest.BrokerPayload[BrokerParameter.Scope]);
                Assert.AreEqual(MsalTestConstants.ClientId, brokerInteractiveRequest.BrokerPayload[BrokerParameter.ClientId]);

                Assert.IsFalse(string.IsNullOrEmpty(brokerInteractiveRequest.BrokerPayload[BrokerParameter.CorrelationId]));
                Assert.AreNotEqual(Guid.Empty.ToString(), brokerInteractiveRequest.BrokerPayload[BrokerParameter.CorrelationId]);
                Assert.AreEqual(MsalIdHelper.GetMsalVersion(), brokerInteractiveRequest.BrokerPayload[BrokerParameter.ClientVersion]);
                Assert.AreEqual("NO", brokerInteractiveRequest.BrokerPayload[BrokerParameter.Force]);
                Assert.AreEqual(string.Empty, brokerInteractiveRequest.BrokerPayload[BrokerParameter.Username]);

                Assert.AreEqual(MsalTestConstants.RedirectUri, brokerInteractiveRequest.BrokerPayload[BrokerParameter.RedirectUri]);

                Assert.AreEqual(MsalTestConstants.BrokerExtraQueryParameters, brokerInteractiveRequest.BrokerPayload[BrokerParameter.ExtraQp]);

                //Assert.AreEqual(MsalTestConstants.BrokerClaims, brokerInteractiveRequest._brokerPayload[BrokerParameter.Claims]); //TODO
                Assert.AreEqual(BrokerParameter.OidcScopesValue, brokerInteractiveRequest.BrokerPayload[BrokerParameter.ExtraOidcScopes]);
            }
        }
예제 #20
0
        public List <PriceCandle> GetPriceCandles(string broker, string granularity, DateTime from, string mode = "Practice")
        {
            switch (broker)
            {
            case "Oanda":
                _factory = new OandaFactory(mode, _configuration);
                break;

            default:
                break;
            }

            BrokerConnection connection = _factory.GetBrokerConnection();

            List <PriceCandle> candle = connection.FetchCandles(granularity, from);

            return(candle);
        }
예제 #21
0
        public void TestPublisher()
        {
            var broker         = BrokerFactory.Broker(BrokerFactoryTest.Nyws802);
            var topicPublisher = broker.TopicPublisher(TestTopic);

            Assert.IsNotNull(topicPublisher);
            Assert.AreEqual(1, broker.PublisherCount);

            var topicPublisherSame = broker.TopicPublisher(TestTopic);

            Assert.IsNotNull(topicPublisher);
            Assert.AreEqual(1, broker.PublisherCount);
            Assert.AreSame(topicPublisher, topicPublisherSame);

            var topicPublisherDifferent = broker.TopicPublisher("Test.Library.Topic2");

            Assert.IsNotNull(topicPublisherDifferent);
            Assert.AreEqual(2, broker.PublisherCount);
            Assert.AreNotEqual(topicPublisher, topicPublisherDifferent);

            // Start up a test listener
            var testMessageConsumer = StartTestListener(broker, TestTopic);

            Assert.IsNotNull(topicPublisher.Publish("UnitTest.NMS.CSharp.Simple", "MyFieldName", "MyFieldValue"));
            WaitFor(HasMessageArrived, this, 10 * 1000);

            Assert.IsNotNull(_receivedMessage);
            Assert.AreEqual(true, _receivedMessage.Contains("MyFieldName"));
            _receivedMessage = null;

            IDictionary <string, string> testMessage = new Dictionary <string, string> {
                { "MyFieldName", "MyFieldValue" }
            };

            Assert.IsNotNull(topicPublisher.Publish(TestTopic, testMessage));

            WaitFor(HasMessageArrived, this, 10 * 1000);
            Assert.IsNotNull(_receivedMessage);
            Assert.AreEqual(true, _receivedMessage.Contains("MyFieldName"));

            StopTestListener(testMessageConsumer);

            BrokerFactory.Remove(BrokerFactoryTest.Nyws802);
        }
        public void BrokerInteractiveRequestTest()
        {
            string CanonicalizedAuthority = AuthorityInfo.CanonicalizeAuthorityUri(CoreHelpers.UrlDecode(MsalTestConstants.AuthorityTestTenant));

            using (var harness = CreateTestHarness())
            {
                // Arrange
                var parameters = harness.CreateAuthenticationRequestParameters(
                    MsalTestConstants.AuthorityTestTenant,
                    null,
                    null,
                    null,
                    MsalTestConstants.ExtraQueryParams);

                // Act
                BrokerFactory            brokerFactory            = new BrokerFactory();
                BrokerInteractiveRequest brokerInteractiveRequest = new BrokerInteractiveRequest(parameters, null, null, null, brokerFactory.Create(harness.ServiceBundle));
                Assert.AreEqual(false, brokerInteractiveRequest.Broker.CanInvokeBroker(null));
                AssertException.TaskThrowsAsync <PlatformNotSupportedException>(() => brokerInteractiveRequest.Broker.AcquireTokenUsingBrokerAsync(new Dictionary <string, string>())).ConfigureAwait(false);
            }
        }
예제 #23
0
        private void Close()
        {
            if (this.m_transaction != null)
            {
                try
                {
                    this.m_transaction.Dispose();
                }
                catch { }
            }

            if (this.m_dbConnection.State != ConnectionState.Closed)
            {
                try
                {
                    this.m_dbConnection.Dispose();
                }
                catch { }
            }
            BrokerFactory.DropCurrentBroker();
        }
예제 #24
0
        public static void InitialDatabaseConfigs(string dbConfigFile)
        {
            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.Load("~/DBHelper.config");
            IEbfConfig   dbConfigs     = ConfigFactory.GetConfigOf(dbConfigFile);
            TagElement   rootTag       = dbConfigs.RootTag;
            CompositeTag dataSourceTag = (CompositeTag)dbConfigs.FindTag("dblinks");

            GetDataSource(dataSourceTag);
            BrokerFactory.InitDataSource(DataSourceList);
            if (rootTag is CompositeTag)
            {
                foreach (CompositeTag dbConfig in ((CompositeTag)rootTag).SubTags)
                {
                    if (!dbConfig.Name.Equals("dslist"))
                    {
                        InitalizeDatabaseConfig(dbConfig);
                    }
                }
            }
        }
예제 #25
0
        private Task <NamedConnection> HandleNewConnection(Task <NetworkConnection> conn)
        {
            switch (conn.Status)
            {
            case TaskStatus.Faulted:
                if (conn.Exception != null)
                {
                    throw conn.Exception;
                }
                throw new InvalidOperationException("New connection faulted but there was no exception provided.");

            case TaskStatus.RanToCompletion:
                var connection = conn.Result;
                return(Task.Factory.StartNew(() =>
                {
                    var connRecv = BrokerFactory.Get <ConnectReceive>();
                    return connRecv.Run(connection);
                }));

            default:
                throw new NotImplementedException("say what?");
            }
        }
예제 #26
0
        public async Task CanProduceAndConsume()
        {
            var topic = BrokerFactory.GetNewTopic();

            var producer = BrokerFactory.ConfigureProducer()
                           .Topics(m => m.Map <string>(topic))
                           .Create();

            Using(producer);

            var gotTheString = new ManualResetEvent(false);

            var consumer = BrokerFactory.ConfigureConsumer("default-group")
                           .Handle(async(messages, token) =>
            {
                var receivedString = messages.Select(m => m.Body).FirstOrDefault() as string;

                if (receivedString == "HEJ MED DIG MIN VEN")
                {
                    gotTheString.Set();
                    return;
                }

                throw new ArgumentException($@"Did not receive the expected string 'HEJ MED DIG MIN VEN':

{messages.ToPrettyJson()}");
            })
                           .Topics(t => t.Subscribe(topic))
                           .Positions(p => p.StoreInMemory())
                           .Start();

            Using(consumer);

            await producer.Send("HEJ MED DIG MIN VEN");

            gotTheString.WaitOrDie(errorMessage: "Waited for the text 'HEJ MED DIG MIN VEN' to arrive in the consumer");
        }
예제 #27
0
        /// <summary>
        /// Create a new Excel topic.
        ///
        /// An Excel topic is a cell.  We may have multiple Excel topics listening to the same
        /// NMS topic.
        ///
        /// Parse the supplied values and create a mapping so that the application can
        /// send data back to the correct topic/cell.
        /// </summary>
        /// <param name="topicId"></param>
        /// <param name="strings">
        /// The first value is a string representing the topic.
        /// The second value is the field of interest.
        /// The third (optional) value is the broker.
        /// </param>
        /// <param name="getNewValues"></param>
        /// <returns></returns>
        public object ConnectData(int topicId, ref Array strings, ref bool getNewValues)
        {
            getNewValues = true; // over-write any saved values in the spreadsheet
            TopicDetails details = null;

            try {
                _log.Info("Creating subscriber for Excel topic " + topicId);
                // If we have a brokerUrl use it, otherwise use the default broker
                details = new TopicDetails {
                    TopicId   = topicId,
                    Topic     = ((string)strings.GetValue(0)),
                    Field     = ((string)strings.GetValue(1)),
                    BrokerUrl = _config.MarketDataBrokerUrl
                };

                if (strings.Length > 2)
                {
                    details.BrokerUrl = (string)strings.GetValue(2);
                }

                // setup our mappings
                lock (_topicToDetails) {
                    _topicToDetails.Add(topicId, details);

                    var detailList = GetFieldDetails(details);
                    if (!detailList.Contains(details))
                    {
                        detailList.Add(details);
                    }

                    var broker     = BrokerFactory.Broker(details.BrokerUrl);
                    var subscriber = broker.TopicSubscriber(details.Topic, _topicHandler.OnMessageHandler);
                    if (!_brokers.ContainsKey(details.BrokerUrl))
                    {
                        _brokers.Add(details.BrokerUrl, broker);
                    }

                    var rt = LookupValueFor(details.BrokerUrl, details.Topic, details.Field);
                    if (rt != null)
                    {
                        return(rt);
                    }
                }
                switch (details.Field)
                {
                case "productVersion":
                    return(_version);

                case "brokerUrl":
                    return(_config.MarketDataBrokerUrl);
                }
                return("N/A");
            } catch (Exception e) {
                _log.Error("Tried to subscribe to topic " + strings, e);

                if (details != null)
                {
                    SetLookupValue(details.BrokerUrl, details.Topic, details.Field, "#Error");
                }
                return("#Error");
            }
        }
예제 #28
0
        public async Task ConsumerCanPickUpWhereItLeftOff()
        {
            var receivedStrings = new ConcurrentQueue <string>();
            var topic           = BrokerFactory.GetNewTopic();

            var producer = BrokerFactory.ConfigureProducer()
                           .Topics(m => m.Map <string>(topic))
                           .Create();

            Using(producer);

            IDisposable CreateConsumer(InMemPositionsStorage storage)
            {
                return(BrokerFactory.ConfigureConsumer("default-group")
                       .Handle(async(messages, token) =>
                {
                    var strings = messages.Select(m => m.Body).Cast <string>();

                    receivedStrings.Enqueue(strings);
                })
                       .Topics(t => t.Subscribe(topic))
                       .Positions(p => p.StoreInMemory(storage))
                       .Start());
            }

            var positionsStorage = new InMemPositionsStorage();

            const string partitionKey = "same-every-time";

            using (CreateConsumer(positionsStorage))
            {
                await producer.Send("HEJ", partitionKey : partitionKey);

                await producer.Send("MED", partitionKey : partitionKey);

                await producer.Send("DIG", partitionKey : partitionKey);

                string GetFailureDetailsFunction() => $@"Got these strings:

{receivedStrings.ToPrettyJson()}";

                await receivedStrings.WaitOrDie(
                    completionExpression : q => q.Count == 3,
                    failExpression : q => q.Count > 3,
                    failureDetailsFunction : GetFailureDetailsFunction
                    );
            }

            Console.WriteLine($@"Got these positions after FIRST run:

{string.Join(Environment.NewLine, positionsStorage.GetAll(topic).Select(position => $"    {position}"))}

");

            using (CreateConsumer(positionsStorage))
            {
                await producer.Send("MIN", partitionKey : partitionKey);

                await producer.Send("SØDE", partitionKey : partitionKey);

                await producer.Send("VEN", partitionKey : partitionKey);

                await receivedStrings.WaitOrDie(q => q.Count == 6, failExpression : q => q.Count > 6);

                // additional delay to be absolutely sure that no additional messages arrive after this point
                await Task.Delay(TimeSpan.FromSeconds(1));
            }

            Console.WriteLine($@"Got these positions after SECOND run:

{string.Join(Environment.NewLine, positionsStorage.GetAll(topic).Select(position => $"    {position}"))}

");

            Assert.That(receivedStrings.Count, Is.EqualTo(6), $@"Queue did not contain 6 strings as expected:

{receivedStrings.ToPrettyJson()}");

            var expectedReceivedStrings = new[]
            {
                "HEJ",
                "MED",
                "DIG",
                "MIN",
                "SØDE",
                "VEN",
            };

            Assert.That(receivedStrings, Is.EqualTo(expectedReceivedStrings), $@"

Expected

    {string.Join(", ", expectedReceivedStrings)}

but got

    {string.Join(", ", receivedStrings)}

");
        }
예제 #29
0
 public void StartPublisher()
 {
     _log.Info("Using BrokerURL: " + BrokerUrl);
     _broker = BrokerFactory.Broker(BrokerUrl);
 }
예제 #30
0
        public void TestServerSubscribe()
        {
            var config = new AppConfiguration {
                MarketDataBrokerUrl = BrokerFactoryTest.Nyws802
            };

            var             server             = new ActiveMQRtdServer(config);
            IRTDUpdateEvent updateEventHandler = new TestEventHandler();
            var             startResult        = server.ServerStart(updateEventHandler);

            Assert.AreEqual(1, startResult);
            Assert.AreEqual(1, server.Heartbeat());

            // Use the default broker
            var   newValues  = false;
            Array parameters = new[] { "Test.Topic", "FieldName1" };

            Assert.AreEqual("N/A", server.ConnectData(1, ref parameters, ref newValues));
            Assert.IsTrue(newValues);
            Assert.AreEqual(1, server.TopicCount);
            Assert.AreEqual(1, server.FieldCount);

            var testBroker = BrokerFactory.Broker(BrokerFactoryTest.Nyws802);
            //PublishTestMessage(testBroker, "Test.Topic", "FieldName", "FieldValue");
            var multiFieldRecord = new Dictionary <string, string> {
                { "FieldName1", "FieldValue1" },
                { "FieldName2", "FieldValue2" }
            };

            PublishTestMessage(testBroker, "Test.Topic", multiFieldRecord);

            Thread.Sleep(1000);
            Assert.AreEqual("FieldValue1", server.ConnectData(2, ref parameters, ref newValues));
            Assert.AreEqual(2, server.TopicCount);
            Assert.AreEqual(1, server.FieldCount);

            // subscribe to field already in the message/cache
            parameters = new[] { "Test.Topic", "FieldName2" };
            Assert.AreEqual("FieldValue2", server.ConnectData(3, ref parameters, ref newValues));
            Assert.AreEqual(3, server.TopicCount);
            Assert.AreEqual(2, server.FieldCount);
            server.DisconnectData(3);
            Assert.AreEqual(2, server.TopicCount);
            Assert.AreEqual(1, server.FieldCount);

            var topicCount    = 0;
            var updatedTopics = server.RefreshData(ref topicCount);

            Assert.AreEqual(1, topicCount);
            Assert.IsNotNull(updatedTopics);

            // Publish again to ensure we get both updates
            Console.WriteLine("Publish second message, when we have two Excel topics");
            PublishTestMessage(testBroker, "Test.Topic", "FieldName1", "FieldValue1");
            Thread.Sleep(1000);

            Console.WriteLine("Calling Refresh");
            updatedTopics = server.RefreshData(ref topicCount);
            Assert.AreEqual(2, topicCount);
            Assert.IsNotNull(updatedTopics);

            server.DisconnectData(1);
            Assert.AreEqual(1, server.TopicCount);
            Assert.AreEqual(1, server.FieldCount);
            server.DisconnectData(2);
            Assert.AreEqual(0, server.TopicCount);
            Assert.AreEqual(0, server.FieldCount);

            // Check constant lookups
            var   newValues2  = false;
            Array parameters2 = new[] { "Test.Topic", "brokerUrl" };

            Assert.AreEqual(BrokerFactoryTest.Nyws802, server.ConnectData(10, ref parameters2, ref newValues2));

            parameters2 = new[] { "Test.Topic", "productVersion" };
            var productVersion = server.ConnectData(11, ref parameters2, ref newValues2);

            Assert.IsNotNull(productVersion);
            Assert.AreNotEqual("#Error", productVersion);
            Console.WriteLine(productVersion);
        }