-
Notifications
You must be signed in to change notification settings - Fork 66
/
Copy pathStompClient.pas
2040 lines (1810 loc) · 57.9 KB
/
StompClient.pas
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
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Stomp Client for Embarcadero Delphi & FreePascal
// Tested With ApacheMQ 5.2/5.3, Apache Apollo 1.2, RabbitMQ
// Copyright (c) 2009-2017 Daniele Teti
//
// Contributors:
// Daniel Gaspary: dgaspary@gmail.com
// Oliver Marr: oliver.sn@wmarr.de
// Marco Mottadelli: mottadelli75@gmail.com
// Marcelo Varela: https://www.facebook.com/marcelo.varela.9?fref=nf
// WebSite: www.danieleteti.it
// email:d.teti@bittime.it
// *******************************************************
unit StompClient;
// For FreePascal users:
// Automatically selected synapse tcp library
{$IFDEF FPC}
{$MODE DELPHI}
{$DEFINE USESYNAPSE}
{$ENDIF}
// For Delphi users:
// Decomment following line to use synapse also in Delphi
{ .$DEFINE USESYNAPSE }
interface
uses
SysUtils,
DateUtils,
{$IFNDEF USESYNAPSE}
IdTCPClient,
IdException,
IdExceptionCore,
IdHeaderList,
IdIOHandler, IdIOHandlerSocket, IdIOHandlerStack, IdSSL, IdSSLOpenSSL, // SSL
System.SyncObjs,
{$ELSE}
synsock,
blcksock,
{$ENDIF}
Classes, System.Generics.Collections;
const
LINE_END: char = #10;
BYTE_LINE_END: Byte = 10;
COMMAND_END: char = #0;
DEFAULT_STOMP_HOST = '127.0.0.1';
DEFAULT_STOMP_PORT = 61613;
DEFAULT_STOMP_TLS_PORT = 61614;
type
// Add by GC 26/01/2011
IStompClient = interface;
IStompFrame = interface;
// Add by Gc 26/01/2011
TStompConnectNotifyEvent = procedure (Client: IStompClient; Frame: IStompFrame) of object;
TAckMode = (amAuto, amClient, amClientIndividual { STOMP 1.1 } );
TStompAcceptProtocol = (Ver_1_0, Ver_1_1);
EStomp = class(Exception)
end;
TKeyValue = record
public
Key: string;
Value: string;
constructor Create(const Key: String; const Value: String);
end;
// PKeyValue = ^TKeyValue;
TSenderFrameEvent = procedure(AFrame: IStompFrame) of object;
StompHeaders = class
const
MESSAGE_ID: string = 'message-id';
TRANSACTION: string = 'transaction';
REPLY_TO: string = 'reply-to';
AUTO_DELETE: string = 'auto-delete';
CONTENT_LENGTH: string = 'content-length';
CONTENT_TYPE: string = 'content-type';
RECEIPT: string = 'receipt';
// RabbitMQ specific headers
PREFETCH_COUNT: string = 'prefetch-count';
X_MESSAGE_TTL: string = 'x-message-ttl';
X_EXPIRES: string = 'x-expires';
TIMESTAMP: string = 'timestamp';
end;
IStompHeaders = interface
['{BD087D9D-0576-4C35-88F9-F5D6348E3894}']
function Add(Key, Value: string): IStompHeaders; overload;
function Add(HeaderItem: TKeyValue): IStompHeaders; overload;
function Value(Key: string): string;
function Remove(Key: string): IStompHeaders;
function IndexOf(Key: string): Integer;
function Count: Cardinal;
function GetAt(const index: Integer): TKeyValue;
function Output: string;
end;
IStompFrame = interface
['{68274885-D3C3-4890-A058-03B769B2191E}']
function Output: string;
function OutputBytes: TBytes;
procedure SetHeaders(const Value: IStompHeaders);
function GetCommand: string;
procedure SetCommand(const Value: string);
function GetBody: string;
procedure SetBody(const Value: string);
property Body: string read GetBody write SetBody;
function GetBytesBody: TBytes;
procedure SetBytesBody(const Value: TBytes);
property BytesBody: TBytes read GetBytesBody write SetBytesBody;
function GetHeaders: IStompHeaders;
function MessageID: string;
function ContentLength: Integer;
function ReplyTo: string;
property Headers: IStompHeaders read GetHeaders write SetHeaders;
property Command: string read GetCommand write SetCommand;
end;
IStompClient = interface
['{EDE6EF1D-59EE-4FCC-9CD7-B183E606D949}']
function Receive(out StompFrame: IStompFrame; ATimeout: Integer)
: Boolean; overload;
function Receive: IStompFrame; overload;
function Receive(ATimeout: Integer): IStompFrame; overload;
procedure Receipt(const ReceiptID: string);
function SetHost(Host: string): IStompClient;
function SetPort(Port: Integer): IStompClient;
function SetVirtualHost(VirtualHost: string): IStompClient;
function SetClientId(ClientId: string): IStompClient;
function SetAcceptVersion(AcceptVersion: TStompAcceptProtocol): IStompClient;
function Connect: IStompClient;
function Clone: IStompClient;
procedure Disconnect;
procedure Subscribe(QueueOrTopicName: string; Ack: TAckMode = amAuto;
Headers: IStompHeaders = nil);
procedure Unsubscribe(Queue: string; const subscriptionId: string = ''); // Unsubscribe STOMP 1.1 : It requires that the id header matches the id value of previous SUBSCRIBE operation.
procedure Send(QueueOrTopicName: string; TextMessage: string;
Headers: IStompHeaders = nil); overload;
procedure Send(QueueOrTopicName: string; TextMessage: string;
TransactionIdentifier: string; Headers: IStompHeaders = nil); overload;
procedure Send(QueueOrTopicName: string; ByteMessage: TBytes;
Headers: IStompHeaders = nil); overload;
procedure Send(QueueOrTopicName: string; ByteMessage: TBytes;
TransactionIdentifier: string; Headers: IStompHeaders = nil); overload;
procedure Ack(const MessageID: string; const subscriptionId: string = '';
const TransactionIdentifier: string = ''); // ACK STOMP 1.1 : has two REQUIRED headers: message-id, which MUST contain a value matching the message-id for the MESSAGE being acknowledged and subscription, which MUST be set to match the value of the subscription's id header
{ ** STOMP 1.1 ** }
procedure Nack(const MessageID: string; const subscriptionId: string = ''; // NACK STOMP 1.1 : takes the same headers as ACK: message-id (mandatory), subscription (mandatory) and transaction (OPTIONAL).
const TransactionIdentifier: string = '');
procedure BeginTransaction(const TransactionIdentifier: string);
procedure CommitTransaction(const TransactionIdentifier: string);
procedure AbortTransaction(const TransactionIdentifier: string);
{ ****************************************************************** }
Function SetUseSSL(const boUseSSL: boolean; const PassThrough: Boolean = True;
const KeyFile : string =''; const CertFile : string = '';
const PassPhrase : string = ''): IStompClient; // SSL
function SetPassword(const Value: string): IStompClient;
function SetUserName(const Value: string): IStompClient;
function SetReceiveTimeout(const AMilliSeconds: Cardinal): IStompClient;
function SetHeartBeat(const OutgoingHeartBeats, IncomingHeartBeats: Int64): IStompClient;
function Connected: Boolean;
function GetProtocolVersion: string;
function GetServer: string;
function GetSession: string;
function SetConnectionTimeout(const Value: UInt32): IStompClient;
function SetOnBeforeSendFrame(const Value: TSenderFrameEvent): IStompClient;
function SetOnAfterSendFrame(const Value: TSenderFrameEvent): IStompClient;
function SetOnHeartBeatError(const Value: TNotifyEvent): IStompClient;
function GetOnConnect: TStompConnectNotifyEvent;
procedure SetOnConnect(const Value: TStompConnectNotifyEvent);
property OnConnect: TStompConnectNotifyEvent read GetOnConnect write SetOnConnect;
end;
TAddress = record
Host: string;
Port: Integer;
UserName: string;
Password: string;
end;
TAddresses = array of TAddress;
IStompListener = interface
['{CB3EB297-8616-408E-A0B2-7CCC11224DBC}']
procedure StopListening;
procedure StartListening;
end;
IStompClientListener = interface
['{C4C0D932-8994-43FB-9D32-A03FE86AEFE4}']
procedure OnMessage(StompFrame: IStompFrame; var TerminateListener: Boolean);
procedure OnListenerStopped(StompClient: IStompClient);
end;
StompUtils = class
class function StompClient: IStompClient;
class function StompClientAndConnect(Host: string = DEFAULT_STOMP_HOST;
Port: Integer = DEFAULT_STOMP_PORT;
VirtualHost: string = '';
ClientID: string = '';
AcceptVersion: TStompAcceptProtocol = TStompAcceptProtocol.
Ver_1_0): IStompClient;
class function NewDurableSubscriptionHeader(const SubscriptionName: string): TKeyValue;
class function NewPersistentHeader(const Value: Boolean): TKeyValue;
class function NewReplyToHeader(const DestinationName: string): TKeyValue;
class function CreateListener(const StompClient: IStompClient;
const StompClientListener: IStompClientListener): IStompListener;
class function StripLastChar(Buf: string): string;
class function CreateFrame: IStompFrame;
class function CreateFrameWithBuffer(Buf: string): IStompFrame; overload;
class function CreateFrameWithBuffer(Buf: TBytes): IStompFrame; overload;
class function AckModeToStr(AckMode: TAckMode): string;
class function NewHeaders: IStompHeaders; deprecated 'Use Headers instead';
class function Headers: IStompHeaders;
class function NewFrame: IStompFrame;
class function TimestampAsDateTime(const HeaderValue: string): TDateTime;
end;
implementation
{$IFDEF FPC}
const
CHAR0 = #0;
{$ELSE}
uses
// Windows, // Remove windows unit for compiling on ios
IdGlobal,
IdGlobalProtocols,
Character;
{$ENDIF}
type
TStompFrame = class(TInterfacedObject, IStompFrame)
private
FCommand: string;
FBody: TBytes;
FContentLength: Integer;
FHeaders: IStompHeaders;
procedure SetHeaders(const Value: IStompHeaders);
function GetCommand: string;
procedure SetCommand(const Value: string);
function GetBody: string;
procedure SetBody(const Value: string);
function GetBytesBody: TBytes;
procedure SetBytesBody(const Value: TBytes);
function GetHeaders: IStompHeaders;
public
constructor Create;
destructor Destroy; override;
property Command: string read GetCommand write SetCommand;
property Body: string read GetBody write SetBody;
property BytesBody: TBytes read GetBytesBody write SetBytesBody;
// return '', when Key doesn't exist or Value of Key is ''
// otherwise, return Value;
function Output: string;
function OutputBytes: TBytes;
function MessageID: string;
function ContentLength: Integer;
function ReplyTo: string;
property Headers: IStompHeaders read GetHeaders write SetHeaders;
end;
TStompClientListener = class(TInterfacedObject, IStompListener)
strict private
FReceiverThread: TThread;
FTerminated: Boolean;
private
FStompClientListener: IStompClientListener;
strict protected
FStompClient: IStompClient;
public
constructor Create(const StompClient: IStompClient;
const StompClientListener: IStompClientListener); virtual;
destructor Destroy; override;
procedure StartListening;
procedure StopListening;
end;
TReceiverThread = class(TThread)
private
FStompClient: IStompClient;
FStompClientListener: IStompClientListener;
protected
procedure Execute; override;
public
constructor Create(StompClient: IStompClient; StompClientListener: IStompClientListener);
end;
THeartBeatThread = class;
{ TStompClient }
TStompClient = class(TInterfacedObject, IStompClient)
private
{$IFDEF USESYNAPSE}
FSynapseTCP: TTCPBlockSocket;
FSynapseConnected: boolean;
{$ELSE}
FTCP: TIdTCPClient;
FIOHandlerSocketOpenSSL : TIdSSLIOHandlerSocketOpenSSL;
{$ENDIF}
FOnConnect: TStompConnectNotifyEvent; // Add By GC 26/01/2011
FHeaders: IStompHeaders;
FPassword: string;
FUserName: string;
FTimeout: Integer;
FSession: string;
FInTransaction: boolean;
FTransactions: TStringList;
FReceiptTimeout: Integer;
FServerProtocolVersion: string;
FClientAcceptProtocolVersion: TStompAcceptProtocol;
FServer: string;
FOnBeforeSendFrame: TSenderFrameEvent;
FOnAfterSendFrame: TSenderFrameEvent;
FHost: string;
FPort: Integer;
FVirtualHost: string;
FClientID: string;
FUseSSL : boolean; // SSL
FsslKeyFile : string; // SSL
FsslCertFile : string; // SSL
FsslKeyPass : string; // SSL
FPassThrough : Boolean; // SSL
FAcceptVersion: TStompAcceptProtocol;
FConnectionTimeout: UInt32;
FOutgoingHeartBeats: Int64;
FIncomingHeartBeats: Int64;
FLock: TObject;
FHeartBeatThread: THeartBeatThread;
FServerIncomingHeartBeats: Int64;
FServerOutgoingHeartBeats: Int64;
FOnHeartBeatError: TNotifyEvent;
procedure ParseHeartBeat(Headers: IStompHeaders);
procedure SetReceiptTimeout(const Value: Integer);
function GetOnConnect: TStompConnectNotifyEvent;
procedure SetOnConnect(const Value: TStompConnectNotifyEvent);
protected
{$IFDEF USESYNAPSE}
procedure SynapseSocketCallBack(Sender: TObject; Reason: THookSocketReason;
const Value: string);
{$ENDIF}
procedure Init;
procedure DeInit;
procedure MergeHeaders(var AFrame: IStompFrame;
var AHeaders: IStompHeaders);
procedure SendFrame(AFrame: IStompFrame; AsBytes: boolean = false);
procedure SendHeartBeat;
function FormatErrorFrame(const AErrorFrame: IStompFrame): string;
function ServerSupportsHeartBeat: boolean;
procedure OnHeartBeatErrorHandler(Sender: TObject);
procedure DoHeartBeatErrorHandler;
procedure OpenSSLGetPassword(var Password: String);
public
Function SetUseSSL(const boUseSSL: boolean; const PassThrough: Boolean = True;
const KeyFile : string =''; const CertFile : string = '';
const PassPhrase : string = ''): IStompClient; // SSL
function SetPassword(const Value: string): IStompClient;
function SetUserName(const Value: string): IStompClient;
function Receive(out StompFrame: IStompFrame; ATimeout: Integer)
: boolean; overload;
function Receive: IStompFrame; overload;
function Receive(ATimeout: Integer): IStompFrame; overload;
procedure Receipt(const ReceiptID: string);
function SetHost(Host: string): IStompClient;
function SetPort(Port: Integer): IStompClient;
function SetVirtualHost(VirtualHost: string): IStompClient;
function SetClientId(ClientId: string): IStompClient;
function SetAcceptVersion(AcceptVersion: TStompAcceptProtocol): IStompClient;
function Connect: IStompClient;
procedure Disconnect;
procedure Subscribe(QueueOrTopicName: string;
Ack: TAckMode = TAckMode.amAuto; Headers: IStompHeaders = nil);
procedure Unsubscribe(Queue: string; const subscriptionId: string = ''); // Unsubscribe STOMP 1.1 : It requires that the id header matches the id value of previous SUBSCRIBE operation.
procedure Send(QueueOrTopicName: string; TextMessage: string;
Headers: IStompHeaders = nil); overload;
procedure Send(QueueOrTopicName: string; TextMessage: string;
TransactionIdentifier: string; Headers: IStompHeaders = nil); overload;
procedure Send(QueueOrTopicName: string; ByteMessage: TBytes;
Headers: IStompHeaders = nil); overload;
procedure Send(QueueOrTopicName: string; ByteMessage: TBytes;
TransactionIdentifier: string; Headers: IStompHeaders = nil); overload;
procedure Ack(const MessageID: string; const subscriptionId: string = '';
const TransactionIdentifier: string = ''); // ACK STOMP 1.1 : has two REQUIRED headers: message-id, which MUST contain a value matching the message-id for the MESSAGE being acknowledged and subscription, which MUST be set to match the value of the subscription's id header
{ STOMP 1.1 }
procedure Nack(const MessageID: string; const subscriptionId: string = '';
const TransactionIdentifier: string = ''); // NACK STOMP 1.1 : takes the same headers as ACK: message-id (mandatory), subscription (mandatory) and transaction (OPTIONAL).
procedure BeginTransaction(const TransactionIdentifier: string);
procedure CommitTransaction(const TransactionIdentifier: string);
procedure AbortTransaction(const TransactionIdentifier: string);
/// ////////////
constructor Create; overload; virtual;
destructor Destroy; override;
function SetHeartBeat(const OutgoingHeartBeats, IncomingHeartBeats: Int64): IStompClient;
function Clone: IStompClient;
function Connected: boolean;
function SetReceiveTimeout(const AMilliSeconds: Cardinal): IStompClient;
function GetProtocolVersion: string;
function GetServer: string;
function GetSession: string;
property ReceiptTimeout: Integer read FReceiptTimeout
write SetReceiptTimeout;
property Transactions: TStringList read FTransactions;
function SetConnectionTimeout(const Value: UInt32): IStompClient;
property ConnectionTimeout: UInt32 read FConnectionTimeout
write FConnectionTimeout;
// * Manage Events
function SetOnAfterSendFrame(const Value: TSenderFrameEvent): IStompClient;
function SetOnBeforeSendFrame(const Value: TSenderFrameEvent): IStompClient;
function SetOnHeartBeatError(const Value: TNotifyEvent): IStompClient;
// Add by GC 26/01/2001
property OnConnect: TStompConnectNotifyEvent read GetOnConnect write SetOnConnect;
end;
THeartBeatThread = class(TThread)
private
FStompClient: TStompClient;
FLock: TObject;
FOutgoingHeatBeatTimeout: Int64;
FOnHeartBeatError: TNotifyEvent;
protected
procedure Execute; override;
procedure DoHeartBeatError;
public
constructor Create(StompClient: TStompClient; Lock: TObject;
OutgoingHeatBeatTimeout: Int64); virtual;
property OnHeartBeatError: TNotifyEvent read FOnHeartBeatError write FOnHeartBeatError;
end;
TStompHeaders = class(TInterfacedObject, IStompHeaders)
private
FList: TList<TKeyValue>;
function GetItems(index: Cardinal): TKeyValue;
procedure SetItems(index: Cardinal; const Value: TKeyValue);
public
class function NewDurableSubscriptionHeader(const SubscriptionName: string): TKeyValue;
deprecated 'Use Subscription instead';
class function NewPersistentHeader(const Value: Boolean): TKeyValue;
deprecated 'Use Persistent instead';
class function NewReplyToHeader(const DestinationName: string): TKeyValue;
deprecated 'Use ReplyTo instead';
class function Subscription(const SubscriptionName: string): TKeyValue;
class function Persistent(const Value: Boolean): TKeyValue;
class function Durable(const Value: Boolean): TKeyValue;
class function ReplyTo(const DestinationName: string): TKeyValue;
/// /
function Add(Key, Value: string): IStompHeaders; overload;
function Add(HeaderItem: TKeyValue): IStompHeaders; overload;
function Value(Key: string): string;
function Remove(Key: string): IStompHeaders;
function IndexOf(Key: string): Integer;
function Count: Cardinal;
function GetAt(const index: Integer): TKeyValue;
constructor Create;
destructor Destroy; override;
function Output: string;
property Items[index: Cardinal]: TKeyValue read GetItems
write SetItems; default;
end;
class function TStompHeaders.NewDurableSubscriptionHeader(const SubscriptionName
: string): TKeyValue;
begin
Result := Subscription(SubscriptionName);
end;
class function TStompHeaders.NewPersistentHeader(const Value: Boolean)
: TKeyValue;
begin
Result := Persistent(Value);
end;
class function TStompHeaders.NewReplyToHeader(const DestinationName: string)
: TKeyValue;
begin
Result := ReplyTo(DestinationName);
end;
constructor TStompFrame.Create;
begin
FHeaders := TStompHeaders.Create;
self.FCommand := '';
SetLength(self.FBody, 0);
self.FContentLength := 0;
end;
destructor TStompFrame.Destroy;
begin
inherited;
end;
function TStompFrame.GetBody: string;
begin
Result := TEncoding.UTF8.GetString(FBody);
end;
function TStompFrame.GetBytesBody: TBytes;
begin
Result := FBody;
end;
function TStompFrame.GetCommand: string;
begin
Result := FCommand;
end;
function TStompFrame.GetHeaders: IStompHeaders;
begin
Result := FHeaders;
end;
function TStompFrame.MessageID: string;
begin
Result := self.GetHeaders.Value(StompHeaders.MESSAGE_ID);
end;
function TStompFrame.Output: string;
begin
Result := FCommand + LINE_END + FHeaders.Output + LINE_END + GetBody +
COMMAND_END;
end;
function TStompFrame.OutputBytes: TBytes;
begin
Result := TEncoding.UTF8.GetBytes(FCommand + LINE_END + FHeaders.Output + LINE_END)
+ GetBytesBody + TEncoding.UTF8.GetBytes(COMMAND_END);
end;
function TStompFrame.ReplyTo: string;
begin
Result := self.GetHeaders.Value(StompHeaders.REPLY_TO);
end;
function TStompFrame.ContentLength: Integer;
begin
Result := FContentLength;
end;
procedure TStompFrame.SetBody(const Value: string);
begin
SetBytesBody(TEncoding.UTF8.GetBytes(Value));
end;
procedure TStompFrame.SetBytesBody(const Value: TBytes);
begin
FBody := Value;
FContentLength := Length(FBody);
end;
procedure TStompFrame.SetCommand(const Value: string);
begin
FCommand := Value;
end;
procedure TStompFrame.SetHeaders(const Value: IStompHeaders);
begin
FHeaders := Value;
end;
function GetLine(Buf: string; var From: Integer): string;
var
i: Integer;
begin
if (From > Length(Buf)) then
raise EStomp.Create('From out of bound.');
i := From;
while (i <= Length(Buf)) do
begin
if (Buf[i] <> LINE_END) then
inc(i)
else
break;
end;
if (Buf[i] = LINE_END) then
begin
Result := Copy(Buf, From, i - From);
From := i + 1;
exit;
end
else
raise EStomp.Create('End of Line not found.');
end;
function GetByteLine(Buf: TBytes; var From: Integer): TBytes;
var
i: Integer;
begin
if (From > Length(Buf)) then
raise EStomp.Create('From out of bound.');
i := From;
while (i <= Length(Buf)) do
begin
if (Buf[i] <> BYTE_LINE_END) then
inc(i)
else
break;
end;
if (Buf[i] = BYTE_LINE_END) then
begin
Result := Copy(Buf, From, i - From);
From := i + 1;
exit;
end
else
raise EStomp.Create('End of Line not found.');
end;
{ TStompHeaders }
function TStompHeaders.Add(Key, Value: string): IStompHeaders;
begin
FList.Add(TKeyValue.Create(Key, Value));
Result := self;
end;
function TStompHeaders.Add(HeaderItem: TKeyValue): IStompHeaders;
begin
Result := Add(HeaderItem.Key, HeaderItem.Value);
end;
function TStompHeaders.Count: Cardinal;
begin
Result := FList.Count;
end;
constructor TStompHeaders.Create;
begin
inherited;
FList := TList<TKeyValue>.Create;
end;
destructor TStompHeaders.Destroy;
begin
FList.Free;
inherited;
end;
class function TStompHeaders.Durable(const Value: Boolean): TKeyValue;
begin
Result := TKeyValue.Create('durable', LowerCase(BoolToStr(Value, true)));
end;
function TStompHeaders.GetAt(const index: Integer): TKeyValue;
begin
Result := GetItems(index)
end;
function TStompHeaders.GetItems(index: Cardinal): TKeyValue;
begin
Result := FList[index];
end;
function TStompHeaders.IndexOf(Key: string): Integer;
var
i: Integer;
begin
Result := -1;
for i := 0 to FList.Count - 1 do
begin
if GetItems(i).Key = Key then
begin
Result := i;
break;
end;
end;
end;
function TStompHeaders.Output: string;
var
i: Integer;
kv: TKeyValue;
begin
Result := '';
if FList.Count > 0 then
for i := 0 to FList.Count - 1 do
begin
kv := Items[i];
Result := Result + kv.Key + ':' + kv.Value + LINE_END;
end
else
Result := LINE_END;
end;
class function TStompHeaders.Persistent(const Value: Boolean): TKeyValue;
begin
Result := TKeyValue.Create('persistent', LowerCase(BoolToStr(Value, true)));
end;
function TStompHeaders.Remove(Key: string): IStompHeaders;
var
p: Integer;
begin
p := IndexOf(Key);
FList.Delete(p);
Result := self;
end;
class function TStompHeaders.ReplyTo(const DestinationName: string): TKeyValue;
begin
Result := TKeyValue.Create('reply-to', DestinationName);
end;
procedure TStompHeaders.SetItems(index: Cardinal; const Value: TKeyValue);
var
p: Integer;
begin
p := IndexOf(Value.Key);
// FList[p].Free;
FList[p] := Value;
end;
class function TStompHeaders.Subscription(
const SubscriptionName: string): TKeyValue;
begin
Result := TKeyValue.Create('id', SubscriptionName);
end;
function TStompHeaders.Value(Key: string): string;
var
i: Integer;
begin
Result := '';
i := IndexOf(Key);
if i > -1 then
Result := GetItems(i).Value;
end;
{ TStompListener }
constructor TStompClientListener.Create(const StompClient: IStompClient;
const StompClientListener: IStompClientListener);
begin
FStompClientListener := StompClientListener;
FStompClient := StompClient;
FTerminated := False;
FReceiverThread := nil;
inherited Create;
end;
destructor TStompClientListener.Destroy;
begin
FTerminated := true;
FReceiverThread.Free;
inherited;
end;
procedure TStompClientListener.StartListening;
begin
if Assigned(FReceiverThread) then
raise EStomp.Create('Already listening');
FReceiverThread := TReceiverThread.Create(FStompClient, FStompClientListener);
FReceiverThread.Start;
end;
procedure TStompClientListener.StopListening;
begin
if not Assigned(FReceiverThread) then
exit;
FReceiverThread.Terminate;
FReceiverThread.Free;
FReceiverThread := nil;
end;
{ TReceiverThread }
constructor TReceiverThread.Create(StompClient: IStompClient;
StompClientListener: IStompClientListener);
begin
inherited Create(true);
FStompClient := StompClient;
FStompClientListener := StompClientListener;
end;
procedure TReceiverThread.Execute;
var
LFrame: IStompFrame;
LTerminateListener: Boolean;
begin
try
LTerminateListener := False;
while (not Terminated) and (not LTerminateListener) do
begin
if FStompClient.Receive(LFrame, 1000) then
begin
TThread.Synchronize(nil,
procedure
begin
FStompClientListener.OnMessage(LFrame, LTerminateListener);
end);
end;
end;
finally
TThread.Synchronize(nil,
procedure
begin
FStompClientListener.OnListenerStopped(FStompClient);
end);
end;
end;
{ TStompClient }
procedure TStompClient.AbortTransaction(const TransactionIdentifier: string);
var
Frame: IStompFrame;
begin
if FTransactions.IndexOf(TransactionIdentifier) > -1 then
begin
Frame := TStompFrame.Create;
Frame.Command := 'ABORT';
Frame.Headers.Add('transaction', TransactionIdentifier);
SendFrame(Frame);
FInTransaction := False;
FTransactions.Delete(FTransactions.IndexOf(TransactionIdentifier));
end
else
raise EStomp.CreateFmt
('Abort Transaction Error. Transaction [%s] not found',
[TransactionIdentifier]);
end;
procedure TStompClient.Ack(const MessageID: string; const subscriptionId: string;
const TransactionIdentifier: string);
var
Frame: IStompFrame;
begin
Frame := TStompFrame.Create;
Frame.Command := 'ACK';
Frame.Headers.Add(StompHeaders.MESSAGE_ID, MessageID);
if subscriptionId <> '' then
Frame.Headers.Add('subscription', subscriptionId);
if TransactionIdentifier <> '' then
Frame.Headers.Add('transaction', TransactionIdentifier);
SendFrame(Frame);
end;
procedure TStompClient.BeginTransaction(const TransactionIdentifier: string);
var
Frame: IStompFrame;
begin
if FTransactions.IndexOf(TransactionIdentifier) = -1 then
begin
Frame := TStompFrame.Create;
Frame.Command := 'BEGIN';
Frame.Headers.Add('transaction', TransactionIdentifier);
SendFrame(Frame);
// CheckReceipt(Frame);
FInTransaction := True;
FTransactions.Add(TransactionIdentifier);
end
else
raise EStomp.CreateFmt
('Begin Transaction Error. Transaction [%s] still open',
[TransactionIdentifier]);
end;
// procedure TStompClient.CheckReceipt(Frame: TStompFrame);
// var
// ReceiptID: string;
// begin
// if FEnableReceipts then
// begin
// ReceiptID := inttostr(GetTickCount);
// Frame.Headers.Add('receipt', ReceiptID);
// SendFrame(Frame);
// Receipt(ReceiptID);
// end
// else
// SendFrame(Frame);
// end;
function TStompClient.Clone: IStompClient;
begin
Result := TStompClient.Create;
Result
.SetUserName(FUserName)
.SetPassword(FPassword)
.SetConnectionTimeout(FConnectionTimeout)
.SetHeartBeat(FOutgoingHeartBeats, FIncomingHeartBeats)
.SetHost(FHost)
.SetPort(FPort)
.SetVirtualHost(FVirtualHost)
.SetClientID(FClientId)
.SetAcceptVersion(FAcceptVersion)
.Connect;
end;
procedure TStompClient.CommitTransaction(const TransactionIdentifier: string);
var
Frame: IStompFrame;
begin
if FTransactions.IndexOf(TransactionIdentifier) > -1 then
begin
Frame := TStompFrame.Create;
Frame.Command := 'COMMIT';
Frame.Headers.Add('transaction', TransactionIdentifier);
SendFrame(Frame);
FInTransaction := False;
FTransactions.Delete(FTransactions.IndexOf(TransactionIdentifier));
end
else
raise EStomp.CreateFmt
('Commit Transaction Error. Transaction [%s] not found',
[TransactionIdentifier]);
end;
function TStompClient.SetHost(Host: string): IStompClient;
begin
FHost := Host;
Result := Self;
end;
function TStompClient.SetPort(Port: Integer): IStompClient;
begin
FPort := Port;
Result := Self;
end;
function TStompClient.SetVirtualHost(VirtualHost: string): IStompClient;
begin
FVirtualHost := VirtualHost;
Result := Self;
end;
function TStompClient.SetClientId(ClientId: string): IStompClient;
begin
FClientId := ClientId;
Result := Self;
end;
function TStompClient.SetAcceptVersion(AcceptVersion: TStompAcceptProtocol): IStompClient;
begin
FAcceptVersion := AcceptVersion;
Result := Self;
end;
function TStompClient.Connect: IStompClient;
var
Frame: IStompFrame;
lHeartBeat: string;
begin
try
Init;
{$IFDEF USESYNAPSE}
FSynapseConnected := False;
FSynapseTCP.Connect(FHost, intToStr(FPort));
FSynapseConnected := True;
{$ELSE}
if FUseSSL then
begin
FIOHandlerSocketOpenSSL.OnGetPassword := OpenSSLGetPassword;
FIOHandlerSocketOpenSSL.Port := 0 ;
FIOHandlerSocketOpenSSL.DefaultPort := 0 ;
FIOHandlerSocketOpenSSL.SSLOptions.Method := sslvTLSv1_2; //sslvSSLv3; //sslvSSLv23;
FIOHandlerSocketOpenSSL.SSLOptions.KeyFile := FsslKeyFile;
FIOHandlerSocketOpenSSL.SSLOptions.CertFile := FsslCertFile;
FIOHandlerSocketOpenSSL.SSLOptions.Mode := sslmUnassigned; //sslmClient;
FIOHandlerSocketOpenSSL.SSLOptions.VerifyMode := [];
FIOHandlerSocketOpenSSL.SSLOptions.VerifyDepth := 0;
// FIOHandlerSocketOpenSSL.OnBeforeConnect := BeforeConnect;
FIOHandlerSocketOpenSSL.PassThrough := FPassThrough;
FTCP.IOHandler := FIOHandlerSocketOpenSSL;
end
else
begin
FTCP.IOHandler := nil;
end;