summaryrefslogtreecommitdiff
path: root/dotnet/Qpid.Client/Client/Message/AbstractQmsMessage.cs
blob: 4c4adb8063e5bcd0938e60595a30454e5b270e09 (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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
/*
 *
 * 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.Collections;
using System.Text;
using log4net;
using Qpid.Framing;
using Qpid.Messaging;
using Qpid.Buffer;

namespace Qpid.Client.Message
{
    public abstract class AbstractQmsMessage : AMQMessage, IMessage
    {
        private static readonly ILog _log = LogManager.GetLogger(typeof(AbstractQmsMessage));

//        protected long _messageNbr;

        protected bool _redelivered;

        protected ByteBuffer _data;

        //protected AbstractQmsMessage() : base(new BasicContentHeaderProperties())
        //{           
        //}

        //protected AbstractQmsMessage(ulong messageNbr, BasicContentHeaderProperties contentHeader)
        //    : this(contentHeader)
        //{            
        //    _messageNbr = messageNbr;
        //}

        //protected AbstractQmsMessage(BasicContentHeaderProperties contentHeader) 
        //    : base(contentHeader)
        //{            
        //}


#region new_java_ctrs

        protected AbstractQmsMessage(ByteBuffer data)
            : base(new BasicContentHeaderProperties())
        {
            _data = data;
            if (_data != null)
            {
                _data.Acquire();
            }
        }

        protected AbstractQmsMessage(long deliveryTag, BasicContentHeaderProperties contentHeader, ByteBuffer data)
            : this(contentHeader, deliveryTag)
        {
            _data = data;
            if (_data != null)
            {
                _data.Acquire();
            }
        }

        protected AbstractQmsMessage(BasicContentHeaderProperties contentHeader, long deliveryTag) : base(contentHeader, deliveryTag)
        {
        }

#endregion

        public string MessageId
        {
            get
            {
                if (ContentHeaderProperties.MessageId == null)
                {
                    ContentHeaderProperties.MessageId = "ID:" + DeliveryTag;
                }
                return ContentHeaderProperties.MessageId;
            }
            set
            {
                ContentHeaderProperties.MessageId = value;
            }


        }        

        public long Timestamp
        {
            get
            {
                // TODO: look at ulong/long choice
                return (long) ContentHeaderProperties.Timestamp;
            }
            set
            {
                ContentHeaderProperties.Timestamp = (ulong) value;
            }
        }        

        public byte[] CorrelationIdAsBytes
        {
            get
            {            
                return Encoding.Default.GetBytes(ContentHeaderProperties.CorrelationId);
            }
            set
            {
                ContentHeaderProperties.CorrelationId = Encoding.Default.GetString(value);
            }
        }

        public string CorrelationId
        {
            get
            {
                return ContentHeaderProperties.CorrelationId;
            }
            set
            {
                ContentHeaderProperties.ContentType = value;
            }
        }
        
        struct Dest
        {
            public string ExchangeName;
            public string RoutingKey;

            public Dest(string exchangeName, string routingKey)
            {
                ExchangeName = exchangeName;
                RoutingKey = routingKey;
            }
        }

        public string ReplyToExchangeName
        {
            get
            {
                Dest dest = ReadReplyToHeader();
                return dest.ExchangeName;
            }
            set
            {
                Dest dest = ReadReplyToHeader();
                dest.ExchangeName = value;
                WriteReplyToHeader(dest);
            }
        }

        public string ReplyToRoutingKey
        {
            get
            {
                Dest dest = ReadReplyToHeader();
                return dest.RoutingKey;
            }
            set
            {
                Dest dest = ReadReplyToHeader();
                dest.RoutingKey = value;
                WriteReplyToHeader(dest);
            }
        }

        private Dest ReadReplyToHeader()
        {
            string replyToEncoding = ContentHeaderProperties.ReplyTo;
            if (replyToEncoding == null)
            {
                return new Dest();
            }
            else
            {
                string routingKey;
                string exchangeName = GetExchangeName(replyToEncoding, out routingKey);
                return new Dest(exchangeName, routingKey);                
            }            
        }
        
        private void WriteReplyToHeader(Dest dest)
        {
            string encodedDestination = string.Format("{0}:{1}", dest.ExchangeName, dest.RoutingKey);
            ContentHeaderProperties.ReplyTo = encodedDestination;            
        }

        private static string GetExchangeName(string replyToEncoding, out string routingKey)
        {
            string[] split = replyToEncoding.Split(new char[':']);
            if (_log.IsDebugEnabled)
            {
                _log.Debug(string.Format("replyToEncoding = '{0}'", replyToEncoding));
                _log.Debug(string.Format("split = {0}", split));
                _log.Debug(string.Format("split.Length = {0}", split.Length));                            
            }
            if (split.Length == 1)
            {
                // Using an alternative split implementation here since it appears that string.Split
                // is broken in .NET. It doesn't split when the first character is the delimiter.
                // Here we check for the first character being the delimiter. This handles the case
                // where ExchangeName is empty (i.e. sends will be to the default exchange).
                if (replyToEncoding[0] == ':')
                {
                    split = new string[2];
                    split[0] = null;
                    split[1] = replyToEncoding.Substring(1);
                    if (_log.IsDebugEnabled)
                    {
                        _log.Debug("Alternative split method...");
                        _log.Debug(string.Format("split = {0}", split));
                        _log.Debug(string.Format("split.Length = {0}", split.Length));                                    
                    }
                }
            }
            if (split.Length != 2)
            {
                throw new QpidException("Illegal value in ReplyTo property: " + replyToEncoding);
            }

            string exchangeName = split[0];
            routingKey = split[1];
            return exchangeName;
        }

        public DeliveryMode DeliveryMode
        {
            get
            {
                byte b = ContentHeaderProperties.DeliveryMode;
                switch (b)
                {
                    case 1:
                        return DeliveryMode.NonPersistent;
                    case 2:
                        return DeliveryMode.Persistent;
                    default:
                        throw new QpidException("Illegal value for delivery mode in content header properties");
                }                
            }
            set
            {
                ContentHeaderProperties.DeliveryMode = (byte)(value==DeliveryMode.NonPersistent?1:2);
            }
        }        

        public bool Redelivered
        {
            get
            {
                return _redelivered;
            }
            set
            {
                _redelivered = value;
            }
        }        

        public string Type
        {
            get
            {
                return MimeType;
            }            
            set
            {
                //MimeType = value;
            }
        }
        
        public long Expiration
        {
            get
            {
                return ContentHeaderProperties.Expiration;
            }
            set
            {
                ContentHeaderProperties.Expiration = (uint) value;
            }
        }

        public int Priority
        {
            get
            {
                return ContentHeaderProperties.Priority;
            }
            set
            {
                ContentHeaderProperties.Priority = (byte) value;
            }
        }

        // FIXME: implement
        public string ContentType
        {
            get { throw new NotImplementedException(); }
            set { throw new NotImplementedException(); }
        }

        // FIXME: implement
        public string ContentEncoding
        {
            get { throw new NotImplementedException(); }
            set { throw new NotImplementedException(); }
        }

        public void Acknowledge()
        {
            // the JMS 1.1 spec says in section 3.6 that calls to acknowledge are ignored when client acknowledge
            // is not specified. In our case, we only set the session field where client acknowledge mode is specified.
            if (_channel != null)
            {
                // we set multiple to true here since acknowledgement implies acknowledge of all previous messages
                // received on the session
                _channel.AcknowledgeMessage((ulong)DeliveryTag, true);
            }

        }

        public IHeaders Headers
        {
            get { return new QpidHeaders(this); }
        }

        public abstract void ClearBody();

        /// <summary>
        /// Get a String representation of the body of the message. Used in the
        /// toString() method which outputs this before message properties.
        /// </summary>
        /// <exception cref="QpidException"></exception>
        public abstract string ToBodyString();

        /// <summary>
        /// Return the raw byte array that is used to populate the frame when sending
        /// the message.
        /// </summary>
        /// <value>a byte array of message data</value>                
        public ByteBuffer Data
        {
            get
            {
                // make sure we rewind the data just in case any method has moved the
                // position beyond the start
                if (_data != null)
                {
                    _data.Rewind();
                }
                return _data;
            }

            set
            {
                _data = value;
            }
        }

        public abstract string MimeType
        {
            get;           
        }

        public override string ToString()
        {
            try
            {
                StringBuilder buf = new StringBuilder("Body:\n");
                buf.Append(ToBodyString());
                buf.Append("\nQmsTimestamp: ").Append(Timestamp);
                buf.Append("\nQmsExpiration: ").Append(Expiration);
                buf.Append("\nQmsPriority: ").Append(Priority);
                buf.Append("\nQmsDeliveryMode: ").Append(DeliveryMode);
                buf.Append("\nReplyToExchangeName: ").Append(ReplyToExchangeName);
                buf.Append("\nReplyToRoutingKey: ").Append(ReplyToRoutingKey);
                buf.Append("\nAMQ message number: ").Append(DeliveryTag);
                buf.Append("\nProperties:");
                if (ContentHeaderProperties.Headers == null)
                {
                    buf.Append("<NONE>");
                }
                else
                {
                    buf.Append(Headers.ToString());
                }
                return buf.ToString();
            }
            catch (Exception e)
            {
                return e.ToString();
            }
        }

        public IFieldTable UnderlyingMessagePropertiesMap
        {
            get
            {
                return ContentHeaderProperties.Headers;
            }
            set
            {
                ContentHeaderProperties.Headers = (FieldTable)value;
            }
        }
        
        public FieldTable PopulateHeadersFromMessageProperties()
        {
            if (ContentHeaderProperties.Headers == null)
            {
                return null;
            }
            else
            {
                //
                // We need to convert every property into a String representation
                // Note that type information is preserved in the property name
                //
                FieldTable table = new FieldTable();
                foreach (DictionaryEntry entry in  ContentHeaderProperties.Headers)
                {                    
                    string propertyName = (string) entry.Key;
                    if (propertyName == null)
                    {
                        continue;
                    }
                    else
                    {
                        table[propertyName] = entry.Value.ToString();
                    }
                }
                return table;
            }
        }

        /// <summary>
        /// Get the AMQ message number assigned to this message
        /// </summary>
        /// <returns>the message number</returns>
        //public ulong MessageNbr
        //{
        //    get
        //    {
        //        return _messageNbr;
        //    }
        //    set
        //    {
        //        _messageNbr = value;
        //    }
        //}        

        public BasicContentHeaderProperties ContentHeaderProperties
        {
            get
            {
                return (BasicContentHeaderProperties) _contentHeaderProperties;
            }
        }
    }

    internal class QpidHeaders : IHeaders
    {
        public const char BOOLEAN_PROPERTY_PREFIX = 'B';
        public const char BYTE_PROPERTY_PREFIX = 'b';
        public const char SHORT_PROPERTY_PREFIX = 's';
        public const char INT_PROPERTY_PREFIX = 'i';
        public const char LONG_PROPERTY_PREFIX = 'l';
        public const char FLOAT_PROPERTY_PREFIX = 'f';
        public const char DOUBLE_PROPERTY_PREFIX = 'd';
        public const char STRING_PROPERTY_PREFIX = 'S';

        AbstractQmsMessage _message;
        
        public QpidHeaders(AbstractQmsMessage message)
        {
            _message = message;
        }

        public bool Contains(string name)
        {
            CheckPropertyName(name);
            if (_message.ContentHeaderProperties.Headers == null)
            {
                return false;
            }
            else
            {
                // TODO: fix this
                return _message.ContentHeaderProperties.Headers.Contains(STRING_PROPERTY_PREFIX + name);
            }
        }

        public void Clear()
        {
            if (_message.ContentHeaderProperties.Headers != null)
            {
                _message.ContentHeaderProperties.Headers.Clear();
            }
        }

        public string this[string name]
        {
            get 
            { 
                return GetString(name);
            }
            set
            {
                SetString(name, value);
            }
        }

        public bool GetBoolean(string name)
        {
            CheckPropertyName(name);
            if (_message.ContentHeaderProperties.Headers == null)
            {
                return false;
            }
            else
            {
                object b = _message.ContentHeaderProperties.Headers[BOOLEAN_PROPERTY_PREFIX + name];

                if (b == null)
                {
                    return false;
                }
                else
                {
                    return (bool)b;
                }
            }
        }

        public void SetBoolean(string name, bool b)
        {
            CheckPropertyName(name);
            _message.ContentHeaderProperties.Headers[BOOLEAN_PROPERTY_PREFIX + name] = b;
        }

        public byte GetByte(string propertyName)
        {
            CheckPropertyName(propertyName);
            if (_message.ContentHeaderProperties.Headers == null)
            {
                return 0;
            }
            else
            {
                object b = _message.ContentHeaderProperties.Headers[BYTE_PROPERTY_PREFIX + propertyName];
                if (b == null)
                {
                    return 0;
                }
                else
                {
                    return (byte)b;
                }
            }
        }

        public void SetByte(string propertyName, byte b)
        {
            CheckPropertyName(propertyName);
            _message.ContentHeaderProperties.Headers[BYTE_PROPERTY_PREFIX + propertyName] = b;
        }

        public short GetShort(string propertyName)
        {
            CheckPropertyName(propertyName);
            if (_message.ContentHeaderProperties.Headers == null)
            {
                return 0;
            }
            else
            {
                object s = _message.ContentHeaderProperties.Headers[SHORT_PROPERTY_PREFIX + propertyName];
                if (s == null)
                {
                    return 0;
                }
                else
                {
                    return (short)s;
                }
            }
        }

        public void SetShort(string propertyName, short i)
        {
            CheckPropertyName(propertyName);
            _message.ContentHeaderProperties.Headers[SHORT_PROPERTY_PREFIX + propertyName] = i;
        }

        public int GetInt(string propertyName)
        {
            CheckPropertyName(propertyName);
            if (_message.ContentHeaderProperties.Headers == null)
            {
                return 0;
            }
            else
            {
                object i = _message.ContentHeaderProperties.Headers[INT_PROPERTY_PREFIX + propertyName];
                if (i == null)
                {
                    return 0;
                }
                else
                {
                    return (int)i;
                }
            }
        }

        public void SetInt(string propertyName, int i)
        {
            CheckPropertyName(propertyName);
            _message.ContentHeaderProperties.Headers[INT_PROPERTY_PREFIX + propertyName] = i;
        }

        public long GetLong(string propertyName)
        {
            CheckPropertyName(propertyName);
            if (_message.ContentHeaderProperties.Headers == null)
            {
                return 0;
            }
            else
            {
                object l = _message.ContentHeaderProperties.Headers[LONG_PROPERTY_PREFIX + propertyName];
                if (l == null)
                {
                    // temp - the spec says do this but this throws a NumberFormatException
                    //return Long.valueOf(null).longValue();
                    return 0;
                }
                else
                {
                    return (long)l;
                }
            }
        }

        public void SetLong(string propertyName, long l)
        {
            CheckPropertyName(propertyName);
            _message.ContentHeaderProperties.Headers[LONG_PROPERTY_PREFIX + propertyName] = l;
        }

        public float GetFloat(String propertyName)
        {
            CheckPropertyName(propertyName);
            if (_message.ContentHeaderProperties.Headers == null)
            {
                return 0;
            }
            else
            {
                object f = _message.ContentHeaderProperties.Headers[FLOAT_PROPERTY_PREFIX + propertyName];
                if (f == null)
                {
                    return 0;
                }
                else
                {
                    return (float)f;
                }
            }
        }

        public void SetFloat(string propertyName, float f)
        {
            CheckPropertyName(propertyName);
            _message.ContentHeaderProperties.Headers[FLOAT_PROPERTY_PREFIX + propertyName] = f;
        }

        public double GetDouble(string propertyName)
        {
            CheckPropertyName(propertyName);
            if (_message.ContentHeaderProperties.Headers == null)
            {
                return 0;
            }
            else
            {
                object d = _message.ContentHeaderProperties.Headers[DOUBLE_PROPERTY_PREFIX + propertyName];
                if (d == null)
                {
                    return 0;
                }
                else
                {
                    return (double)d;
                }
            }
        }

        public void SetDouble(string propertyName, double v)
        {
            CheckPropertyName(propertyName);
            _message.ContentHeaderProperties.Headers[DOUBLE_PROPERTY_PREFIX + propertyName] = v;
        }

        public string GetString(string propertyName)
        {
            CheckPropertyName(propertyName);
            if (_message.ContentHeaderProperties.Headers == null)
            {
                return null;
            }
            else
            {
                return (string)_message.ContentHeaderProperties.Headers[STRING_PROPERTY_PREFIX + propertyName];
            }
        }

        public void SetString(string propertyName, string value)
        {
            CheckPropertyName(propertyName);
            CreatePropertyMapIfRequired();
            propertyName = STRING_PROPERTY_PREFIX + propertyName;
            _message.ContentHeaderProperties.Headers[propertyName] = value;
        }

        private void CheckPropertyName(string propertyName)
        {
            if (propertyName == null)
            {
                throw new ArgumentException("Property name must not be null");
            }
            else if ("".Equals(propertyName))
            {
                throw new ArgumentException("Property name must not be the empty string");
            }

            if (_message.ContentHeaderProperties.Headers == null)
            {
                _message.ContentHeaderProperties.Headers = new FieldTable();
            }
        }

        private void CreatePropertyMapIfRequired()
        {
            if (_message.ContentHeaderProperties.Headers == null)
            {
                _message.ContentHeaderProperties.Headers = new FieldTable();
            }
        }

        public override string ToString()
        {
            StringBuilder buf = new StringBuilder("{");
            int i = 0;
            foreach (DictionaryEntry entry in _message.ContentHeaderProperties.Headers)
            {
                ++i;
                if (i > 1)
                {
                    buf.Append(", ");
                }
                string propertyName = (string)entry.Key;
                if (propertyName == null)
                {
                    buf.Append("\nInternal error: Property with NULL key defined");
                }
                else
                {
                    buf.Append(propertyName.Substring(1));

                    buf.Append(" : ");

                    char typeIdentifier = propertyName[0];
                    buf.Append(typeIdentifierToName(typeIdentifier));
                    buf.Append(" = ").Append(entry.Value);
                }
            }
            buf.Append("}");
            return buf.ToString();
        }

        private static string typeIdentifierToName(char typeIdentifier)
        {
            switch (typeIdentifier)
            {
                case BOOLEAN_PROPERTY_PREFIX:
                    return "boolean";
                case BYTE_PROPERTY_PREFIX:
                    return "byte";
                case SHORT_PROPERTY_PREFIX:
                    return "short";
                case INT_PROPERTY_PREFIX:
                    return "int";
                case LONG_PROPERTY_PREFIX:
                    return "long";
                case FLOAT_PROPERTY_PREFIX:
                    return "float";
                case DOUBLE_PROPERTY_PREFIX:
                    return "double";
                case STRING_PROPERTY_PREFIX:
                    return "string";
                default:
                    return "unknown ( '" + typeIdentifier + "')";
            }
        }
    }
}