private static Action getAction(NetMessage message)
        {
            Action action = new Action();
            ActionType actionType = translate( message.Action.Action );
            action.Action_type = actionType;

            switch(actionType)
            {
                case ActionType.PUBLISH:
                    action.Publish = getPublishMessage(message);
                    break;
                case ActionType.POLL:
                    action.Poll = getPollMessage(message);
                    break;
                case ActionType.ACKNOWLEDGE:
                    action.Ack_message = getAcknowledgeMessage(message);
                    break;
                case ActionType.SUBSCRIBE:
                    action.Subscribe = getSubscribeMessage(message);
                    break;
                case ActionType.UNSUBSCRIBE:
                    action.Unsubscribe = getUnsubscribeMessage(message);
                    break;
                case ActionType.PING:
                    action.Ping = getPingMessage(message);
                    break;
                case ActionType.AUTH:
                    action.Auth = getAuthMessage(message);
                    break;
                default:
                    throw new Exception("Unexpected ActionType while marshalling message " + actionType.ToString() );
            }

            return action;
        }
        public static NetMessage translate(Atom message)
        {
            NetAction action = getAction(message);
            IDictionary<string, string> headers = getHeaders(message);
            NetMessage netMessage = new NetMessage(action, headers);

            return netMessage;
        }
        private static Acknowledge getAcknowledgeMessage(NetMessage message)
        {
            NetAcknowledge netAck = message.Action.AcknowledgeMessage;

            Acknowledge ack = new Acknowledge();
            ack.Action_id = netAck.ActionId;
            ack.Destination = netAck.Destination;
            ack.Message_id = netAck.MessageId;

            return ack;
        }
        public static Atom translate(NetMessage message)
        {
            Atom atom = new Atom();

            Action action = getAction(message);
            Header header = getHeaders(message);

            atom.Action = action;
            atom.Header = header;

            return atom;
        }
Esempio n. 5
0
        /// <summary>
        /// Publish a message (to a topic).
        /// </summary>
        /// <param name="message">A broker message</param>
        /// <param name="destination">A destination (e.g. "/topic/foo")</param>
        /// <param name="acceptRequest">An AcceptRequest instance.</param>
        public void Publish(NetBrokerMessage message, string destination, AcceptRequest acceptRequest)
        {
            if (IsClosed())
                return;

            NetPublish publish = new NetPublish(destination, NetAction.DestinationType.TOPIC, message);

            NetAction action = new NetAction(NetAction.ActionType.PUBLISH);
            action.PublishMessage = publish;

            NetMessage netMessage = new NetMessage(action, message.Headers);

            protocolHandler.HandleOutgoingMessage(netMessage, acceptRequest);
        }
Esempio n. 6
0
        /// <summary>
        /// Poll an message from a queue.
        /// </summary>
        /// <param name="queueName">Queue name (e.g. "/queue/foo").</param>
        /// <param name="timeout">Time, in miliseconds, before the agent stops waiting for a message, if the timeout is bigger than 0. If timeout is reached a TimeoutException is thrown. If the value is zero, than the agent will wait forever. A negative value means that the client doesn't want to wait if there are no messages is local agent's queue.</param>
        /// <param name="reserveTime">Message reserve time, in milliseconds. Polled messages are reserved, by default, for 15 minutes. If clients prefer a different reserve time, bigger or small, they can specify it.</param>
        /// <param name="acceptRequest">An AcceptRequest instance.</param>
        /// <returns>A NetNotification instance. In case of connection fail or if there are no messages in local agent's queue when timeout is negative null is returned.</returns>
        public NetNotification Poll(String queueName, long timeout, long reserveTime,AcceptRequest acceptRequest)
        {
            if (IsClosed())
                return null;

            NetPoll poll = new NetPoll(queueName, timeout);
            NetAction action = new NetAction(NetAction.ActionType.POLL);
            action.PollMessage = poll;
            NetMessage netMessage = new NetMessage(action);

            if (reserveTime != -1)
            {
                netMessage.Headers.Add("RESERVE_TIME", reserveTime.ToString());
            }

            protocolHandler.HandleOutgoingMessage(netMessage, acceptRequest);
            NetNotification notification = protocolHandler.GetSyncMessage(queueName, netMessage);

            if (notification == BrokerProtocolHandler.UnblockNotification)
                throw new TimeoutException();

            if (notification == BrokerProtocolHandler.NoMessageNotification)
                return null;

            return notification;
        }
 private static Header getHeaders(NetMessage message)
 {
     Header headers = new Header();
     headers.Parameters = new Dictionary<string, string>(message.Headers);
     return headers;
 }
 private void HandlePongMessage(NetMessage message)
 {
     PongHandler handler = OnPong;
     if (handler != null)
         OnPong(message.Action.PongMessage);
 }
        private void HandleFault(NetMessage message)
        {
            string msgDest = message.Action.FaultMessage.Detail;

            if( message.Action.FaultMessage.Code.Equals( NetFault.PollTimeoutErrorMessage.Action.FaultMessage.Code ) ||
                message.Action.FaultMessage.Code.Equals(NetFault.NoMessageInQueueErrorMessage.Action.FaultMessage.Code) )
            {
                lock (this.syncSubscriptions)
                {
                    if (syncSubscriptions.ContainsKey(msgDest))
                    {
                        PollRequest request = syncSubscriptions[msgDest];
                        if( message.Action.FaultMessage.Code.Equals( NetFault.PollTimeoutErrorMessage.Action.FaultMessage.Code ) )
                        {
                            request.Handover.Offer(UnblockNotification);
                        }
                        else
                        {
                            request.Handover.Offer(NoMessageNotification);
                        }
                    }
                    return;
                }
            }

            message.Action.FaultMessage.Headers = message.Headers;

            if (!PendingAcceptRequestsManager.MessageFailed(message.Action.FaultMessage))
            {
                FaultHandler handler = OnFault;
                if (handler != null)
                    OnFault(message.Action.FaultMessage);
            }
        }
        //syncSubscriptions
        internal NetNotification GetSyncMessage(string queueName, NetMessage message)
        {
            NetNotification receivedMessage = null;
            HandoverSyncObject<NetNotification> synObj = null;
            lock (syncSubscriptions)
            {
                if (syncSubscriptions.ContainsKey(queueName))
                    throw new ArgumentException("Queue " + queueName + " has already a poll runnig.");
                PollRequest pr = new PollRequest();
                pr.Subscription = message;
                pr.Handover = synObj = new HandoverSyncObject<NetNotification>();
                syncSubscriptions.Add(queueName, pr);
            }

            receivedMessage = synObj.Get();
            lock (syncSubscriptions)
            {
                syncSubscriptions.Remove(queueName);
            }

            return receivedMessage;
        }
 public void HandleIncommingMessage(NetMessage message)
 {
     try{
         switch( message.Action.Action )
         {
         case NetAction.ActionType.ACCEPTED:
             PendingAcceptRequestsManager.MessageReceived(message.Action.AcceptedMessage.ActionId);
             break;
         case NetAction.ActionType.FAULT:
             HandleFault(message);
             break;
         case NetAction.ActionType.NOTIFICATION:
             HandleNotification(message);
             break;
         case NetAction.ActionType.PONG:
             HandlePongMessage(message);
             break;
         default:
             DealWithException( new Exception(String.Format("Unexpected incoming message type: {0}", message.Action.Action)));
             break;
         }
     } catch(Exception ex) {
         DealWithException( new Exception("Error handling incomming message.", ex));
     }
 }
 public static void SendMessageOverUdp(NetMessage message, HostInfo hostInfo, IMessageSerializer messageSerializer)
 {
     byte[] encodedData = messageSerializer.Marshall(message);
     UdpNetworkHandler.SendMessage(encodedData, hostInfo, messageSerializer);
 }
Esempio n. 13
0
        /// <summary>
        /// Subscribe to a destination.
        /// </summary>
        /// <param name="subscription">A Subscription instance.</param>
        /// <param name="acceptRequest">An AcceptRequest instance.</param>
        public void Subscribe(Subscription subscription, AcceptRequest acceptRequest)
        {
            if (IsClosed())
                return;

            subscription.BrokerClient = this;

            NetSubscribe netSubscribe = new NetSubscribe(subscription.DestinationPattern, subscription.DestinationType);
            NetAction action = new NetAction(NetAction.ActionType.SUBSCRIBE);
            action.SubscribeMessage = netSubscribe;
            NetMessage netMessage = new NetMessage(action, subscription.Headers);

            protocolHandler.HandleOutgoingMessage(netMessage, acceptRequest);

            protocolHandler.AddSubscription(subscription);
        }
        private static Unsubscribe getUnsubscribeMessage(NetMessage message)
        {
            NetUnsubscribe netUnsub = message.Action.UnsbuscribeMessage;

            Unsubscribe unsubscribe = new Unsubscribe();
            unsubscribe.Action_id = netUnsub.ActionId;
            unsubscribe.Destination = netUnsub.Destination;
            unsubscribe.Destination_type = translate ( netUnsub.DestinationType );

            return unsubscribe;
        }
        private static Subscribe getSubscribeMessage(NetMessage message)
        {
            NetSubscribe netSubs = message.Action.SubscribeMessage;

            Subscribe subs = new Subscribe();
            subs.Action_id = netSubs.ActionId;
            subs.Destination = netSubs.Destination;
            subs.Destination_type = translate(netSubs.DestinationType);

            return subs;
        }
        private static Publish getPublishMessage(NetMessage message)
        {
            NetPublish netPublish = message.Action.PublishMessage;

            Publish publish = new Publish();
            publish.Action_id = netPublish.ActionId;
            publish.Destination =  netPublish.Destination;
            publish.Destination_type = translate( netPublish.DestinationType );
            publish.Message = getBrokerMessage( netPublish.Message );

            return publish;
        }
        private static Poll getPollMessage(NetMessage message)
        {
            NetPoll netPoll = message.Action.PollMessage;

            Poll poll = new Poll();
            poll.Action_id = netPoll.ActionId;
            poll.Destination = netPoll.Destination;
            poll.Timeout = netPoll.Timeout;

            return poll;
        }
        private static Ping getPingMessage(NetMessage message)
        {
            NetPing netPing = message.Action.PingMessage;

            Ping ping = new Ping();
            ping.Action_id = netPing.ActionId;

            return ping;
        }
Esempio n. 19
0
        /// <summary>
        /// Cancel a previous subscription.
        /// </summary>
        /// <param name="subscription">A Subscription instance.</param>
        /// <param name="acceptRequest">An AcceptRequest instance.</param>
        public void Unsubscribe(Subscription subscription, AcceptRequest acceptRequest)
        {
            if (IsClosed())
                return;

            NetUnsubscribe netUnsubscribe = new NetUnsubscribe(subscription.DestinationPattern, subscription.DestinationType);
            NetAction action = new NetAction(NetAction.ActionType.UNSUBSCRIBE);
            action.UnsbuscribeMessage = netUnsubscribe;
            NetMessage netMessage = new NetMessage(action, subscription.Headers);

            protocolHandler.HandleOutgoingMessage(netMessage, acceptRequest);

            protocolHandler.RemoveSubscription(subscription);
        }
Esempio n. 20
0
 static NetFault()
 {
     InvalidMessageSizeErrorMessage = buildNetFaultMessage("1101", "Invalid message size");
     UnknownEncodingProtocolMessage = buildNetFaultMessage("1102", "Unknown encoding protocol");
     UnknownEncodingVersionMessage = buildNetFaultMessage("1103", "Unknown encoding version");
     InvalidMessageFormatErrorMessage = buildNetFaultMessage("1201", "Invalid message format");
     UnexpectedMessageTypeErrorMessage = buildNetFaultMessage("1202", "Unexpected message type");
     InvalidDestinationNameErrorMessage = buildNetFaultMessage("2001", "Invalid destination name");
     InvalidMessageDestinationTypeErrorMessage = buildNetFaultMessage("2002", "Invalid destination type");
     MaximumNrQueuesReachedMessage = buildNetFaultMessage("2003", "Maximum number of queues reached");
     MaximumDistinctSubscriptionsReachedMessage = buildNetFaultMessage("2004", "Maximum distinct subscriptions reached");
     PollTimeoutErrorMessage = buildNetFaultMessage("2005", "Message poll timeout");
     NoMessageInQueueErrorMessage = buildNetFaultMessage("2006", "No message in local agent queue.");
     AuthenticationFailedErrorMessage = buildNetFaultMessage("3101", "Authentication failed");
     UnknownAuthenticationTypeMessage = buildNetFaultMessage("3102", "Unknown authentication type");
     InvalidAuthenticationChannelType = buildNetFaultMessage("3103", "Invalid authentication channel type");
     AccessDeniedErrorMessage = buildNetFaultMessage("3201", "Access denied");
 }
        public bool Authenticate(ICredentialsProvider provider)
        {
            log.Info("Authenticating");
            if (provider == null)
            {
                throw new ArgumentNullException("AuthenticationInfo can not be null in order to authenticate.");
            }
            AuthenticationInfo authInfoToUse = null;
            try
            {
                authInfoToUse = provider.GetCredentials();
                if (authInfoToUse == null)
                    throw new InvalidCredentialsException("Credential provider returned null");
            }
            catch (InvalidCredentialsException ice)
            {
                log.Error("Failed to obtain credentials.", ice);
                return false;
            }

            // save important information
            lock (this)
            {
                this.provider = provider;
                this.clientAuthInfo = authInfoToUse;
                this.usingAuth = true;
            }

            // build NetMessage

            string actionId = System.Guid.NewGuid().ToString();

            NetAuthentication netAuth = new NetAuthentication(authInfoToUse.Token, authInfoToUse.UserAuthenticationType);
            if ((authInfoToUse.Roles != null) && (authInfoToUse.Roles.Count != 0))
                netAuth.Roles = authInfoToUse.Roles;
            if (authInfoToUse.UserId != null)
            {
                netAuth.UserId = authInfoToUse.UserId;
            }
            netAuth.ActionId = actionId;

            NetAction netAction = new NetAction(NetAction.ActionType.AUTH);
            netAction.AuthenticationMessage = netAuth;
            NetMessage msg = new NetMessage(netAction);

            // build waitable object
            WaitMessageAccepted waitMsgAccepted = new WaitMessageAccepted();
            AcceptRequest acceptRequest = new AcceptRequest(actionId, waitMsgAccepted, 7000);

            //send message
            HandleOutgoingMessage(msg, acceptRequest);

            // wait for response
            lock (waitMsgAccepted.SyncObject)
            {
                Monitor.Wait(waitMsgAccepted.SyncObject);
            }
            if (waitMsgAccepted.WaitResult != WaitMessageAccepted.Result.Accepted)
            {
                log.Error("Authenticatation failed. Reason: " + waitMsgAccepted.WaitResult);
                return false;
            }

            log.Info("Authenticated");

            return true;
        }
Esempio n. 22
0
 public static NetMessage buildNetFaultMessage(string code, string message)
 {
     NetFault fault = new NetFault(code, message);
     NetAction action = new NetAction(NetAction.ActionType.FAULT);
     action.FaultMessage = fault;
     NetMessage msg = new NetMessage(action);
     return msg;
 }
        public bool HandleOutgoingMessage(NetMessage message, AcceptRequest acceptRequest)
        {
            if( acceptRequest != null)
            {
                PendingAcceptRequestsManager.AddAcceptRequest(acceptRequest);
            }

            // transform and Marshall message
            byte[] encodedData = EncodeMessage(message);

            return SendMessage(encodedData);
        }
Esempio n. 24
0
        public static NetMessage getMessageFaultWithDetail(NetMessage message, string detail)
        {
            NetFault fault = message.Action.FaultMessage;
            NetFault newFault = new NetFault(fault.Code, fault.Message);
            newFault.ActionId = fault.ActionId;
            newFault.Detail = detail;

            NetAction action = new NetAction(NetAction.ActionType.FAULT);
            action.FaultMessage = newFault;

            return new NetMessage(action, message.Headers);
        }
 private byte[] EncodeMessage(NetMessage message)
 {
     return messageSerializer.Marshall(message);
 }
Esempio n. 26
0
        /// <summary>
        /// Publish a message over UDP.
        /// </summary>
        /// <param name="message">Message content.</param>
        /// <param name="destination">Message destination.</param>
        /// <param name="hostInfo">Agent information.</param>
        /// <param name="messageSerializer">Serialization type.</param>
        public static void PublishMessageOverUdp(NetBrokerMessage message, string destination, HostInfo hostInfo, IMessageSerializer messageSerializer)
        {
            NetPublish publish = new NetPublish(destination, NetAction.DestinationType.TOPIC, message);

            NetAction action = new NetAction(NetAction.ActionType.PUBLISH);
            action.PublishMessage = publish;

            NetMessage netMessage = new NetMessage(action, message.Headers);

            BrokerProtocolHandler.SendMessageOverUdp(netMessage, hostInfo, messageSerializer);
        }
        private void HandleNotification(NetMessage message)
        {
            string subscription = message.Action.NotificationMessage.Subscription;

            NetAction.DestinationType destType = message.Action.NotificationMessage.DestinationType;

            if (destType != NetAction.DestinationType.TOPIC)
            {
                lock (this.syncSubscriptions)
                {
                    string subs = message.Action.NotificationMessage.Subscription;
                    if (syncSubscriptions.ContainsKey(subscription))
                    {
                        PollRequest request = syncSubscriptions[subs];
                        request.Handover.Offer(message.Action.NotificationMessage);
                        return;
                    }
                }
            }

            lock (subscriptions)
            {
                IDictionary<string, Subscription> destSubscriptions = subscriptions[destType == NetAction.DestinationType.TOPIC ? NetAction.DestinationType.TOPIC : NetAction.DestinationType.QUEUE];

                if (destSubscriptions.ContainsKey(subscription))
                {
                    destSubscriptions[subscription].FireOnMessage(message.Action.NotificationMessage);
                }
                else
                {
                    DealWithException(new UnexpectedMessageException("No registered subscribers for received message.", message));
                }
            }
        }
Esempio n. 28
0
        /// <summary>
        /// Acknowledge a queue message.
        /// </summary>
        /// <param name="quequeName">Queue name (e.g. "/queue/foo" or "myQueue@/topic/foo").</param>
        /// <param name="messageId">The received message identifier.</param>
        /// <param name="acceptRequest">An AcceptRequest instance.</param>
        public void Acknowledge(string quequeName, string messageId, AcceptRequest acceptRequest)
        {
            if (IsClosed())
                return;
            NetAcknowledge netAck = new NetAcknowledge(quequeName, messageId);
            NetAction action = new NetAction(NetAction.ActionType.ACKNOWLEDGE);
            action.AcknowledgeMessage = netAck;
            NetMessage netMessage = new NetMessage(action);

            protocolHandler.HandleOutgoingMessage(netMessage, acceptRequest);
        }
Esempio n. 29
0
        /// <summary>
        /// Get a NetMessage containing a NetSubscribe object that represents this subscription request. This is meant to be used by the messaging framework.
        /// </summary>
        /// <returns>A NetMessage instance.</returns>
        public NetMessage ToNetMessage()
        {
            NetSubscribe netSubscribe = new NetSubscribe(this.destinationPattern, this.destinationType);
            NetAction netAction = new NetAction(NetAction.ActionType.SUBSCRIBE);
            netAction.SubscribeMessage = netSubscribe;
            NetMessage netMessage = new NetMessage(netAction, this.Headers);

            return netMessage;
        }
Esempio n. 30
0
        /// <summary>
        /// Send a Ping message to determine agent liveness.
        /// </summary>
        /// <returns>A Pong message or null if conection failed.</returns>
        public NetPong Ping()
        {
            if (IsClosed())
                return null;

            NetPong localNetPong = null;

            string actionId = Guid.NewGuid().ToString();
            NetPing ping = new NetPing(actionId);
            NetAction action = new NetAction(NetAction.ActionType.PING);
            action.PingMessage = ping;
            NetMessage netMessage = new NetMessage(action);

            ManualResetEvent mrEvent = new ManualResetEvent(false);

            PongHandler handler = delegate(NetPong pong)
            {
                if (pong.ActionId.Equals(actionId))
                {
                    localNetPong = pong;
                    mrEvent.Set();
                }
            };
            protocolHandler.OnPong += handler;

            protocolHandler.HandleOutgoingMessage(netMessage, null);

            mrEvent.WaitOne(2 * 1000, false);
            protocolHandler.OnPong -= handler;

            return localNetPong;
        }