/// <summary> /// Подписывает запрос /// </summary> /// <param name="httpMethod"> /// метод, используемый для запроса /// </param> /// <param name="requestUrl"> /// адрес для запроса /// </param> /// <param name="requestParameters"> /// параметры запроса /// </param> /// <param name="consumerInfo"> /// информация о программе клиенте /// </param> /// <param name="token"> /// токен /// </param> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="ArgumentOutOfRangeException"></exception> /// <returns> /// подписанная сторока запроса /// </returns> public static string Sign(HttpMethods httpMethod, string requestUrl, List<RequestParameter> requestParameters, ConsumerInfo consumerInfo, OAuthToken token) { if (consumerInfo.CallbackUrl == null && consumerInfo.ConsumerKey == null && consumerInfo.ConsumerSecret == null) throw new ArgumentNullException("consumerInfo"); // Подготовка и нормализация операндов для подписи // Определяем метод запроса if ((httpMethod < 0) && (httpMethod > (HttpMethods) 3)) throw new ArgumentOutOfRangeException("httpMethod"); var baseHttpMethod = httpMethod.ToString().ToUpper() + "&"; // определяем и нормализуем Url запроса if (string.IsNullOrWhiteSpace(requestUrl)) throw new ArgumentNullException("requestUrl"); var baseRequesUrl = Uri.EscapeDataString(requestUrl) + "&"; // Определяем и нормализуем параметры запроса if (requestParameters == null) throw new ArgumentNullException("requestParameters"); // нормализуем и сортируем список параметров requestParameters = NormalizeRequestParameters(requestParameters); var baseParameters = string.Join("&", requestParameters.Select(param => param.Name + "=" + param.Value)); //строка для подписывания var baseRequestString = baseHttpMethod + baseRequesUrl + Uri.EscapeDataString(baseParameters); #if DEBUG Debug.WriteLine(string.Format("Подписываемая строка {0}", baseRequestString)); #endif // Определяем ключ для подписи var baseKey = token == null ? consumerInfo.ConsumerSecret + "&" + string.Empty : consumerInfo.ConsumerSecret + "&" + token.Secret; // осуществляем шифрование var encoder = new HMACSHA1 {Key = Encoding.ASCII.GetBytes(baseKey)}; var buffer = Encoding.ASCII.GetBytes(baseRequestString); var signatureByte = encoder.ComputeHash(buffer, 0, buffer.Length); // получаем стороку подписи в представлении Base64 var sigmature = Convert.ToBase64String(signatureByte); #if DEBUG Debug.WriteLine(string.Format("Подписанная строка {0}", sigmature)); #endif /* Формируем подписанную строку запроса */ // Для формирования стоки запроса к параметрам добавляем параметр с цифровой подписью requestParameters.Add(new RequestParameter(OAuthParam.Signature, NormalizeParameter(sigmature))); // формируем строку var signedUrlString = requestUrl + "?" + string.Join("&", requestParameters.Select(param => param.Name + "=" + param.Value)); #if DEBUG Debug.WriteLine(string.Format("Подписанная строка запроса {0}", signedUrlString)); #endif // возвращаем подписанную строку return signedUrlString; }
/// <summary> /// Регистриует клиент атентификации 500px.com /// <example> /// <code> /// ConsumerInfo consumer = new ConsumerInfo("consumerKey", "consumerSecret", "callbackUrl"); /// OAuthBroker client = new OAuthBroker().RegisterClient("name", consumer); /// </code> /// </example> /// </summary> /// <param name="consumerInfo"> /// <see cref="ConsumerInfo" /> /// информация о клиентском приложении /// </param> /// <returns> /// объект клиента аутентификации 500px.com /// </returns> public OAuthBroker RegisterClient(ConsumerInfo consumerInfo) { try { if (consumerInfo.IsEmpty) throw new ArgumentNullException("consumerInfo"); Consumer = consumerInfo; } catch (ArgumentNullException exception) { MessageBox.Show(exception.Message); } return this; }
private ConsumerInfo BuildConsumerInfo(string group, string consumerId, string topic, int queueId) { var queueCurrentOffset = _queueStore.GetQueueCurrentOffset(topic, queueId); var consumerInfo = new ConsumerInfo(); consumerInfo.ConsumerGroup = group; consumerInfo.ConsumerId = consumerId; consumerInfo.Topic = topic; consumerInfo.QueueId = queueId; consumerInfo.QueueCurrentOffset = queueCurrentOffset; consumerInfo.ConsumedOffset = _offsetStore.GetConsumeOffset(topic, queueId, group); return(consumerInfo); }
public void AddConsumer(ConsumerInfo info) { CheckShutdown(); ConsumerState consumerState = new ConsumerState(info); if (consumers.ContainsKey(info.ConsumerId)) { consumers.Add(info.ConsumerId, consumerState); } else { consumers.Add(info.ConsumerId, consumerState); } }
private ConsumerInfo BuildConsumerInfo(string group, string consumerId, string topic, int queueId) { var queueCurrentOffset = _queueService.GetQueueCurrentOffset(topic, queueId); var consumerInfo = new ConsumerInfo(); consumerInfo.ConsumerGroup = group; consumerInfo.ConsumerId = consumerId; consumerInfo.Topic = topic; consumerInfo.QueueId = queueId; consumerInfo.QueueMaxOffset = queueCurrentOffset; consumerInfo.ConsumedOffset = _offsetManager.GetQueueOffset(topic, queueId, group); consumerInfo.UnConsumedMessageCount = consumerInfo.QueueMaxOffset - consumerInfo.ConsumedOffset; return(consumerInfo); }
ConsumerInfo createConsumer(SessionInfo parent) { ConsumerId id = new ConsumerId(); id.ConnectionId = parent.SessionId.ConnectionId; id.SessionId = parent.SessionId.Value; id.Value = consumerIdx++; ConsumerInfo info = new ConsumerInfo(); info.ConsumerId = id; return(info); }
protected virtual void WriteConsumerInfo(ConsumerInfo command, BinaryWriter dataOut) { var frame = new StompFrame("SUBSCRIBE", _encodeHeaders); if (command.ResponseRequired) { frame.SetProperty("receipt", command.CommandId); } frame.SetProperty("destination", Destination.ConvertToStompString(command.Destination)); frame.SetProperty("id", command.ConsumerId.ToString()); frame.SetProperty("durable-subscriber-name", command.SubscriptionName); frame.SetProperty("selector", command.Selector); frame.SetProperty("ack", StompHelper.ToStomp(command.AckMode)); if (command.NoLocal) { frame.SetProperty("no-local", command.NoLocal.ToString()); } // ActiveMQ extensions to STOMP frame.SetProperty("transformation", command.Transformation ?? "jms-xml"); frame.SetProperty("activemq.dispatchAsync", command.DispatchAsync); if (command.Exclusive) { frame.SetProperty("activemq.exclusive", command.Exclusive); } if (command.SubscriptionName != null) { frame.SetProperty("activemq.subscriptionName", command.SubscriptionName); // For an older 4.0 broker we need to set this header so they get the // subscription as well.. frame.SetProperty("activemq.subcriptionName", command.SubscriptionName); } frame.SetProperty("activemq.maximumPendingMessageLimit", command.MaximumPendingMessageLimit); frame.SetProperty("activemq.prefetchSize", command.PrefetchSize); frame.SetProperty("activemq.priority", command.Priority); if (command.Retroactive) { frame.SetProperty("activemq.retroactive", command.Retroactive); } frame.ToStream(dataOut); }
// Constructor internal to prevent clients from creating an instance. internal MessageConsumer(Session session, ConsumerId id, ActiveMQDestination destination, String name, String selector, int prefetch, int maxPendingMessageCount, bool noLocal, bool browser, bool dispatchAsync) { if (destination == null) { throw new InvalidDestinationException("Consumer cannot receive on Null Destinations."); } this.session = session; this.redeliveryPolicy = this.session.Connection.RedeliveryPolicy; this.messageTransformation = this.session.Connection.MessageTransformation; if (session.Connection.MessagePrioritySupported) { this.unconsumedMessages = new SimplePriorityMessageDispatchChannel(); } else { this.unconsumedMessages = new FifoMessageDispatchChannel(); } this.info = new ConsumerInfo(); this.info.ConsumerId = id; this.info.Destination = destination; this.info.SubscriptionName = name; this.info.Selector = selector; this.info.PrefetchSize = prefetch; this.info.MaximumPendingMessageLimit = maxPendingMessageCount; this.info.NoLocal = noLocal; this.info.Browser = browser; this.info.DispatchAsync = dispatchAsync; this.info.Retroactive = session.Retroactive; this.info.Exclusive = session.Exclusive; this.info.Priority = session.Priority; // If the destination contained a URI query, then use it to set public properties // on the ConsumerInfo if (destination.Options != null) { // Get options prefixed with "consumer.*" StringDictionary options = URISupport.GetProperties(destination.Options, "consumer."); // Extract out custom extension options "consumer.nms.*" StringDictionary customConsumerOptions = URISupport.ExtractProperties(options, "nms."); URISupport.SetProperties(this.info, options); URISupport.SetProperties(this, customConsumerOptions, "nms."); } }
protected virtual void WriteConsumerInfo(ConsumerInfo command, BinaryWriter dataOut) { var frame = new StompFrame("SUBSCRIBE", _encodeHeaders); if (command.ResponseRequired) { frame.SetProperty(PropertyKeys.Receipt, command.CommandId); } frame.SetProperty(PropertyKeys.Destination, command.Destination?.ConvertToStompString()); frame.SetProperty(PropertyKeys.Id, command.ConsumerId.ToString()); frame.SetProperty(PropertyKeys.DurableSubscriberName, command.SubscriptionName); frame.SetProperty(PropertyKeys.Selector, command.Selector); frame.SetProperty(PropertyKeys.Ack, StompHelper.ToStomp(command.AckMode)); if (command.NoLocal) { frame.SetProperty(PropertyKeys.NoLocal, command.NoLocal.ToString()); } // ActiveMQ extensions to STOMP frame.SetProperty(PropertyKeys.Transformation, command.Transformation ?? "jms-xml"); frame.SetProperty(PropertyKeys.ActivemqDispatchAsync, command.DispatchAsync); if (command.Exclusive) { frame.SetProperty(PropertyKeys.ActivemqExclusive, command.Exclusive); } if (command.SubscriptionName != null) { frame.SetProperty(PropertyKeys.ActivemqSubscriptionName, command.SubscriptionName); // For an older 4.0 broker we need to set this header so they get the // subscription as well.. frame.SetProperty(PropertyKeys.ActivemqSubcriptionName, command.SubscriptionName); } frame.SetProperty(PropertyKeys.ActivemqMaximumPendingMessageLimit, command.MaximumPendingMessageLimit); frame.SetProperty(PropertyKeys.ActivemqPrefetchSize, command.PrefetchSize); frame.SetProperty(PropertyKeys.ActivemqPriority, command.Priority); if (command.Retroactive) { frame.SetProperty(PropertyKeys.ActivemqRetroactive, command.Retroactive); } frame.ToStream(dataOut); }
private void AddConsumers(IJetStreamManagement jsm, string stream, int count, string durableVary, string filterSubject) { for (int x = 0; x < count; x++) { String dur = Durable(durableVary, x + 1); ConsumerConfiguration cc = ConsumerConfiguration.Builder() .WithDurable(dur) .WithFilterSubject(filterSubject) .Build(); ConsumerInfo ci = jsm.AddOrUpdateConsumer(stream, cc); Assert.Equal(dur, ci.Name); Assert.Equal(dur, ci.ConsumerConfiguration.Durable); Assert.Empty(ci.ConsumerConfiguration.DeliverSubject); } }
public Task AddConsumer(Consumer <T> consumer, CancellationToken token) { ConsumerInfo info = new ConsumerInfo() { consumer = consumer, tokenSource = this.token == token ? tokenSource : CancellationTokenSource.CreateLinkedTokenSource(token), token = token }; Task task = new Task(Consume, info, token); info.associatedTaks = task; task.Start(); consumers.Add(consumer, info); return(task); }
public static void EnsureNotBound(IJetStreamSubscription sub) { ConsumerInfo ci = sub.GetConsumerInformation(); Stopwatch sw = Stopwatch.StartNew(); while (ci.PushBound) { if (sw.ElapsedMilliseconds > 5000) { return; // don't wait forever } Thread.Sleep(5); ci = sub.GetConsumerInformation(); } }
private ConsumerInfo BuildConsumerInfo(string groupName, string consumerId, MessageQueueEx messageQueue) { var queueCurrentOffset = _queueStore.GetQueueCurrentOffset(messageQueue.Topic, messageQueue.QueueId); var consumerInfo = new ConsumerInfo(); consumerInfo.ConsumerGroup = groupName; consumerInfo.ConsumerId = consumerId; consumerInfo.Topic = messageQueue.Topic; consumerInfo.QueueId = messageQueue.QueueId; consumerInfo.ClientCachedMessageCount = messageQueue.ClientCachedMessageCount; consumerInfo.QueueCurrentOffset = queueCurrentOffset; consumerInfo.ConsumedOffset = _consumeOffsetStore.GetConsumeOffset(messageQueue.Topic, messageQueue.QueueId, groupName); consumerInfo.QueueNotConsumeCount = consumerInfo.CalculateQueueNotConsumeCount(); return(consumerInfo); }
public void TestGetConsumerInfo() { Context.RunInJsServer(c => { IJetStreamManagement jsm = c.CreateJetStreamManagementContext(); CreateDefaultTestStream(jsm); Assert.Throws <NATSJetStreamException>(() => jsm.DeleteConsumer(STREAM, DURABLE)); ConsumerConfiguration cc = ConsumerConfiguration.Builder().WithDurable(DURABLE).Build(); ConsumerInfo ci = jsm.AddOrUpdateConsumer(STREAM, cc); Assert.Equal(STREAM, ci.Stream); Assert.Equal(DURABLE, ci.Name); ci = jsm.GetConsumerInfo(STREAM, DURABLE); Assert.Equal(STREAM, ci.Stream); Assert.Equal(DURABLE, ci.Name); Assert.Throws <NATSJetStreamException>(() => jsm.GetConsumerInfo(STREAM, Durable(999))); }); }
private void AssertValidAddOrUpdate(IJetStreamManagement jsm, ConsumerConfiguration cc) { ConsumerInfo ci = jsm.AddOrUpdateConsumer(STREAM, cc); ConsumerConfiguration cicc = ci.ConsumerConfiguration; Assert.Equal(cc.Durable, ci.Name); Assert.Equal(cc.Durable, cicc.Durable); Assert.Equal(cc.DeliverSubject, cicc.DeliverSubject); Assert.Equal(cc.MaxDeliver, cicc.MaxDeliver); Assert.Equal(cc.DeliverPolicy, cicc.DeliverPolicy); IList <string> consumers = jsm.GetConsumerNames(STREAM); Assert.Single(consumers); Assert.Equal(cc.Durable, consumers[0]); }
internal static unsafe uint SNIOpenMarsSession(ConsumerInfo consumerInfo, SNIHandle parent, ref IntPtr pConn, bool fSync, SqlConnectionIPAddressPreference ipPreference, SQLDNSInfo cachedDNSInfo) { // initialize consumer info for MARS Sni_Consumer_Info native_consumerInfo = new Sni_Consumer_Info(); MarshalConsumerInfo(consumerInfo, ref native_consumerInfo); SNI_DNSCache_Info native_cachedDNSInfo = new SNI_DNSCache_Info(); native_cachedDNSInfo.wszCachedFQDN = cachedDNSInfo?.FQDN; native_cachedDNSInfo.wszCachedTcpIPv4 = cachedDNSInfo?.AddrIPv4; native_cachedDNSInfo.wszCachedTcpIPv6 = cachedDNSInfo?.AddrIPv6; native_cachedDNSInfo.wszCachedTcpPort = cachedDNSInfo?.Port; return(SNIOpenWrapper(ref native_consumerInfo, "session:", parent, out pConn, fSync, ipPreference, ref native_cachedDNSInfo)); }
public void RemoveConsumer(Consumer <T> consumer) { ConsumerInfo info = consumers[consumer]; info.tokenSource.Cancel(); try { info.associatedTaks.Wait(); } catch (Exception) { //log //throw; } consumers.Remove(consumer); }
// // Un-marshal an object instance from the data input stream // public override void TightUnmarshal(OpenWireFormat wireFormat, Object o, BinaryReader dataIn, BooleanStream bs) { base.TightUnmarshal(wireFormat, o, dataIn, bs); ConsumerInfo info = (ConsumerInfo)o; info.ConsumerId = (ConsumerId) TightUnmarshalCachedObject(wireFormat, dataIn, bs); info.Browser = bs.ReadBoolean(); info.Destination = (ActiveMQDestination) TightUnmarshalCachedObject(wireFormat, dataIn, bs); info.PrefetchSize = dataIn.ReadInt32(); info.MaximumPendingMessageLimit = dataIn.ReadInt32(); info.DispatchAsync = bs.ReadBoolean(); info.Selector = TightUnmarshalString(dataIn, bs); info.SubscriptionName = TightUnmarshalString(dataIn, bs); info.NoLocal = bs.ReadBoolean(); info.Exclusive = bs.ReadBoolean(); info.Retroactive = bs.ReadBoolean(); info.Priority = dataIn.ReadByte(); if (bs.ReadBoolean()) { short size = dataIn.ReadInt16(); BrokerId[] value = new BrokerId[size]; for( int i=0; i < size; i++ ) { value[i] = (BrokerId) TightUnmarshalNestedObject(wireFormat,dataIn, bs); } info.BrokerPath = value; } else { info.BrokerPath = null; } info.AdditionalPredicate = (BooleanExpression) TightUnmarshalNestedObject(wireFormat, dataIn, bs); info.NetworkSubscription = bs.ReadBoolean(); info.OptimizedAcknowledge = bs.ReadBoolean(); info.NoRangeAcks = bs.ReadBoolean(); if (bs.ReadBoolean()) { short size = dataIn.ReadInt16(); ConsumerId[] value = new ConsumerId[size]; for( int i=0; i < size; i++ ) { value[i] = (ConsumerId) TightUnmarshalNestedObject(wireFormat,dataIn, bs); } info.NetworkConsumerPath = value; } else { info.NetworkConsumerPath = null; } }
internal static unsafe uint SNIOpenSyncEx(ConsumerInfo consumerInfo, string constring, ref IntPtr pConn, byte[] spnBuffer, byte[] instanceName, bool fOverrideCache, bool fSync, int timeout, bool fParallel, SqlConnectionIPAddressPreference ipPreference, SQLDNSInfo cachedDNSInfo) { fixed(byte *pin_instanceName = &instanceName[0]) { SNI_CLIENT_CONSUMER_INFO clientConsumerInfo = new SNI_CLIENT_CONSUMER_INFO(); // initialize client ConsumerInfo part first MarshalConsumerInfo(consumerInfo, ref clientConsumerInfo.ConsumerInfo); clientConsumerInfo.wszConnectionString = constring; clientConsumerInfo.networkLibrary = PrefixEnum.UNKNOWN_PREFIX; clientConsumerInfo.szInstanceName = pin_instanceName; clientConsumerInfo.cchInstanceName = (uint)instanceName.Length; clientConsumerInfo.fOverrideLastConnectCache = fOverrideCache; clientConsumerInfo.fSynchronousConnection = fSync; clientConsumerInfo.timeout = timeout; clientConsumerInfo.fParallel = fParallel; clientConsumerInfo.transparentNetworkResolution = TransparentNetworkResolutionMode.DisabledMode; clientConsumerInfo.totalTimeout = SniOpenTimeOut; clientConsumerInfo.isAzureSqlServerEndpoint = ADP.IsAzureSqlServerEndpoint(constring); clientConsumerInfo.ipAddressPreference = ipPreference; clientConsumerInfo.DNSCacheInfo.wszCachedFQDN = cachedDNSInfo?.FQDN; clientConsumerInfo.DNSCacheInfo.wszCachedTcpIPv4 = cachedDNSInfo?.AddrIPv4; clientConsumerInfo.DNSCacheInfo.wszCachedTcpIPv6 = cachedDNSInfo?.AddrIPv6; clientConsumerInfo.DNSCacheInfo.wszCachedTcpPort = cachedDNSInfo?.Port; if (spnBuffer != null) { fixed(byte *pin_spnBuffer = &spnBuffer[0]) { clientConsumerInfo.szSPN = pin_spnBuffer; clientConsumerInfo.cchSPN = (uint)spnBuffer.Length; return(SNIOpenSyncExWrapper(ref clientConsumerInfo, out pConn)); } } else { // else leave szSPN null (SQL Auth) return(SNIOpenSyncExWrapper(ref clientConsumerInfo, out pConn)); } } }
/// <summary> /// </summary> /// <param name="transport"></param> /// <param name="sessionState"></param> protected void DoRestoreConsumers(ITransport transport, SessionState sessionState) { // Restore the session's consumers but possibly in pull only (prefetch 0 state) till // recovery completes. ConnectionState connectionState = null; bool connectionInterruptionProcessingComplete = false; if (connectionStates.TryGetValue(sessionState.Info.SessionId.ParentId, out connectionState)) { connectionInterruptionProcessingComplete = connectionState.ConnectionInterruptProcessingComplete; } // Restore the session's consumers foreach (ConsumerState consumerState in sessionState.ConsumerStates) { ConsumerInfo infoToSend = consumerState.Info; if (!connectionInterruptionProcessingComplete && infoToSend.PrefetchSize > 0 && transport.WireFormat.Version > 5) { infoToSend = consumerState.Info.Clone() as ConsumerInfo; lock (((ICollection)connectionState.RecoveringPullConsumers).SyncRoot) { if (!connectionState.RecoveringPullConsumers.ContainsKey(infoToSend.ConsumerId)) { connectionState.RecoveringPullConsumers.Add(infoToSend.ConsumerId, consumerState.Info); } } infoToSend.PrefetchSize = 0; if (Tracer.IsDebugEnabled) { Tracer.Debug("restore consumer: " + infoToSend.ConsumerId + " in pull mode pending recovery, overriding prefetch: " + consumerState.Info.PrefetchSize); } } if (Tracer.IsDebugEnabled) { Tracer.Debug("restore consumer: " + infoToSend.ConsumerId); } transport.Oneway(infoToSend); } }
void Consume(object consumerInfo) { ConsumerInfo info = consumerInfo as ConsumerInfo; foreach (var item in msgs.GetConsumingEnumerable()) { info.token.ThrowIfCancellationRequested(); try { info.consumer.Process(item); } catch (Exception) { //log //throw; } } }
public void TestGetConsumerInfoFromSubscription() { Context.RunInJsServer(c => { CreateDefaultTestStream(c); IJetStream js = c.CreateJetStreamContext(); IJetStreamPushSyncSubscription psync = js.PushSubscribeSync(SUBJECT); ConsumerInfo ci = psync.GetConsumerInformation(); Assert.Equal(STREAM, ci.Stream); PullSubscribeOptions pso = PullSubscribeOptions.Builder().WithDurable(DURABLE).Build(); IJetStreamPullSubscription pull = js.PullSubscribe(SUBJECT, pso); ci = pull.GetConsumerInformation(); Assert.Equal(STREAM, ci.Stream); }); }
private void UpdateArraySummary(SystemSummary systemInfo, ConsumerInfo consumerInfo = null) { try { View summaryCard = FindViewById <View>(Resource.Id.production_card_bg_root); TextView productionHourlyText = FindViewById <TextView>(Resource.Id.production_per_hour); TextView productionTodayText = FindViewById <TextView>(Resource.Id.production_daily); TextView productionMonthlyText = FindViewById <TextView>(Resource.Id.production_per_month); TextView productionAnnualText = FindViewById <TextView>(Resource.Id.production_per_year); if (systemInfo != null) { productionHourlyText.Text = systemInfo.HourlyDCArrayOutput.ToString("0.00") + " kW"; productionTodayText.Text = systemInfo.TodayDCArrayOutput.ToString("0.00") + " kW"; productionMonthlyText.Text = systemInfo.MonthlyDCArrayOutput.ToString("0.00") + " kW"; productionAnnualText.Text = systemInfo.AnnualDCArrayOutput.ToString("0.00") + " kW"; if (consumerInfo != null) { if (consumerInfo.TotalUsage >= systemInfo.TodayDCArrayOutput) { summaryCard.SetBackgroundResource(Resource.Color.md_red_100); } else { summaryCard.SetBackgroundResource(Resource.Color.md_green_100); } } } else { productionHourlyText.Text = "..."; productionTodayText.Text = "..."; productionMonthlyText.Text = "..."; productionAnnualText.Text = "..."; } } catch (Exception e) { Log.Error(ToString(), e.ToString()); } }
public IMessageConsumer CreateDurableConsumer(ITopic destination, string name, string selector, bool noLocal) { if (destination == null) { throw new InvalidDestinationException("Cannot create a Consumer with a Null destination"); } ConsumerInfo command = CreateConsumerInfo(destination, selector); ConsumerId consumerId = command.ConsumerId; command.SubscriptionName = name; command.NoLocal = noLocal; command.PrefetchSize = this.connection.PrefetchPolicy.DurableTopicPrefetch; MessageConsumer consumer = null; // Registered with Connection before we register at the broker. connection.addDispatcher(consumerId, this); try { consumer = new MessageConsumer(this, command); consumer.ConsumerTransformer = this.ConsumerTransformer; consumers[consumerId] = consumer; if (this.Started) { consumer.Start(); } this.connection.SyncRequest(command); } catch (Exception) { if (consumer != null) { consumer.Close(); } throw; } return(consumer); }
public IMessageConsumer CreateConsumer(IDestination destination, string selector, bool noLocal) { if (destination == null) { throw new InvalidDestinationException("Cannot create a Consumer with a Null destination"); } ConsumerInfo command = CreateConsumerInfo(destination, selector); command.NoLocal = noLocal; ConsumerId consumerId = command.ConsumerId; MessageConsumer consumer = null; // Registered with Connection before we register at the broker. connection.addDispatcher(consumerId, this); try { consumer = new MessageConsumer(this, command); consumer.ConsumerTransformer = this.ConsumerTransformer; consumers[consumerId] = consumer; if (this.Started) { consumer.Start(); } // lets register the consumer first in case we start dispatching messages immediately this.Connection.SyncRequest(command); return(consumer); } catch (Exception) { if (consumer != null) { consumer.Close(); } throw; } }
public void RegisterConsumer(ITcpConnection connection, string consumerId, IList <string> subscriptionTopics, IList <MessageQueueEx> consumingMessageQueues) { var connectionId = connection.RemotingEndPoint.ToAddress(); _consumerInfoDict.AddOrUpdate(connectionId, key => { var newConsumerInfo = new ConsumerInfo { ConsumerId = consumerId, HeartbeatInfo = new ClientHeartbeatInfo(connection) { LastHeartbeatTime = DateTime.Now }, SubscriptionTopics = subscriptionTopics, ConsumingQueues = consumingMessageQueues }; _logger.InfoFormat("Consumer registered to group, groupName: {0}, consumerId: {1}, connectionId: {2}, subscriptionTopics: {3}, consumingQueues: {4}", _groupName, consumerId, key, string.Join("|", subscriptionTopics), string.Join("|", consumingMessageQueues)); return(newConsumerInfo); }, (key, existingConsumerInfo) => { existingConsumerInfo.HeartbeatInfo.LastHeartbeatTime = DateTime.Now; var oldSubscriptionList = existingConsumerInfo.SubscriptionTopics.ToList(); var newSubscriptionList = subscriptionTopics.ToList(); if (IsStringCollectionChanged(oldSubscriptionList, newSubscriptionList)) { existingConsumerInfo.SubscriptionTopics = newSubscriptionList; _logger.InfoFormat("Consumer subscriptionTopics changed. groupName: {0}, consumerId: {1}, connectionId: {2}, old: {3}, new: {4}", _groupName, consumerId, key, string.Join("|", oldSubscriptionList), string.Join("|", newSubscriptionList)); } var oldConsumingQueues = existingConsumerInfo.ConsumingQueues; var newConsumingQueues = consumingMessageQueues; if (IsMessageQueueChanged(oldConsumingQueues, newConsumingQueues)) { existingConsumerInfo.ConsumingQueues = newConsumingQueues; _logger.InfoFormat("Consumer consumingQueues changed. groupName: {0}, consumerId: {1}, connectionId: {2}, old: {3}, new: {4}", _groupName, consumerId, key, string.Join("|", oldConsumingQueues), string.Join("|", newConsumingQueues)); } return(existingConsumerInfo); }); }
public void Add <T, TH>(Func <string, string, Task> processEvent) where T : IntegrationEvent where TH : IIntegrationEventHandler <T> { var eventName = GetKey <T>(); string queueName = GetQueueName <T, TH>(); if (!HasConsumersForEvent(eventName)) { consumers.Add(eventName, new List <ConsumerInfo>()); } var consumersList = consumers[eventName]; if (!consumersList.Any(info => info.QueueName == queueName)) { var info = new ConsumerInfo(queueName, CreateConsumerChannel(queueName, processEvent)); consumersList.Add(info); } }
public override Response processAddConsumer(ConsumerInfo info) { if (info != null) { SessionId sessionId = info.ConsumerId.ParentId; if (sessionId != null) { ConnectionId connectionId = sessionId.ParentId; if (connectionId != null) { ConnectionState cs = connectionStates[connectionId]; if (cs != null) { cs.addConsumer(info); } } } } return(TRACKED_RESPONSE_MARKER); }
public void TestAddDeleteConsumer() { Context.RunInJsServer(c => { IJetStreamManagement jsm = c.CreateJetStreamManagementContext(); CreateMemoryStream(jsm, STREAM, Subject(0), Subject(1)); IList <ConsumerInfo> list = jsm.GetConsumers(STREAM); Assert.Empty(list); // Assert.Throws<ArgumentException>(() => ConsumerConfiguration cc = ConsumerConfiguration.Builder().Build(); Assert.Throws <ArgumentException>(() => jsm.AddOrUpdateConsumer(null, cc)); Assert.Throws <ArgumentNullException>(() => jsm.AddOrUpdateConsumer(STREAM, null)); Assert.Throws <ArgumentNullException>(() => jsm.AddOrUpdateConsumer(STREAM, cc)); ConsumerConfiguration cc0 = ConsumerConfiguration.Builder() .WithDurable(Durable(0)) .Build(); ConsumerInfo ci = jsm.AddOrUpdateConsumer(STREAM, cc0); Assert.Equal(Durable(0), ci.Name); Assert.Equal(Durable(0), ci.ConsumerConfiguration.Durable); Assert.Empty(ci.ConsumerConfiguration.DeliverSubject); ConsumerConfiguration cc1 = ConsumerConfiguration.Builder() .WithDurable(Durable(1)) .WithDeliverSubject(Deliver(1)) .Build(); ci = jsm.AddOrUpdateConsumer(STREAM, cc1); Assert.Equal(Durable(1), ci.Name); Assert.Equal(Durable(1), ci.ConsumerConfiguration.Durable); Assert.Equal(Deliver(1), ci.ConsumerConfiguration.DeliverSubject); IList <string> consumers = jsm.GetConsumerNames(STREAM); Assert.Equal(2, consumers.Count); Assert.True(jsm.DeleteConsumer(STREAM, cc1.Durable)); consumers = jsm.GetConsumerNames(STREAM); Assert.Single(consumers); Assert.Throws <NATSJetStreamException>(() => jsm.DeleteConsumer(STREAM, cc1.Durable)); }); }
private void CreateConsumer(string mqName, string mqServer, string projectKey, int index, EventHandler <BasicDeliverEventArgs> handler) { if (HttpContext.Application["TaskList"] == null) { HttpContext.Application["TaskList"] = new List <Contain>(); } Dictionary <string, string> args = new Dictionary <string, string>(); args["projectKey"] = projectKey; args["mqName"] = mqName; args["index"] = index.ToString(); args["type"] = "1"; ConsumerInfo info = new ConsumerInfo() { Handler = handler, HostName = mqServer, QueueName = mqName, ConsumerTag = mqName + "_" + (index + 1), Args = args, Notice = new Func <Dictionary <string, string>, string>(SendHeartData) }; ConsumerTask cTask = RabbitMQHelper.CreateConsumer(info); Contain c = new Contain { task = cTask.Task, tokenSource = cTask.TokenSource, taskKey = mqName, projectKey = projectKey }; List <Contain> tasklist = HttpContext.Application["TaskList"] as List <Contain>; tasklist.Add(c); Dictionary <string, List <HeartData> > heart = HttpContext.Application[projectKey] as Dictionary <string, List <HeartData> >; heart[mqName + "_" + (index + 1)] = new List <HeartData>(); }
protected virtual void WriteConsumerInfo(ConsumerInfo command, StompFrameStream ss) { ss.WriteCommand(command, "SUBSCRIBE"); ss.WriteHeader("destination", StompHelper.ToStomp(command.Destination)); ss.WriteHeader("id", StompHelper.ToStomp(command.ConsumerId)); ss.WriteHeader("durable-subscriber-name", command.SubscriptionName); ss.WriteHeader("selector", command.Selector); if (command.NoLocal) { ss.WriteHeader("no-local", command.NoLocal); } ss.WriteHeader("ack", "client"); // ActiveMQ extensions to STOMP ss.WriteHeader("activemq.dispatchAsync", command.DispatchAsync); if (command.Exclusive) { ss.WriteHeader("activemq.exclusive", command.Exclusive); } if (command.SubscriptionName != null) { ss.WriteHeader("activemq.subscriptionName", command.SubscriptionName); // For an older 4.0 broker we need to set this header so they get the // subscription as wel.. ss.WriteHeader("activemq.subcriptionName", command.SubscriptionName); } ss.WriteHeader("activemq.maximumPendingMessageLimit", command.MaximumPendingMessageLimit); ss.WriteHeader("activemq.prefetchSize", command.PrefetchSize); ss.WriteHeader("activemq.priority", command.Priority); if (command.Retroactive) { ss.WriteHeader("activemq.retroactive", command.Retroactive); } consumers[command.ConsumerId] = command.ConsumerId; ss.Flush(); }
protected virtual ConsumerInfo CreateConsumerInfo(IDestination destination, string selector) { ConsumerInfo answer = new ConsumerInfo(); ConsumerId id = new ConsumerId(); id.ConnectionId = info.SessionId.ConnectionId; id.SessionId = info.SessionId.Value; id.Value = Interlocked.Increment(ref consumerCounter); answer.ConsumerId = id; answer.Destination = Destination.Transform(destination); answer.Selector = selector; answer.Priority = this.Priority; answer.Exclusive = this.Exclusive; answer.DispatchAsync = this.DispatchAsync; answer.Retroactive = this.Retroactive; answer.MaximumPendingMessageLimit = this.connection.PrefetchPolicy.MaximumPendingMessageLimit; answer.AckMode = this.AcknowledgementMode; if (destination is ITopic || destination is ITemporaryTopic) { answer.PrefetchSize = this.connection.PrefetchPolicy.TopicPrefetch; } else if (destination is IQueue || destination is ITemporaryQueue) { answer.PrefetchSize = this.connection.PrefetchPolicy.QueuePrefetch; } // If the destination contained a URI query, then use it to set public properties // on the ConsumerInfo Destination amqDestination = destination as Destination; if (amqDestination != null && amqDestination.Options != null) { StringDictionary options = URISupport.GetProperties(amqDestination.Options, "consumer."); URISupport.SetProperties(answer, options); } return(answer); }
/** * Set the access token for the given user/gadget/service/token */ public abstract void setTokenInfo(ISecurityToken securityToken, ConsumerInfo consumerInfo, String serviceName, String tokenName, TokenInfo tokenInfo);
public override void setTokenInfo(ISecurityToken securityToken, ConsumerInfo consumerInfo, String serviceName, String tokenName, TokenInfo tokenInfo) { ++accessTokenAddCount; BasicOAuthStoreTokenIndex tokenKey = MakeBasicOAuthStoreTokenIndex(securityToken, serviceName, tokenName); tokens.Add(tokenKey, tokenInfo); }
public override void removeToken(ISecurityToken securityToken, ConsumerInfo consumerInfo, String serviceName, String tokenName) { ++accessTokenRemoveCount; BasicOAuthStoreTokenIndex tokenKey = MakeBasicOAuthStoreTokenIndex(securityToken, serviceName, tokenName); tokens.Remove(tokenKey); }
/// <summary> /// Create the ESB Request method for getting the Line Activation Portability Status using WPS endpoints. /// </summary> /// <param name="request">Contains Subscriber Telephone Number to Query</param> /// <param name="headerArgs">Contains User Info</param> /// <returns></returns> private static GetLineNumberPortabilityStatusRequest CreateLineTestPortabilityStatusRequest(ActivateServiceOrderRequestDto request, HeaderArgs headerArgs) { try { var _executionContext = new ExecutionContext(); if (request.ExecutionContext == null) { var consumerInfo = new ConsumerInfo(); consumerInfo.ApplicationID = ApplicationIDEnum.SIMPL; consumerInfo.EmployeeID = headerArgs.CrisId; consumerInfo.UserID = headerArgs.CorpId ?? String.Empty; var esbHeader = new ESBHeader(); esbHeader.ConsumerInfo = consumerInfo; _executionContext.ESBHeader = esbHeader; _executionContext.ESBHeader.ConsumerInfo.ApplicationID = ApplicationIDEnum.SIMPL; _executionContext.ESBHeader.ConsumerInfo.EmployeeID = headerArgs.CrisId; _executionContext.ESBHeader.ConsumerInfo.UserID = headerArgs.CorpId ?? String.Empty; } else { _executionContext.ESBHeader.ConsumerInfo.ApplicationID = ApplicationIDEnum.SIMPL; _executionContext.ESBHeader.ConsumerInfo.EmployeeID = request.ExecutionContext.EsbHeader.ConsumerInfo.EmployeeID; _executionContext.ESBHeader.ConsumerInfo.UserID = request.ExecutionContext.EsbHeader.ConsumerInfo.UserID ?? String.Empty; } var tn = new TelephoneNumber(); tn.Item = request.TN; var _requestCriteria = new GetNumberRegistrationStatusRequest(); _requestCriteria.TelephoneNumber = tn; var manage = new ManageTelephoneNumberRegistrationGetLineNumberPortabilityStatusRequest(); manage.ExecutionContext = _executionContext; manage.RequestCriteria = _requestCriteria; var _request = new GetLineNumberPortabilityStatusRequest(); _request.ManageTelephoneNumberRegistrationGetLineNumberPortabilityStatusRequest = manage; return _request; } catch (System.Exception ex) { var myException = new System.Exception("Error Creating ActivateServiceOrderRequest", ex); throw myException; } }
/// <summary> /// Create the ESB Request method for ActivateService Order using WPS endpoints. /// </summary> /// <param name="request">Contains Subscriber Telephone Number to Activate</param> /// <param name="headerArgs">Contains User Info</param> /// <returns></returns> private static UpdateLineNumberPortabilityRequest CreateWpsActivateServiceOrderRequest(ActivateServiceOrderRequestDto request, HeaderArgs headerArgs) { try { var _executionContext = new ExecutionContext(); if (request.ExecutionContext == null) { var consumerInfo = new ConsumerInfo(); consumerInfo.ApplicationID = ApplicationIDEnum.SIMPL; consumerInfo.EmployeeID = headerArgs.CrisId; consumerInfo.UserID = headerArgs.CorpId ?? String.Empty; var esbHeader = new ESBHeader(); esbHeader.ConsumerInfo = consumerInfo; _executionContext.ESBHeader = esbHeader; _executionContext.ESBHeader.ConsumerInfo.ApplicationID = ApplicationIDEnum.SIMPL; _executionContext.ESBHeader.ConsumerInfo.EmployeeID = headerArgs.CrisId; _executionContext.ESBHeader.ConsumerInfo.UserID = headerArgs.CorpId ?? String.Empty; } else { _executionContext.ESBHeader.ConsumerInfo.ApplicationID = ApplicationIDEnum.SIMPL; _executionContext.ESBHeader.ConsumerInfo.EmployeeID = request.ExecutionContext.EsbHeader.ConsumerInfo.EmployeeID; _executionContext.ESBHeader.ConsumerInfo.UserID = request.ExecutionContext.EsbHeader.ConsumerInfo.UserID ?? String.Empty; } var _requestCriteria = new NumberRegistrationRequest(); _requestCriteria.Action = NumberRegistrationActionEnum.Activate; _requestCriteria.RequestDateTimeSpecified = true; _requestCriteria.RequestDateTime = DateTime.Now; _requestCriteria.PortedTelephoneNumber = new TelephoneNumber(); _requestCriteria.PortedTelephoneNumber.Item = request.TN; _requestCriteria.PortAction = PortActionEnum.SOAOnlyPortIn; var _request = new UpdateLineNumberPortabilityRequest(); _request.ManageTelephoneNumberRegistrationUpdateLineNumberPortabilityRequest = new ManageTelephoneNumberRegistrationUpdateLineNumberPortabilityRequest(); _request.ManageTelephoneNumberRegistrationUpdateLineNumberPortabilityRequest.ExecutionContext = _executionContext; _request.ManageTelephoneNumberRegistrationUpdateLineNumberPortabilityRequest.RequestCriteria = _requestCriteria; return _request; } catch (System.Exception ex) { var myException = new System.Exception("Error Creating ActivateServiceOrderRequest", ex); throw myException; } }
/** * Remove the access token for the given user/gadget/service/token */ public abstract void removeToken(ISecurityToken securityToken, ConsumerInfo consumerInfo, String serviceName, String tokenName);
public static uint SNIOpenMarsSession (ConsumerInfo info, SNIHandle parent, ref IntPtr handle, bool sync) { throw new NotSupportedException (msg); }
private static void MarshalConsumerInfo(ConsumerInfo consumerInfo, ref Sni_Consumer_Info native_consumerInfo) { native_consumerInfo.DefaultUserDataLength = consumerInfo.defaultBufferSize; native_consumerInfo.fnReadComp = null != consumerInfo.readDelegate ? Marshal.GetFunctionPointerForDelegate(consumerInfo.readDelegate) : IntPtr.Zero; native_consumerInfo.fnWriteComp = null != consumerInfo.writeDelegate ? Marshal.GetFunctionPointerForDelegate(consumerInfo.writeDelegate) : IntPtr.Zero; native_consumerInfo.ConsumerKey = consumerInfo.key; }
public IConsumerDescription GetConsumer(string consumerKey) { // We don't keep a list of authorized consumers, everyone is welcome ConsumerInfo description = new ConsumerInfo(); description.Key = consumerKey; return description; }
public static uint SNIOpen (ConsumerInfo info, SafeHandle handle, out IntPtr result, bool b) { throw new NotSupportedException (msg); }
/** * Retrieve OAuth access token to use for the request. * @param securityToken token for user/gadget making request. * @param consumerInfo OAuth consumer that will be used for the request. * @param serviceName gadget's nickname for the service being accessed. * @param tokenName gadget's nickname for the token to use. * @return the token and secret, or null if none exist * @throws GadgetException if an error occurs during lookup */ public abstract TokenInfo getTokenInfo(ISecurityToken securityToken, ConsumerInfo consumerInfo, String serviceName, String tokenName);
internal static unsafe uint SNIOpenMarsSession(ConsumerInfo consumerInfo, SNIHandle parent, ref IntPtr pConn, bool fSync) { // initialize consumer info for MARS Sni_Consumer_Info native_consumerInfo = new Sni_Consumer_Info(); MarshalConsumerInfo(consumerInfo, ref native_consumerInfo); return SNIOpenWrapper(ref native_consumerInfo, "session:", parent, out pConn, fSync); }
public override TokenInfo getTokenInfo(ISecurityToken securityToken, ConsumerInfo consumerInfo, String serviceName, String tokenName) { ++accessTokenLookupCount; BasicOAuthStoreTokenIndex tokenKey = MakeBasicOAuthStoreTokenIndex(securityToken, serviceName, tokenName); return tokens.ContainsKey(tokenKey)?tokens[tokenKey]:null; }
internal static unsafe uint SNIOpenSyncEx(ConsumerInfo consumerInfo, string constring, ref IntPtr pConn, byte[] spnBuffer, byte[] instanceName, bool fOverrideCache, bool fSync, int timeout, bool fParallel) { fixed (byte* pin_instanceName = &instanceName[0]) { SNI_CLIENT_CONSUMER_INFO clientConsumerInfo = new SNI_CLIENT_CONSUMER_INFO(); // initialize client ConsumerInfo part first MarshalConsumerInfo(consumerInfo, ref clientConsumerInfo.ConsumerInfo); clientConsumerInfo.wszConnectionString = constring; clientConsumerInfo.networkLibrary = PrefixEnum.UNKNOWN_PREFIX; clientConsumerInfo.szInstanceName = pin_instanceName; clientConsumerInfo.cchInstanceName = (uint)instanceName.Length; clientConsumerInfo.fOverrideLastConnectCache = fOverrideCache; clientConsumerInfo.fSynchronousConnection = fSync; clientConsumerInfo.timeout = timeout; clientConsumerInfo.fParallel = fParallel; if (spnBuffer != null) { fixed (byte* pin_spnBuffer = &spnBuffer[0]) { clientConsumerInfo.szSPN = pin_spnBuffer; clientConsumerInfo.cchSPN = (uint)spnBuffer.Length; return SNIOpenSyncExWrapper(ref clientConsumerInfo, out pConn); } } else { // else leave szSPN null (SQL Auth) return SNIOpenSyncExWrapper(ref clientConsumerInfo, out pConn); } } }
public static uint SNIOpenSyncEx (ConsumerInfo info, string serverName, ref IntPtr handle, byte [] spnBuffer, byte [] instanceName, bool flushCache, bool sync, int timeout, bool parallel) { throw new NotSupportedException (msg); }