Esempio n. 1
0
        public async Task Too_long_connect_delay_causes_unauthorized_error_in_Workspace_API()
        {
            var httpPost =
                new AgentApiHttpPoster(
                    new HttpClientHttpPost(await InitHttpClient()),
                    BaseUrl);

            //var initResponse = await httpClient.PostAsync(
            //    BaseURL + "/workspace/v3/initialize-workspace",
            //    new StringContent(""));
            //initResponse.EnsureSuccessStatusCode();

            var bayeuxClient = new BayeuxClient(new HttpLongPollingTransportOptions()
            {
                HttpPost = httpPost,
                Uri      = BaseUrl + "/workspace/v3/notifications",
            });

            using (bayeuxClient)
            {
                await bayeuxClient.Start();

                await bayeuxClient.Subscribe("/**");

                Thread.Sleep(TimeSpan.FromSeconds(11));
            }
        }
        public async Task Run_for_a_while_using_WebSocket()
        {
            // Begin: README example
            var bayeuxClient = new BayeuxClient(
                new WebSocketTransportOptions()
            {
                Uri = new Uri("ws://localhost:8080/bayeux/"),
            });

            // End: README example

            bayeuxClient.EventReceived += (e, args) =>
                                          Debug.WriteLine($"Event received on channel {args.Channel} with data\n{args.Data}");

            bayeuxClient.ConnectionStateChanged += (e, args) =>
                                                   Debug.WriteLine($"Bayeux connection state changed to {args.ConnectionState}");

            bayeuxClient.AddSubscriptions("/**");

            await bayeuxClient.Start();

            using (bayeuxClient)
            {
                await Delay(60);
            }
        }
        public async Task Run_for_a_while_using_HTTP()
        {
            // Begin: README example
            var httpClient   = new HttpClient();
            var bayeuxClient = new BayeuxClient(
                new HttpLongPollingTransportOptions()
            {
                HttpClient = httpClient,
                Uri        = "http://localhost:8080/bayeux/",
            });

            bayeuxClient.EventReceived += (e, args) =>
                                          Debug.WriteLine($"Event received on channel {args.Channel} with data\n{args.Data}");

            bayeuxClient.ConnectionStateChanged += (e, args) =>
                                                   Debug.WriteLine($"Bayeux connection state changed to {args.ConnectionState}");

            bayeuxClient.AddSubscriptions("/**");

            await bayeuxClient.Start();

            // End: README example

            using (bayeuxClient)
            {
                await Delay(60);
            }
        }
        public async Task Reconnections()
        {
            var mock = new Mock <HttpMessageHandler>();

            mock.Protected().As <IHttpMessageHandlerProtected>()
            .SetupSequence(h => h.SendAsync(It.IsAny <HttpRequestMessage>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(BuildBayeuxResponse(successfulHandshakeResponse))
            .ReturnsAsync(BuildBayeuxResponse(successfulConnectResponse))
            .ReturnsAsync(BuildBayeuxResponse(rehandshakeConnectResponse))
            .ThrowsAsync(new HttpRequestException("mock raising exception"))
            .ReturnsAsync(BuildBayeuxResponse(successfulHandshakeResponse))
            .ThrowsAsync(new HttpRequestException("mock raising exception"))
            .ThrowsAsync(new HttpRequestException("mock raising exception"))
            .ThrowsAsync(new HttpRequestException("mock raising exception"))
            .ThrowsAsync(new HttpRequestException("mock raising exception"))
            .ThrowsAsync(new HttpRequestException("mock raising exception"))
            .ReturnsIndefinitely(() =>
                                 Task.Delay(TimeSpan.FromSeconds(5))
                                 .ContinueWith(t => BuildBayeuxResponse(successfulHandshakeResponse)))
            ;

            var bayeuxClient = new BayeuxClient(
                new HttpLongPollingTransportOptions()
            {
                HttpClient = new HttpClient(mock.Object), Uri = Url
            },
                reconnectDelays: new[] { TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2) });

            using (bayeuxClient)
            {
                await bayeuxClient.Start();

                await Task.Delay(TimeSpan.FromSeconds(20));
            }
        }
Esempio n. 5
0
        /// <summary>
        /// Initializes a new instance of the <see cref="BayeuxClientState"/> class
        /// with the specified <see cref="BayeuxClientStates"/> type.
        /// </summary>
        protected BayeuxClientState(
            BayeuxClient session,
            BayeuxClientStates type,
            IDictionary <string, object> handshakeFields,
            IDictionary <string, object> advice,
            ClientTransport transport,
            string clientId,
            long backOff)
        {
            if (session == null)
            {
                throw new ArgumentNullException("session");
            }
            if (type == BayeuxClientStates.None)
            {
                throw new ArgumentOutOfRangeException("type");
            }
            if (transport == null)
            {
                throw new ArgumentNullException("transport");
            }

            _session = session;

            _type            = type;
            _handshakeFields = handshakeFields;
            _advice          = advice;
            _transport       = transport;
            _clientId        = clientId;
            _backOff         = backOff;
        }
        public void Connect(String access_token)
        {
            IList <ClientTransport> transports = new List <ClientTransport>();

            transports.Add(new LongPollingTransport(null));
            client = new BayeuxClient(url, transports);

            // Subscribe and call 'Initialize' after successful login
            initListener = new InitializerListener(Initialize);
            client.getChannel(Channel_Fields.META_HANDSHAKE).addListener(initListener);

            // Subscribe to connect/disconnect-events
            connectionListener = new ConnectionListener();
            client.getChannel(Channel_Fields.META_CONNECT).addListener(connectionListener);

            // Handshaking with oauth2
            IDictionary <String, Object> handshakeAuth = new Dictionary <String, Object>();

            handshakeAuth.Add("authType", "oauth2");
            handshakeAuth.Add("oauth_token", access_token);

            IDictionary <String, Object> ext = new Dictionary <String, Object>();

            ext.Add("ext", handshakeAuth);
            client.handshake(ext);
            client.handshake(handshakeAuth);
        }
Esempio n. 7
0
        private void tryToDelete(string mychannel)
        {
            //如果发哥的程序没有跟新就用下面这个调试
            //string url = "http://112.74.22.182:8080/BubbleServer/cometd";
            string url     = "http://112.74.22.182/cometd";
            var    options = new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase)
            {
                // CometD server socket timeout during connection: 2 minutes
                { ClientTransport.MaxNetworkDelayOption, 120000 }
            };

            using (client = new BayeuxClient(url, new LongPollingTransport(options)))
            {
                if (client.Handshake(null, 3000))  // Handshake timeout: 30 seconds
                {
                    IClientSessionChannel channel = client.GetChannel("/service/deleteRoom");
                    channel.Subscribe(new CallbackMessageListener <BayeuxClient>(ReplyForDelete, client));
                    var data = new Dictionary <string, string>()
                    {
                        { "roomId", mychannel }
                    };
                    channel.Publish(data);
                }
            }
        }
Esempio n. 8
0
 /// <summary>
 /// Initializes a new instance of the <see cref="HandshakingState"/> class
 /// with the specified handshaking message template: <paramref name="handshakeFields"/>.
 /// </summary>
 public HandshakingState(
     BayeuxClient session,
     IDictionary <string, object> handshakeFields,
     ClientTransport transport)
     : base(session, BayeuxClientStates.Handshaking, handshakeFields, null, transport, null, 0)
 {
 }
Esempio n. 9
0
        public static async Task BayeuxDemoAsync()
        {
            // Create the client settings.
            var endpoint = new Uri("https://localhost:8000/faye");
            var settings = new BayeuxClientSettings(endpoint)
            {
                Logger = new ConsoleLogger()
            };

            // Create the client.
            using (var client = new BayeuxClient(settings))
            {
                // Connect to server.
                await client.Connect();

                var extensions = new Dictionary <string, object>();
                //extensions.Add("access_token", "abc123");
                // Additional extensions can be added as needed

                // Subscribe to channel.
                await client.Subscribe("/test",
                                       message => Console.WriteLine("Message received: {0}", message.Channel),
                                       extensions);
            }
        }
Esempio n. 10
0
        public StreamingAPIClient(string userName, string password)
        {
            if (null == userName || (userName = userName.Trim()).Length == 0)
            {
                throw new ArgumentNullException("userName");
            }
            if (String.IsNullOrEmpty(password))
            {
                throw new ArgumentNullException("password");
            }

            _userName = userName;
            _password = password;

            // Initializes a new Bayeux client
            IDictionary <string, object> options = new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase)
            {
                // TODO: Salesforce socket timeout during connection (CometD session) = 110 seconds
                { ClientTransport.MaxNetworkDelayOption, 120000 }
            };

            _clientTransport = new LongPollingTransport(options);
            // TODO: DefaultInstanceUrl "https://na14.salesforce.com/" + StreamingAPIEndpoint
            _bayeuxClient = new BayeuxClient(null, _clientTransport);
        }
 protected override void StopImpl(UpdateResult result)
 {
     if (bayeuxClient != null)
     {
         bayeuxClient.Dispose();
         bayeuxClient = null;
     }
 }
Esempio n. 12
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ReHandshakingState"/> class
 /// with the specified handshaking message template: <paramref name="handshakeFields"/>.
 /// </summary>
 public ReHandshakingState(
     BayeuxClient session,
     IDictionary <string, object> handshakeFields,
     ClientTransport transport,
     long backOff)
     : base(session, BayeuxClientStates.ReHandshaking, handshakeFields, null, transport, null, backOff)
 {
 }
 public async Task Unsubscribe_throws_exception_when_not_connected()
 {
     var httpPoster   = new Mock <IHttpPost>();
     var bayeuxClient = new BayeuxClient(new HttpLongPollingTransportOptions()
     {
         HttpPost = httpPoster.Object, Uri = "none"
     });
     await bayeuxClient.Unsubscribe("dummy");
 }
Esempio n. 14
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ConnectedState"/> class
 /// with the specified handshaking message template: <paramref name="handshakeFields"/>,
 /// and the last received information from a Bayeux server like: <paramref name="advice"/>, <paramref name="clientId"/>.
 /// </summary>
 public ConnectedState(
     BayeuxClient session,
     IDictionary <string, object> handshakeFields,
     IDictionary <string, object> advice,
     ClientTransport transport,
     string clientId)
     : base(session, BayeuxClientStates.Connected, handshakeFields, advice, transport, clientId, 0)
 {
 }
 public async Task RemoveSubscriptions_succeeds_when_not_connected()
 {
     var mock         = new Mock <HttpMessageHandler>();
     var bayeuxClient = new BayeuxClient(new HttpLongPollingTransportOptions()
     {
         HttpClient = new HttpClient(mock.Object), Uri = "none"
     });
     await bayeuxClient.RemoveSubscriptionsAsync("dummy");
 }
Esempio n. 16
0
        /// <summary>
        /// Initializes a new instance of the <see cref="PublishTransportListener"/> class.
        /// </summary>
        /// <param name="session">The Bayeux client session.</param>
        public PublishTransportListener(BayeuxClient session)
        {
            if (null == session)
            {
                throw new ArgumentNullException("session");
            }

            _session = session;
        }
 public async Task Unsubscribe_throws_exception_when_not_connected()
 {
     var mock         = new Mock <HttpMessageHandler>();
     var bayeuxClient = new BayeuxClient(new HttpLongPollingTransportOptions()
     {
         HttpClient = new HttpClient(mock.Object), Uri = "none"
     });
     await bayeuxClient.UnsubscribeAsync("dummy");
 }
Esempio n. 18
0
        /// <summary>
        /// Initializes a new instance of the <see cref="BayeuxClientChannel"/> class
        /// with the specified <see cref="ChannelId"/>.
        /// </summary>
        public BayeuxClientChannel(BayeuxClient session, ChannelId channelId)
            : base(channelId)
        {
            if (null == session)
            {
                throw new ArgumentNullException("session");
            }

            _bayeuxClient = session;
        }
Esempio n. 19
0
 /// <summary>
 /// Initializes a new instance of the <see cref="UnconnectedState"/> class
 /// with the specified handshaking message template: <paramref name="handshakeFields"/>,
 /// and the last received information from a Bayeux server like: <paramref name="advice"/>, <paramref name="clientId"/>.
 /// </summary>
 public UnconnectedState(
     BayeuxClient session,
     IDictionary <string, object> handshakeFields,
     IDictionary <string, object> advice,
     ClientTransport transport,
     string clientId,
     long backOff)
     : base(session, BayeuxClientStates.Unconnected, handshakeFields, advice, transport, clientId, backOff)
 {
 }
        public void RemoveSubscriptions_succeeds_when_not_connected()
        {
            var httpPoster   = new Mock <IHttpPost>();
            var bayeuxClient = new BayeuxClient(new HttpLongPollingTransportOptions()
            {
                HttpPost = httpPoster.Object, Uri = "none"
            });

            bayeuxClient.RemoveSubscriptions("dummy");
        }
Esempio n. 21
0
        public GitterAdapter(GitterBroker broker, GitterConfiguration configuration, IMessageQueue messageQueue, ILog log)
        {
            _broker       = broker;
            _messageQueue = messageQueue;
            _log          = new AdapterLog("Gitter", log);

            // Create the Bayeux client.
            var settings = new BayeuxClientSettings(new Uri("https://ws.gitter.im/faye"));

            settings.Extensions.Add(new GitterTokenExtension(configuration.Token));
            _bayeux = new BayeuxClient(settings);
        }
Esempio n. 22
0
        static void Main(string[] args)
        {
            var longPollingTransport = new LongPollingTransport(null)
            {
                HeaderCollection = new WebHeaderCollection
                {
                    new NameValueCollection
                    {
                        {
                            "Content-Type",
                            "application/json"
                        },
                        {
                            "Authorization",
                            $"Bearer {accessToken}"
                        }
                    },
                },
                CookieCollection = new CookieCollection(),
            };

            var client = new BayeuxClient(url, new List <ClientTransport> {
                longPollingTransport
            });

            // Save the newReplayId in a reliable way. This is basically the last message processed
            // So when your application recovers a crash the next subscription should start from the last replay id processed
            var replayExtension = new ReplayExtension((changedChannel, newReplayId) => Console.WriteLine($"{changedChannel}: {newReplayId}"));

            replayExtension.SetReplayId(channelName, replayId);
            client.AddExtension(replayExtension);

            client.Handshake(new Dictionary <string, object>
            {
                { MessageFields.ReplayField, true }
            });

            var result = client.WaitFor(6000, new List <BayeuxClient.State> {
                BayeuxClient.State.Connected
            });

            // Subscription to channels
            IClientSessionChannel channel = client.GetChannel(channelName);
            var listener = new SimpleListener();

            channel.Subscribe(listener);
            //channel.Unsubscribe(listener);
            //replayExtension.SetReplayId(channelName, 100);
            //channel.Subscribe(listener);

            Thread.Sleep(Timeout.Infinite);
        }
Esempio n. 23
0
 private static async Task WaitForEvent(BayeuxClient bc)
 {
     await new TaskFactory().StartNew(() =>
     {
         while (true)
         {
             manualResetEvent.WaitOne();
             bc.EventReceived += (e, args) =>
                                 Console.WriteLine($"Event received on channel {args.Channel} with data\n{args.Data}");
             manualResetEvent.Reset();
         }
     });
 }
Esempio n. 24
0
        // response: {"timestamp":1536851691737,"status":500,"error":"Internal Server Error",
        // "message":"java.lang.IllegalArgumentException: Invalid channel id: pepe",
        // "path":"/statistics/v3/notifications"}
        public async Task Subscribe_invalid_channel_id()
        {
            var httpClient = await InitHttpClient();

            var bayeuxClient = new BayeuxClient(new HttpLongPollingTransportOptions()
            {
                HttpClient = httpClient,
                Uri        = BaseUrl + "/statistics/v3/notifications",
            });
            await bayeuxClient.Start();

            await bayeuxClient.Subscribe("pepe");
        }
        public void Initialize(StatisticsApi api)
        {
            WebHeaderCollection headers = new WebHeaderCollection();

            foreach (string key in api.Configuration.DefaultHeader.Keys)
            {
                switch (key)
                {
                case "x-api-key":
                case "Authorization":
                    headers.Add(key, api.Configuration.DefaultHeader[key]);
                    break;
                }
            }

            CookieCollection cookieCollection = CookieManager.Cookies.GetCookies(new Uri(api.GetBasePath()));

            /**
             * GWS currently only supports LongPolling as a method to receive events.
             * So tell the CometD library to negotiate a handshake with GWS and setup a LongPolling session.
             */
            LongPollingTransport transport = new LongPollingTransport(null);

            transport.CookieCollection = cookieCollection;
            transport.HeaderCollection = headers;

            bayeuxClient = new BayeuxClient(api.GetBasePath() + "/notifications", new List <CometD.NetCore.Client.Transport.ClientTransport>()
            {
                transport
            });

            bayeuxClient.Handshake();
            bayeuxClient.WaitFor(30000, new List <BayeuxClient.State>()
            {
                BayeuxClient.State.Connected
            });

            if (bayeuxClient.Connected)
            {
                foreach (Cookie cookie in cookieCollection)
                {
                    CookieManager.AddCookie(cookie);
                }

                foreach (string channelName in subscriptions.Keys)
                {
                    IClientSessionChannel channel = bayeuxClient.GetChannel(channelName);
                    channel.Subscribe(this);
                }
            }
        }
Esempio n. 26
0
        static void Main(string[] args)
        {
            var uri = args[0];

            Console.WriteLine("URI: " + uri);
            var channel = args[1];

            Console.WriteLine("Channel: " + channel);

            BayeuxClient bc = SubToStream(uri, channel).Result;

            manualResetEvent.Set();
            WaitForEvent(bc).Wait();
        }
Esempio n. 27
0
        public RealtimeGitterService(string token)
        {
            // Create the client
            var endpoint = new Uri(Constants.FayeBaseUrl);
            var settings = new BayeuxClientSettings(endpoint)
            {
                Logger = new ConsoleLogger()
            };

            settings.Extensions.Add(new TokenBayeuxProtocolExtension {
                Token = token
            });

            _client = new BayeuxClient(settings);
        }
Esempio n. 28
0
        BayeuxClient InitStatisticsBayeuxClient(HttpClient httpClient)
        {
            var bayeuxClient = new BayeuxClient(new HttpLongPollingTransportOptions()
            {
                HttpClient = httpClient,
                Uri        = BaseUrl + "/statistics/v3/notifications",
            });

            bayeuxClient.EventReceived += (e, args) =>
                                          Debug.WriteLine($"Event received on channel {args.Channel} with data\n{args.Data}");

            bayeuxClient.ConnectionStateChanged += (e, args) =>
                                                   Debug.WriteLine($"Bayeux connection state changed to {args.ConnectionState}");

            return(bayeuxClient);
        }
        private void InitBayeuxClient()
        {
            if (_isDisposed)
            {
                throw new ObjectDisposedException("Cannot create connection when disposed");
            }

            _logger.LogDebug("Initializing {name} ...", nameof(BayeuxClient));

            if (!_authenticationClient.IsAuthenticated)
            {
                Reauthenticate();
            }

            _tokenInfo = _authenticationClient.AuthenticationClient.AccessInfo;

            // Salesforce socket timeout during connection(CometD session) = 110 seconds
            var options = new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase)
            {
                { ClientTransport.TIMEOUT_OPTION, _options.ReadTimeOut ?? ReadTimeOut },
                { ClientTransport.MAX_NETWORK_DELAY_OPTION, _options.ReadTimeOut ?? ReadTimeOut }
            };

            var headers = new NameValueCollection {
                { HttpRequestHeader.Authorization.ToString(), $"OAuth {_tokenInfo.AccessToken}" }
            };

            _clientTransport = new LongPollingTransport(options, headers);

            // only need the scheme and host, strip out the rest
            var serverUri = new Uri(_tokenInfo.InstanceUrl);
            var endpoint  = $"{serverUri.Scheme}://{serverUri.Host}{_options.CometDUri}";

            _bayeuxClient = new BayeuxClient(endpoint, _clientTransport);

            // adds logging and also raises an event to process reconnection to the server.
            _errorExtension = new ErrorExtension();
            _errorExtension.ConnectionError     += ErrorExtension_ConnectionError;
            _errorExtension.ConnectionException += ErrorExtension_ConnectionException;
            _errorExtension.ConnectionMessage   += ErrorExtension_ConnectionMessage;
            _bayeuxClient.AddExtension(_errorExtension);

            _replayIdExtension = new ReplayExtension();
            _bayeuxClient.AddExtension(_replayIdExtension);

            _logger.LogDebug("{name} initializing completed...", nameof(BayeuxClient));
        }
Esempio n. 30
0
 private void ReplyForDelete(IClientSessionChannel channel, IMessage message, BayeuxClient client)
 {
     //IDictionary<String, Object> data = message.DataAsDictionary;
     //string state = (string)data["status"];
     //string msg = (string)data["message"];
     //if (state.Equals("OK"))
     //{
     //    enterSuccess = status.success;
     //}
     //else
     //{
     //    if (MessageBox.Show(msg + "\nwould you like to enter this channel", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
     //        enterSuccess = status.success;
     //    else
     //        enterSuccess = status.fail;
     //}
 }