-
Notifications
You must be signed in to change notification settings - Fork 637
/
Copy pathSession.java
3007 lines (2662 loc) · 117 KB
/
Session.java
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
/*******************************************************************************
* Copyright (c) quickfixj.org All rights reserved.
*
* This file is part of the QuickFIX FIX Engine
*
* This file may be distributed under the terms of the quickfixj.org
* license as defined by quickfixj.org and appearing in the file
* LICENSE included in the packaging of this file.
*
* This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING
* THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE.
*
* See http://www.quickfixengine.org/LICENSE for licensing information.
*
* Contact [email protected] if any conditions of this licensing
* are not clear to you.
******************************************************************************/
package quickfix;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import quickfix.Message.Header;
import quickfix.SessionState.ResendRange;
import quickfix.field.ApplVerID;
import quickfix.field.BeginSeqNo;
import quickfix.field.BeginString;
import quickfix.field.BusinessRejectReason;
import quickfix.field.DefaultApplVerID;
import quickfix.field.EncryptMethod;
import quickfix.field.EndSeqNo;
import quickfix.field.GapFillFlag;
import quickfix.field.HeartBtInt;
import quickfix.field.LastMsgSeqNumProcessed;
import quickfix.field.MsgSeqNum;
import quickfix.field.MsgType;
import quickfix.field.NewSeqNo;
import quickfix.field.NextExpectedMsgSeqNum;
import quickfix.field.OrigSendingTime;
import quickfix.field.PossDupFlag;
import quickfix.field.RefMsgType;
import quickfix.field.RefSeqNum;
import quickfix.field.RefTagID;
import quickfix.field.ResetSeqNumFlag;
import quickfix.field.SenderCompID;
import quickfix.field.SenderLocationID;
import quickfix.field.SenderSubID;
import quickfix.field.SendingTime;
import quickfix.field.SessionRejectReason;
import quickfix.field.SessionStatus;
import quickfix.field.TargetCompID;
import quickfix.field.TargetLocationID;
import quickfix.field.TargetSubID;
import quickfix.field.TestReqID;
import quickfix.field.Text;
import quickfix.mina.EventHandlingStrategy;
import java.io.Closeable;
import java.io.IOException;
import java.net.InetAddress;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import static quickfix.LogUtil.logThrowable;
/**
* The Session is the primary FIX abstraction for message communication.
* <p>
* It performs sequencing and error recovery and represents a communication
* channel to a counter-party. Sessions are independent of specific
* communication layer connections. The Session could span many sequential
* connections (but cannot operate on multiple connection simultaneously).
* <p>
* A logical session is defined as starting with message sequence number 1
* and ending when the session is reset. However, the Session object
* instance is registered when first created (per SessionID), and remains
* registered for the lifetime of the application (until the Connector is
* stopped), even across resets (which reset its internal state, such as
* the sequence number).
*/
public class Session implements Closeable {
/**
* Session setting for heartbeat interval (in seconds).
*/
public static final String SETTING_HEARTBTINT = "HeartBtInt";
/**
* Session setting for enabling message latency checks. Values are "Y" or
* "N".
*/
public static final String SETTING_CHECK_LATENCY = "CheckLatency";
/**
* If set to Y, messages must be received from the counterparty with the
* correct SenderCompID and TargetCompID. Some systems will send you
* different CompIDs by design, so you must set this to N.
*/
public static final String SETTING_CHECK_COMP_ID = "CheckCompID";
/**
* Session setting for maximum message latency (in seconds).
*/
public static final String SETTING_MAX_LATENCY = "MaxLatency";
/**
* Session setting for the test delay multiplier (0-1, as fraction of Heartbeat interval)
*/
public static final String SETTING_TEST_REQUEST_DELAY_MULTIPLIER = "TestRequestDelayMultiplier";
/**
* Session scheduling setting to specify that session never reset
*/
public static final String SETTING_NON_STOP_SESSION = "NonStopSession";
/**
* Session scheduling setting to specify first day of trading week.
*/
public static final String SETTING_START_DAY = "StartDay";
/**
* Session scheduling setting to specify last day of trading week.
*/
public static final String SETTING_END_DAY = "EndDay";
/**
* Session scheduling setting to specify time zone for the session.
*/
public static final String SETTING_TIMEZONE = "TimeZone";
/**
* Session scheduling setting to specify starting time of the trading day.
*/
public static final String SETTING_START_TIME = "StartTime";
/**
* Session scheduling setting to specify end time of the trading day.
*/
public static final String SETTING_END_TIME = "EndTime";
/**
* Session scheduling setting to specify active days of the week.
*/
public static final String SETTING_WEEKDAYS = "Weekdays";
/**
* Session setting to indicate whether a data dictionary should be used. If
* a data dictionary is not used then message validation is not possible.
*/
public static final String SETTING_USE_DATA_DICTIONARY = "UseDataDictionary";
/**
* Session setting specifying the path to the data dictionary to use for
* this session. This setting supports the possibility of a custom data
* dictionary for each session. Normally, the default data dictionary for a
* specific FIX version will be specified.
*/
public static final String SETTING_DATA_DICTIONARY = "DataDictionary";
/**
* Session setting specifying the path to the transport data dictionary.
* This setting supports the possibility of a custom transport data
* dictionary for each session. This setting would only be used with FIXT 1.1 and
* new transport protocols.
*/
public static final String SETTING_TRANSPORT_DATA_DICTIONARY = "TransportDataDictionary";
/**
* Session setting specifying the path to the application data dictionary to use for
* this session. This setting supports the possibility of a custom application data
* dictionary for each session. This setting would only be used with FIXT 1.1 and
* new transport protocols. This setting can be used as a prefix to specify multiple
* application dictionaries for the FIXT transport. For example:
* <pre><code>
* DefaultApplVerID=FIX.4.2
* AppDataDictionary=FIX42.xml
* AppDataDictionary.FIX.4.4=FIX44.xml
* </code></pre>
* This would use FIX42.xml for the default application version ID and FIX44.xml for
* any FIX 4.4 messages.
*/
public static final String SETTING_APP_DATA_DICTIONARY = "AppDataDictionary";
/**
* Default is "Y".
* If set to N, fields that are out of order (i.e. body fields in the header, or header fields in the body) will not be rejected.
*/
public static final String SETTING_VALIDATE_FIELDS_OUT_OF_ORDER = "ValidateFieldsOutOfOrder";
/**
* Session validation setting for enabling whether field ordering is
* validated. Values are "Y" or "N". Default is "Y".
*/
public static final String SETTING_VALIDATE_UNORDERED_GROUP_FIELDS = "ValidateUnorderedGroupFields";
/**
* Session validation setting for enabling whether field values are
* validated. Empty fields values are not allowed. Values are "Y" or "N".
* Default is "Y".
*/
public static final String SETTING_VALIDATE_FIELDS_HAVE_VALUES = "ValidateFieldsHaveValues";
/**
* Allow to bypass the message validation. Default is "Y".
*/
public static final String SETTING_VALIDATE_INCOMING_MESSAGE = "ValidateIncomingMessage";
/**
* Session setting for logon timeout (in seconds).
*/
public static final String SETTING_LOGON_TIMEOUT = "LogonTimeout";
/**
* Session setting for logout timeout (in seconds).
*/
public static final String SETTING_LOGOUT_TIMEOUT = "LogoutTimeout";
/**
* Session setting for doing an automatic sequence number reset on logout.
* Valid values are "Y" or "N". Default is "N".
*/
public static final String SETTING_RESET_ON_LOGOUT = "ResetOnLogout";
/**
* Check the next expected target SeqNum against the received SeqNum. Default is "Y".
* If a mismatch is detected, apply the following logic:
* <ul>
* <li>if lower than expected SeqNum , logout</li>
* <li>if higher, send a resend request</li>
* </ul>
*/
public static final String SETTING_VALIDATE_SEQUENCE_NUMBERS = "ValidateSequenceNumbers";
/**
* Session setting for doing an automatic sequence number reset on
* disconnect. Valid values are "Y" or "N". Default is "N".
*/
public static final String SETTING_RESET_ON_DISCONNECT = "ResetOnDisconnect";
/**
* Session setting for doing an automatic reset when an error occurs. Valid values are "Y" or "N". Default is "N". A
* reset means disconnect, sequence numbers reset, store cleaned and reconnect, as for a daily reset.
*/
public static final String SETTING_RESET_ON_ERROR = "ResetOnError";
/**
* Session setting for doing an automatic disconnect when an error occurs. Valid values are "Y" or "N". Default is
* "N".
*/
public static final String SETTING_DISCONNECT_ON_ERROR = "DisconnectOnError";
/**
* Session setting to control precision in message timestamps.
* Valid values are "SECONDS", "MILLIS", "MICROS", "NANOS". Default is "MILLIS".
* Only valid for FIX version >= 4.2.
*/
public static final String SETTING_TIMESTAMP_PRECISION = "TimeStampPrecision";
/**
* Controls validation of user-defined fields.
*/
public static final String SETTING_VALIDATE_USER_DEFINED_FIELDS = "ValidateUserDefinedFields";
/**
* Session setting that causes the session to reset sequence numbers when initiating
* a logon (>= FIX 4.2).
*/
public static final String SETTING_RESET_ON_LOGON = "ResetOnLogon";
/**
* Session description. Used by external tools.
*/
public static final String SETTING_DESCRIPTION = "Description";
/**
* Requests that state and message data be refreshed from the message store at
* logon, if possible. This supports simple failover behavior for acceptors
*/
public static final String SETTING_REFRESH_ON_LOGON = "RefreshOnLogon";
/**
* Configures the session to send redundant resend requests (off, by default).
*/
public static final String SETTING_SEND_REDUNDANT_RESEND_REQUEST = "SendRedundantResendRequests";
/**
* Persist messages setting (true, by default). If set to false this will cause the Session to
* not persist any messages and all resend requests will be answered with a gap fill.
*/
public static final String SETTING_PERSIST_MESSAGES = "PersistMessages";
/**
* Use actual end of sequence gap for resend requests rather than using "infinity"
* as the end sequence of the gap. Not recommended by the FIX specification, but
* needed for some counterparties.
*/
public static final String SETTING_USE_CLOSED_RESEND_INTERVAL = "ClosedResendInterval";
/**
* Allow unknown fields in messages. This is intended for unknown fields with tags < 5000
* (not user defined fields)
*/
public static final String SETTING_ALLOW_UNKNOWN_MSG_FIELDS = "AllowUnknownMsgFields";
public static final String SETTING_DEFAULT_APPL_VER_ID = "DefaultApplVerID";
/**
* Allow to disable heart beat failure detection
*/
public static final String SETTING_DISABLE_HEART_BEAT_CHECK = "DisableHeartBeatCheck";
/**
* Return the last msg seq number processed (optional tag 369). Valid values are "Y" or "N".
* Default is "N".
*/
public static final String SETTING_ENABLE_LAST_MSG_SEQ_NUM_PROCESSED = "EnableLastMsgSeqNumProcessed";
/**
* Return the next expected message sequence number (optional tag 789 on Logon) on sent Logon message
* and use value of tag 789 on received Logon message to synchronize session.
* Valid values are "Y" or "N".
* Default is "N".
* This should not be enabled for FIX versions lower than 4.4
*/
public static final String SETTING_ENABLE_NEXT_EXPECTED_MSG_SEQ_NUM = "EnableNextExpectedMsgSeqNum";
/**
* Reject garbled messages instead of ignoring them.
* This is only working for messages that pass the FIX decoder and reach the engine.
* Messages that cannot be considered a real FIX message (i.e. not starting with
* 8=FIX or not ending with 10=xxx) will be ignored in any case.
* Default is "N".
*/
public static final String SETTING_REJECT_GARBLED_MESSAGE = "RejectGarbledMessage";
public static final String SETTING_REJECT_INVALID_MESSAGE = "RejectInvalidMessage";
public static final String SETTING_REJECT_MESSAGE_ON_UNHANDLED_EXCEPTION = "RejectMessageOnUnhandledException";
public static final String SETTING_REQUIRES_ORIG_SENDING_TIME = "RequiresOrigSendingTime";
public static final String SETTING_FORCE_RESEND_WHEN_CORRUPTED_STORE = "ForceResendWhenCorruptedStore";
public static final String SETTING_ALLOWED_REMOTE_ADDRESSES = "AllowedRemoteAddresses";
/**
* Setting to limit the size of a resend request in case of missing messages.
* This is useful when the remote FIX engine does not allow to ask for more than n message for a ResendRequest
*/
public static final String SETTING_RESEND_REQUEST_CHUNK_SIZE = "ResendRequestChunkSize";
public static final String SETTING_MAX_SCHEDULED_WRITE_REQUESTS = "MaxScheduledWriteRequests";
public static final String SETTING_VALIDATE_CHECKSUM = "ValidateChecksum";
private static final ConcurrentMap<SessionID, Session> sessions = new ConcurrentHashMap<>();
private final Application application;
private final SessionID sessionID;
private final SessionSchedule sessionSchedule;
private final MessageFactory messageFactory;
// @GuardedBy(this)
private final SessionState state;
private boolean enabled;
private final Object responderLock = new Object(); // unique instance
// @GuardedBy(responderLock)
private Responder responder;
// The session time checks were causing performance problems
// so we are checking only once per second.
private long lastSessionTimeCheck = 0;
private int logonAttempts = 0;
private long lastSessionLogon = 0;
private final DataDictionaryProvider dataDictionaryProvider;
private final boolean checkLatency;
private final int maxLatency;
private int resendRequestChunkSize = 0;
private final boolean resetOnLogon;
private final boolean resetOnLogout;
private final boolean resetOnDisconnect;
private final boolean resetOnError;
private final boolean disconnectOnError;
private final UtcTimestampPrecision timestampPrecision;
private final boolean refreshMessageStoreAtLogon;
private final boolean redundantResentRequestsAllowed;
private final boolean persistMessages;
private final boolean checkCompID;
private final boolean useClosedRangeForResend;
private boolean disableHeartBeatCheck = false;
private boolean rejectGarbledMessage = false;
private boolean rejectInvalidMessage = false;
private boolean rejectMessageOnUnhandledException = false;
private boolean requiresOrigSendingTime = false;
private boolean forceResendWhenCorruptedStore = false;
private boolean enableNextExpectedMsgSeqNum = false;
private boolean enableLastMsgSeqNumProcessed = false;
private boolean validateChecksum = true;
private int maxScheduledWriteRequests = 0;
private final AtomicBoolean isResetting = new AtomicBoolean();
private final AtomicBoolean isResettingState = new AtomicBoolean();
private final ListenerSupport stateListeners = new ListenerSupport(SessionStateListener.class);
private final SessionStateListener stateListener = (SessionStateListener) stateListeners
.getMulticaster();
private final AtomicReference<ApplVerID> targetDefaultApplVerID = new AtomicReference<>();
private final DefaultApplVerID senderDefaultApplVerID;
private boolean validateSequenceNumbers = true;
private boolean validateIncomingMessage = true;
private final int[] logonIntervals;
private final Set<InetAddress> allowedRemoteAddresses;
public static final int DEFAULT_MAX_LATENCY = 120;
public static final int DEFAULT_RESEND_RANGE_CHUNK_SIZE = 0; // no resend range
public static final double DEFAULT_TEST_REQUEST_DELAY_MULTIPLIER = 0.5;
private static final String ENCOUNTERED_END_OF_STREAM = "Encountered END_OF_STREAM";
private static final int BAD_COMPID_REJ_REASON = SessionRejectReason.COMPID_PROBLEM;
private static final String BAD_COMPID_TEXT = new FieldException(BAD_COMPID_REJ_REASON).getMessage();
private static final int BAD_TIME_REJ_REASON = SessionRejectReason.SENDINGTIME_ACCURACY_PROBLEM;
private static final String BAD_ORIG_TIME_TEXT = new FieldException(BAD_TIME_REJ_REASON, OrigSendingTime.FIELD).getMessage();
private static final String BAD_TIME_TEXT = new FieldException(BAD_TIME_REJ_REASON, SendingTime.FIELD).getMessage();
protected static final Logger LOG = LoggerFactory.getLogger(Session.class);
Session(Application application, MessageStoreFactory messageStoreFactory, SessionID sessionID,
DataDictionaryProvider dataDictionaryProvider, SessionSchedule sessionSchedule,
LogFactory logFactory, MessageFactory messageFactory, int heartbeatInterval) {
this(application, messageStoreFactory, sessionID, dataDictionaryProvider, sessionSchedule,
logFactory, messageFactory, heartbeatInterval, true, DEFAULT_MAX_LATENCY, UtcTimestampPrecision.MILLIS,
false, false, false, false, true, false, true, false,
DEFAULT_TEST_REQUEST_DELAY_MULTIPLIER, null, true, new int[] { 5 }, false, false,
false, false, true, false, true, false, null, true, DEFAULT_RESEND_RANGE_CHUNK_SIZE, false, false, false);
}
Session(Application application, MessageStoreFactory messageStoreFactory, SessionID sessionID,
DataDictionaryProvider dataDictionaryProvider, SessionSchedule sessionSchedule,
LogFactory logFactory, MessageFactory messageFactory, int heartbeatInterval,
boolean checkLatency, int maxLatency, UtcTimestampPrecision timestampPrecision,
boolean resetOnLogon, boolean resetOnLogout, boolean resetOnDisconnect,
boolean refreshMessageStoreAtLogon, boolean checkCompID,
boolean redundantResentRequestsAllowed, boolean persistMessages,
boolean useClosedRangeForResend, double testRequestDelayMultiplier,
DefaultApplVerID senderDefaultApplVerID, boolean validateSequenceNumbers,
int[] logonIntervals, boolean resetOnError, boolean disconnectOnError,
boolean disableHeartBeatCheck, boolean rejectGarbledMessage, boolean rejectInvalidMessage,
boolean rejectMessageOnUnhandledException, boolean requiresOrigSendingTime,
boolean forceResendWhenCorruptedStore, Set<InetAddress> allowedRemoteAddresses,
boolean validateIncomingMessage, int resendRequestChunkSize,
boolean enableNextExpectedMsgSeqNum, boolean enableLastMsgSeqNumProcessed,
boolean validateChecksum) {
this.application = application;
this.sessionID = sessionID;
this.sessionSchedule = sessionSchedule;
this.checkLatency = checkLatency;
this.maxLatency = maxLatency;
this.resetOnLogon = resetOnLogon;
this.resetOnLogout = resetOnLogout;
this.resetOnDisconnect = resetOnDisconnect;
this.timestampPrecision = timestampPrecision;
this.refreshMessageStoreAtLogon = refreshMessageStoreAtLogon;
this.dataDictionaryProvider = dataDictionaryProvider;
this.messageFactory = messageFactory;
this.checkCompID = checkCompID;
this.redundantResentRequestsAllowed = redundantResentRequestsAllowed;
this.persistMessages = persistMessages;
this.useClosedRangeForResend = useClosedRangeForResend;
this.senderDefaultApplVerID = senderDefaultApplVerID;
this.logonIntervals = logonIntervals;
this.resetOnError = resetOnError;
this.disconnectOnError = disconnectOnError;
this.disableHeartBeatCheck = disableHeartBeatCheck;
this.rejectGarbledMessage = rejectGarbledMessage;
this.rejectInvalidMessage = rejectInvalidMessage;
this.rejectMessageOnUnhandledException = rejectMessageOnUnhandledException;
this.requiresOrigSendingTime = requiresOrigSendingTime;
this.forceResendWhenCorruptedStore = forceResendWhenCorruptedStore;
this.allowedRemoteAddresses = allowedRemoteAddresses;
this.validateIncomingMessage = validateIncomingMessage;
this.validateSequenceNumbers = validateSequenceNumbers;
this.resendRequestChunkSize = resendRequestChunkSize;
this.enableNextExpectedMsgSeqNum = enableNextExpectedMsgSeqNum;
this.enableLastMsgSeqNumProcessed = enableLastMsgSeqNumProcessed;
this.validateChecksum = validateChecksum;
final Log engineLog = (logFactory != null) ? logFactory.create(sessionID) : null;
if (engineLog instanceof SessionStateListener) {
addStateListener((SessionStateListener) engineLog);
}
final MessageStore messageStore = messageStoreFactory.create(sessionID);
if (messageStore instanceof SessionStateListener) {
addStateListener((SessionStateListener) messageStore);
}
state = new SessionState(this, engineLog, heartbeatInterval, heartbeatInterval != 0,
messageStore, testRequestDelayMultiplier);
registerSession(this);
getLog().onEvent("Session " + sessionID + " schedule is " + sessionSchedule);
try {
resetIfSessionNotCurrent(sessionID, SystemTime.currentTimeMillis());
} catch (final IOException e) {
LogUtil.logThrowable(getLog(), "error during session construction", e);
}
// QFJ-721: for non-FIXT sessions we do not need to set targetDefaultApplVerID from Logon
if (!sessionID.isFIXT()) {
targetDefaultApplVerID.set(MessageUtils.toApplVerID(sessionID.getBeginString()));
}
setEnabled(true);
getLog().onEvent("Created session: " + sessionID);
}
public MessageFactory getMessageFactory() {
return messageFactory;
}
/**
* Registers a responder with the session. This is used by the acceptor and
* initiator implementations.
*
* @param responder a responder implementation
*/
public void setResponder(Responder responder) {
synchronized (responderLock) {
this.responder = responder;
if (responder != null) {
stateListener.onConnect();
} else {
stateListener.onDisconnect();
}
}
}
public Responder getResponder() {
synchronized (responderLock) {
return responder;
}
}
/**
* This should not be used by end users.
*
* @return the Session's connection responder
*/
public boolean hasResponder() {
return getResponder() != null;
}
/**
* Provides remote address of the session connection, if any.
*
* @return remote address (host:port) if connected, null if not.
*/
public String getRemoteAddress() {
Responder responder = getResponder();
if (responder != null) {
return responder.getRemoteAddress();
}
return null;
}
private boolean isCurrentSession(final long time)
throws IOException {
return sessionSchedule == null || sessionSchedule.isSameSession(
SystemTime.getUtcCalendar(time), state.getCreationTimeCalendar());
}
/**
* Send a message to the session specified in the message's target
* identifiers.
*
* @param message a FIX message
* @return true is send was successful, false otherwise
* @throws SessionNotFound if session could not be located
*/
public static boolean sendToTarget(Message message) throws SessionNotFound {
return sendToTarget(message, "");
}
/**
* Send a message to the session specified in the message's target
* identifiers. The session qualifier is used to distinguish sessions with
* the same target identifiers.
*
* @param message a FIX message
* @param qualifier a session qualifier
* @return true is send was successful, false otherwise
* @throws SessionNotFound if session could not be located
*/
public static boolean sendToTarget(Message message, String qualifier) throws SessionNotFound {
try {
final String senderCompID = getSenderCompIDFromMessage(message);
final String targetCompID = getTargetCompIDFromMessage(message);
return sendToTarget(message, senderCompID, targetCompID, qualifier);
} catch (final FieldNotFound e) {
throw new SessionNotFound("missing sender or target company ID");
}
}
private static String getTargetCompIDFromMessage(final Message message) throws FieldNotFound {
return message.getHeader().getString(TargetCompID.FIELD);
}
private static String getSenderCompIDFromMessage(final Message message) throws FieldNotFound {
return message.getHeader().getString(SenderCompID.FIELD);
}
/**
* Send a message to the session specified by the provided target company
* ID. The sender company ID is provided as an argument rather than from the
* message.
*
* @param message a FIX message
* @param senderCompID the sender's company ID
* @param targetCompID the target's company ID
* @return true is send was successful, false otherwise
* @throws SessionNotFound if session could not be located
*/
public static boolean sendToTarget(Message message, String senderCompID, String targetCompID)
throws SessionNotFound {
return sendToTarget(message, senderCompID, targetCompID, "");
}
/**
* Send a message to the session specified by the provided target company
* ID. The sender company ID is provided as an argument rather than from the
* message. The session qualifier is used to distinguish sessions with the
* same target identifiers.
*
* @param message a FIX message
* @param senderCompID the sender's company ID
* @param targetCompID the target's company ID
* @param qualifier a session qualifier
* @return true is send was successful, false otherwise
* @throws SessionNotFound if session could not be located
*/
public static boolean sendToTarget(Message message, String senderCompID, String targetCompID,
String qualifier) throws SessionNotFound {
try {
return sendToTarget(message,
new SessionID(message.getHeader().getString(BeginString.FIELD), senderCompID,
targetCompID, qualifier));
} catch (final SessionNotFound e) {
throw e;
} catch (final Exception e) {
throw new SessionException(e);
}
}
/**
* Send a message to the session specified by the provided session ID.
*
* @param message a FIX message
* @param sessionID the target SessionID
* @return true is send was successful, false otherwise
* @throws SessionNotFound if session could not be located
*/
public static boolean sendToTarget(Message message, SessionID sessionID) throws SessionNotFound {
final Session session = lookupSession(sessionID);
if (session == null) {
throw new SessionNotFound();
}
message.setSessionID(sessionID);
return session.send(message);
}
static void registerSession(Session session) {
sessions.put(session.getSessionID(), session);
}
static void unregisterSessions(List<SessionID> sessionIds, boolean doClose) {
for (final SessionID sessionId : sessionIds) {
unregisterSession(sessionId, doClose);
}
}
static void unregisterSession(SessionID sessionId, boolean doClose) {
final Session session = sessions.get(sessionId);
if (session != null) {
try {
if (doClose) {
session.close();
}
} catch (final IOException e) {
LOG.error("Failed to close session resources", e);
} finally {
sessions.remove(sessionId);
}
}
}
/**
* Locates a session specified by the provided session ID.
*
* @param sessionID the session ID
* @return the session, if found, or null otherwise
*/
public static Session lookupSession(SessionID sessionID) {
return sessions.get(sessionID);
}
/**
* This method can be used to manually logon to a FIX session.
*/
public void logon() {
state.clearLogoutReason();
setEnabled(true);
}
private synchronized void setEnabled(boolean enabled) {
this.enabled = enabled;
}
private void initializeHeader(Message.Header header) {
state.setLastSentTime(SystemTime.currentTimeMillis());
header.setString(BeginString.FIELD, sessionID.getBeginString());
header.setString(SenderCompID.FIELD, sessionID.getSenderCompID());
optionallySetID(header, SenderSubID.FIELD, sessionID.getSenderSubID());
optionallySetID(header, SenderLocationID.FIELD, sessionID.getSenderLocationID());
header.setString(TargetCompID.FIELD, sessionID.getTargetCompID());
optionallySetID(header, TargetSubID.FIELD, sessionID.getTargetSubID());
optionallySetID(header, TargetLocationID.FIELD, sessionID.getTargetLocationID());
header.setInt(MsgSeqNum.FIELD, getExpectedSenderNum());
insertSendingTime(header);
}
private void optionallySetID(Header header, int field, String value) {
if (!value.equals(SessionID.NOT_SET)) {
header.setString(field, value);
}
}
private void insertSendingTime(Message.Header header) {
header.setUtcTimeStamp(SendingTime.FIELD, SystemTime.getLocalDateTime(), getTimestampPrecision());
}
private UtcTimestampPrecision getTimestampPrecision() {
if (sessionID.getBeginString().compareTo(FixVersions.BEGINSTRING_FIX42) >= 0) {
return timestampPrecision;
} else {
return UtcTimestampPrecision.SECONDS;
}
}
/**
* This method can be used to manually logout of a FIX session.
*/
public void logout() {
setEnabled(false);
}
/**
* This method can be used to manually logout of a FIX session.
*
* @param reason this will be included in the logout message
*/
public void logout(String reason) {
state.setLogoutReason(reason);
logout();
}
/**
* Used internally
*
* @return true if session is enabled, false otherwise.
*/
public synchronized boolean isEnabled() {
return enabled;
}
/**
* Predicate indicating whether a logon message has been sent.
*
* (QF Compatibility)
*
* @return true if logon message was sent, false otherwise.
*/
public boolean sentLogon() {
return state.isLogonSent();
}
/**
* Predicate indicating whether a logon message has been received.
*
* (QF Compatibility)
*
* @return true if logon message was received, false otherwise.
*/
public boolean receivedLogon() {
return state.isLogonReceived();
}
/**
* Predicate indicating whether a logout message has been sent.
*
* (QF Compatibility)
*
* @return true if logout message was sent, false otherwise.
*/
public boolean sentLogout() {
return state.isLogoutSent();
}
/**
* Predicate indicating whether a logout message has been received. This can
* be used to determine if a session ended with an unexpected disconnect.
*
* @return true if logout message has been received, false otherwise.
*/
public boolean receivedLogout() {
return state.isLogoutReceived();
}
/**
* Is the session logged on.
*
* @return true if logged on, false otherwise.
*/
public boolean isLoggedOn() {
return sentLogon() && receivedLogon();
}
private boolean isResetNeeded() {
return sessionID.getBeginString().compareTo(FixVersions.BEGINSTRING_FIX41) >= 0
&& (resetOnLogon || resetOnLogout || resetOnDisconnect)
&& getExpectedSenderNum() == 1 && getExpectedTargetNum() == 1;
}
/**
* Logs out and disconnects session (if logged on) and then resets session state.
*
* @throws IOException IO error
* @see SessionState#reset()
*/
public void reset() throws IOException {
if (!isResetting.compareAndSet(false, true)) {
return;
}
try {
if (hasResponder() && isLoggedOn()) {
if (application instanceof ApplicationExtended) {
((ApplicationExtended) application).onBeforeSessionReset(sessionID);
}
generateLogout();
disconnect("Session reset", false);
}
resetState();
} finally {
isResetting.set(false);
}
}
/**
* Set the next outgoing message sequence number. This method is not
* synchronized.
*
* @param num next outgoing sequence number
* @throws IOException IO error
*/
public void setNextSenderMsgSeqNum(int num) throws IOException {
state.getMessageStore().setNextSenderMsgSeqNum(num);
}
/**
* Set the next expected target message sequence number. This method is not
* synchronized.
*
* @param num next expected target sequence number
* @throws IOException IO error
*/
public void setNextTargetMsgSeqNum(int num) throws IOException {
state.getMessageStore().setNextTargetMsgSeqNum(num);
}
/**
* Retrieves the expected sender sequence number. This method is not
* synchronized.
*
* @return next expected sender sequence number
*/
public int getExpectedSenderNum() {
try {
return state.getMessageStore().getNextSenderMsgSeqNum();
} catch (final IOException e) {
getLog().onErrorEvent("getNextSenderMsgSeqNum failed: " + e.getMessage());
return -1;
}
}
/**
* Retrieves the expected target sequence number. This method is not
* synchronized.
*
* @return next expected target sequence number
*/
public int getExpectedTargetNum() {
try {
return state.getMessageStore().getNextTargetMsgSeqNum();
} catch (final IOException e) {
getLog().onErrorEvent("getNextTargetMsgSeqNum failed: " + e.getMessage());
return -1;
}
}
public Log getLog() {
return state.getLog();
}
/**
* Get the message store. (QF Compatibility)
*
* @return the message store
*/
public MessageStore getStore() {
return state.getMessageStore();
}
private void next(Message message, boolean isProcessingQueuedMessages) throws FieldNotFound, RejectLogon, IncorrectDataFormat,
IncorrectTagValue, UnsupportedMessageType, IOException, InvalidMessage {
if (message == EventHandlingStrategy.END_OF_STREAM) {
disconnect(ENCOUNTERED_END_OF_STREAM, false);
return;
}
final Header header = message.getHeader();
final String msgType = header.getString(MsgType.FIELD);
// QFJ-650
if (!header.isSetField(MsgSeqNum.FIELD)) {
generateLogout("Received message without MsgSeqNum");
disconnect("Received message without MsgSeqNum: " + getMessageToLog(message), true);
return;
}
final String sessionBeginString = sessionID.getBeginString();
try {
final String beginString = header.getString(BeginString.FIELD);
if (!beginString.equals(sessionBeginString)) {
throw new UnsupportedVersion("Message version '" + beginString
+ "' does not match the session version '" + sessionBeginString + "'");
}
if (MsgType.LOGON.equals(msgType)) {
if (sessionID.isFIXT()) {
targetDefaultApplVerID.set(new ApplVerID(message
.getString(DefaultApplVerID.FIELD)));
}
// QFJ-648
if (message.isSetField(HeartBtInt.FIELD)) {
if (message.getInt(HeartBtInt.FIELD) < 0) {
throw new RejectLogon("HeartBtInt must not be negative");
}
}
}
if (validateIncomingMessage && dataDictionaryProvider != null) {
final DataDictionary sessionDataDictionary = dataDictionaryProvider
.getSessionDataDictionary(beginString);
final ApplVerID applVerID = header.isSetField(ApplVerID.FIELD) ? new ApplVerID(
header.getString(ApplVerID.FIELD)) : targetDefaultApplVerID.get();
final DataDictionary applicationDataDictionary = MessageUtils
.isAdminMessage(msgType) ? dataDictionaryProvider
.getSessionDataDictionary(beginString) : dataDictionaryProvider
.getApplicationDataDictionary(applVerID);
// related to QFJ-367 : just warn invalid incoming field/tags
try {
DataDictionary.validate(message, sessionDataDictionary,
applicationDataDictionary);
} catch (final IncorrectTagValue e) {
if (rejectInvalidMessage) {
throw e;
} else {
getLog().onErrorEvent("Warn: incoming message with " + e + ": " + getMessageToLog(message));