summaryrefslogtreecommitdiff
path: root/qpid/dotnet/Qpid.Client.Tests/failover/FailoverTest.cs
blob: 1f1e2f726c281902ffbb95d79e74dec5f73aa664 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 */
using System;
using System.Threading;
using log4net;
using NUnit.Framework;
using Apache.Qpid.Client.Qms;
using Apache.Qpid.Messaging;

namespace Apache.Qpid.Client.Tests.failover
{
    [TestFixture, Category("Failover")]
    public class FailoverTest : IConnectionListener
    {
        private static readonly ILog _logger = LogManager.GetLogger(typeof(FailoverTest));

        private IConnection _connection;
        private IChannel _channel;
        private IMessagePublisher _publisher;
        private int _count;

        private IMessageConsumer _consumerOfResponse;

        void DoFailoverTest(IConnectionInfo info)
        {
            DoFailoverTest(new AMQConnection(info));
        }

        void DoFailoverTest(IConnection connection)
        {
            AMQConnection amqConnection = (AMQConnection)connection;
            amqConnection.ConnectionListener = this;
            //Console.WriteLine("connection.url = " + amqConnection.ToURL());
            _connection = connection;
            _connection.ExceptionListener = new ExceptionListenerDelegate(OnConnectionException);
            _channel = _connection.CreateChannel(false, AcknowledgeMode.NoAcknowledge);

            string exchangeName = ExchangeNameDefaults.TOPIC;
            string routingKey = "topic1";

            string queueName = DeclareAndBindTemporaryQueue(exchangeName, routingKey);
            
            new MsgListener(_connection.CreateChannel(false, AcknowledgeMode.NoAcknowledge), queueName);

            IChannel channel = _channel;

            string tempQueueName = channel.GenerateUniqueName();
            channel.DeclareQueue(tempQueueName, false, true, true);
            _consumerOfResponse = channel.CreateConsumerBuilder(tempQueueName).Create();
            _consumerOfResponse.OnMessage = new MessageReceivedDelegate(OnMessage);

            _connection.Start();

            IMessage msg = _channel.CreateTextMessage("Init");
            // FIXME: Leaving ReplyToExchangeName as default (i.e. the default exchange)
            // FIXME: but the implementation might not like this as it defaults to null rather than "".
            msg.ReplyToRoutingKey = tempQueueName;
//            msg.ReplyTo = new ReplyToDestination("" /* i.e. the default exchange */, tempQueueName);
            _logger.Info(String.Format("sending msg.Text={0}", ((ITextMessage)msg).Text));

//            _publisher = _channel.CreatePublisher(exchangeName, exchangeClass, routingKey);
            _publisher = _channel.CreatePublisherBuilder()
                .WithRoutingKey(routingKey)
                .WithExchangeName(exchangeName)
                .Create();
            _publisher.Send(msg);
        }

        public string DeclareAndBindTemporaryQueue(string exchangeName, string routingKey)
        {
            string queueName = _channel.GenerateUniqueName();

            // Queue.Declare
            _channel.DeclareQueue(queueName, false, true, true);

            // Queue.Bind
            _channel.Bind(queueName, exchangeName, routingKey);
            return queueName;
        }

        private void OnConnectionException(Exception e)
        {
            _logger.Error("Connection exception occurred", e);
        }

        public void OnMessage(IMessage message)
        {
            try
            {
                _logger.Info("received message on temp queue msg.Text=" + ((ITextMessage)message).Text);
                Thread.Sleep(1000);
                _publisher.Send(_channel.CreateTextMessage("Message" + (++_count)));
            }
            catch (QpidException e)
            {
                error(e);
            }
        }

        private void error(Exception e)
        {
            _logger.Error("exception received", e);
            stop();
        }

        private void stop()
        {
            _logger.Info("Stopping...");
            try
            {
                _connection.Dispose();
            }
            catch (QpidException e)
            {
                _logger.Error("Failed to shutdown", e);
            }
        }

        public void BytesSent(long count)
        {
        }

        public void BytesReceived(long count)
        {
        }

        public bool PreFailover(bool redirect)
        {
            _logger.Info("preFailover(" + redirect + ") called");
            return true;
        }

        public bool PreResubscribe()
        {
            _logger.Info("preResubscribe() called");
            return true;
        }

        public void FailoverComplete()
        {
            _logger.Info("failoverComplete() called");
        }

        private class MsgListener
        {
            private IChannel _session;
            private IMessagePublisher _publisher;

            internal MsgListener(IChannel session, string queueName)
            {
                _session = session;
                _session.CreateConsumerBuilder(queueName).Create().OnMessage = 
                    new MessageReceivedDelegate(OnMessage);
            }

            public void OnMessage(IMessage message)
            {
                try
                {
                    _logger.Info("Received: msg.Text = " + ((ITextMessage) message).Text);
                    if(_publisher == null)
                    {
                        _publisher = init(message);
                    }
                    reply(message);
                }
                catch (QpidException e)
                {
//                   Error(e);
                    _logger.Error("yikes", e); // XXX
                }
            }

            private void reply(IMessage message)
            {
                string msg = ((ITextMessage) message).Text;
                _logger.Info("sending reply - " + msg);
                _publisher.Send(_session.CreateTextMessage(msg));
            }

            private IMessagePublisher init(IMessage message)
            {
                _logger.Info(string.Format("creating reply producer with dest = '{0}:{1}'", 
                                           message.ReplyToExchangeName, message.ReplyToRoutingKey));

                string exchangeName = message.ReplyToExchangeName;
                string routingKey = message.ReplyToRoutingKey;

                //return _channel.CreatePublisher(exchangeName, exchangeClass, routingKey);
                return _session.CreatePublisherBuilder()
                    .WithExchangeName(exchangeName)
                    .WithRoutingKey(routingKey)
                    .Create();
            }
        }

        [Test]
        public void TestFail()
        {
            Assert.Fail("Tests in this class do not pass, but hang forever, so commented out until can be fixed.");
        }

        /*[Test]
        public void TestWithBasicInfo()
        {
            Console.WriteLine("TestWithBasicInfo");
            try
            {
                QpidConnectionInfo connectionInfo = new QpidConnectionInfo();
                connectionInfo.AddBrokerInfo(new AmqBrokerInfo("amqp", "localhost", 5672, false));
                connectionInfo.AddBrokerInfo(new AmqBrokerInfo("amqp", "localhost", 5673, false));               
                DoFailoverTest(connectionInfo);
                while (true)
                {
                    Thread.Sleep(5000);
                }
            }
            catch (Exception e)
            {
                _logger.Error("Exception caught", e);
            }
        }*/

//        [Test]
//        public void TestWithUrl()
//        {
//            String clientId = "failover" + DateTime.Now.Ticks;
//            String defaultUrl = "amqp://guest:guest@" + clientId + "/test" +
//                                "?brokerlist='tcp://localhost:5672;tcp://localhost:5673'&failover='roundrobin'";
//
//            _logger.Info("url = [" + defaultUrl + "]");
//
//            //            _logger.Info("connection url = [" + new AMQConnectionURL(defaultUrl) + "]");
//
//            String broker = defaultUrl;
//            //new FailoverTest(broker);
//        }
    }
}