Datasets:

ArXiv:
License:
File size: 94,305 Bytes
c574d3a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
package com.thomsonreuters.upa.valueadd.examples.consumer;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.channels.CancelledKeyException;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import com.thomsonreuters.upa.codec.Buffer;
import com.thomsonreuters.upa.codec.Codec;
import com.thomsonreuters.upa.codec.CodecFactory;
import com.thomsonreuters.upa.codec.CodecReturnCodes;
import com.thomsonreuters.upa.codec.DataDictionary;
import com.thomsonreuters.upa.codec.DataStates;
import com.thomsonreuters.upa.codec.DecodeIterator;
import com.thomsonreuters.upa.codec.EncodeIterator;
import com.thomsonreuters.upa.codec.MapEntryActions;
import com.thomsonreuters.upa.codec.Msg;
import com.thomsonreuters.upa.codec.Qos;
import com.thomsonreuters.upa.codec.QosRates;
import com.thomsonreuters.upa.codec.QosTimeliness;
import com.thomsonreuters.upa.codec.StateCodes;
import com.thomsonreuters.upa.codec.StreamStates;
import com.thomsonreuters.upa.rdm.Dictionary;
import com.thomsonreuters.upa.rdm.DomainTypes;
import com.thomsonreuters.upa.rdm.Login;
import com.thomsonreuters.upa.transport.ConnectOptions;
import com.thomsonreuters.upa.transport.ConnectionTypes;
import com.thomsonreuters.upa.transport.Error;
import com.thomsonreuters.upa.transport.TransportFactory;
import com.thomsonreuters.upa.valueadd.cache.CacheFactory;
import com.thomsonreuters.upa.valueadd.cache.PayloadEntry;
import com.thomsonreuters.upa.valueadd.domainrep.rdm.dictionary.DictionaryMsgType;
import com.thomsonreuters.upa.valueadd.domainrep.rdm.dictionary.DictionaryRefresh;
import com.thomsonreuters.upa.valueadd.domainrep.rdm.directory.DirectoryMsgType;
import com.thomsonreuters.upa.valueadd.domainrep.rdm.directory.DirectoryRefresh;
import com.thomsonreuters.upa.valueadd.domainrep.rdm.directory.DirectoryStatus;
import com.thomsonreuters.upa.valueadd.domainrep.rdm.directory.DirectoryUpdate;
import com.thomsonreuters.upa.valueadd.domainrep.rdm.directory.Service;
import com.thomsonreuters.upa.valueadd.domainrep.rdm.login.LoginMsgType;
import com.thomsonreuters.upa.valueadd.domainrep.rdm.login.LoginRefresh;
import com.thomsonreuters.upa.valueadd.domainrep.rdm.login.LoginRequest;
import com.thomsonreuters.upa.valueadd.domainrep.rdm.login.LoginRequestFlags;
import com.thomsonreuters.upa.valueadd.domainrep.rdm.login.LoginStatus;
import com.thomsonreuters.upa.valueadd.examples.common.CacheInfo;
import com.thomsonreuters.upa.valueadd.examples.common.ConnectionArg;
import com.thomsonreuters.upa.valueadd.examples.common.ItemArg;
import com.thomsonreuters.upa.valueadd.examples.consumer.StreamIdWatchList.StreamIdKey;
import com.thomsonreuters.upa.valueadd.examples.consumer.StreamIdWatchList.WatchListEntry;
import com.thomsonreuters.upa.valueadd.reactor.ReactorAuthTokenEvent;
import com.thomsonreuters.upa.valueadd.reactor.ReactorAuthTokenEventCallback;
import com.thomsonreuters.upa.valueadd.reactor.ConsumerCallback;
import com.thomsonreuters.upa.valueadd.reactor.DictionaryDownloadModes;
import com.thomsonreuters.upa.valueadd.reactor.RDMDictionaryMsgEvent;
import com.thomsonreuters.upa.valueadd.reactor.RDMDirectoryMsgEvent;
import com.thomsonreuters.upa.valueadd.reactor.RDMLoginMsgEvent;
import com.thomsonreuters.upa.valueadd.reactor.Reactor;
import com.thomsonreuters.upa.valueadd.reactor.ReactorCallbackReturnCodes;
import com.thomsonreuters.upa.valueadd.reactor.ReactorChannel;
import com.thomsonreuters.upa.valueadd.reactor.ReactorChannelEvent;
import com.thomsonreuters.upa.valueadd.reactor.ReactorChannelEventTypes;
import com.thomsonreuters.upa.valueadd.reactor.ReactorChannelStats;
import com.thomsonreuters.upa.valueadd.reactor.ReactorConnectInfo;
import com.thomsonreuters.upa.valueadd.reactor.ReactorDispatchOptions;
import com.thomsonreuters.upa.valueadd.reactor.ReactorErrorInfo;
import com.thomsonreuters.upa.valueadd.reactor.ReactorFactory;
import com.thomsonreuters.upa.valueadd.reactor.ReactorMsgEvent;
import com.thomsonreuters.upa.valueadd.reactor.ReactorOptions;
import com.thomsonreuters.upa.valueadd.reactor.ReactorReturnCodes;
import com.thomsonreuters.upa.valueadd.reactor.ReactorSubmitOptions;

/**
 * <p>
 * This is a main class to run the UPA Value Add Consumer application.
 * </p>
 * <H2>Summary</H2>
 * <p>
 * The purpose of this application is to demonstrate consuming data from
 * an OMM Provider using Value Add components. It is a single-threaded
 * client application.
 * </p>
 * <p>
 * The consumer application implements callbacks that process information
 * received by the provider. It creates the Reactor, creates the desired
 * connections, then dispatches from the Reactor for events and messages.
 * Once it has received the event indicating that the channel is ready,
 * it will make the desired item requests (snapshot or streaming) to a
 * provider and appropriately processes the responses. The resulting decoded 
 * responses from the provided are displayed on the console.
 * </p>
 * <p>
 * This application supports consuming Level I Market Price, Level II Market By
 * Order, Level II Market By Price and Yield Curve. This application can optionally
 * perform on-stream and off-stream posting for Level I Market Price content. The
 * item name used for an off-stream post is "OFFPOST". For simplicity, the off-stream
 * post item name is not configurable, but users can modify the code if desired.
 * </p>
 * <p>
 * If multiple item requests are specified on the command line for the same domain and
 * the provider supports batch requests, this application will send the item requests
 * as a single Batch request.
 * </p>
 * <p>
 * If supported by the provider and the application requests view use, a dynamic
 * view will be requested with all Level I Market Price requests. For simplicity,
 * this view is not configurable but users can modify the code to change the
 * requested view.  
 * </p>
 * <p>
 * This application supports a symbol list request. The symbol list name is optional.
 * If the user does not provide a symbol list name, the name is taken from the source
 * directory response.
 * </p>
 * <p>
 * This application is intended as a basic usage example. Some of the design choices
 * were made to favor simplicity and readability over performance. This application 
 * is not intended to be used for measuring performance. This application uses
 * Value Add and shows how using Value Add simplifies the writing of UPA
 * applications. Because Value Add is a layer on top of UPA, you may see a
 * slight decrease in performance compared to writing applications directly to
 * the UPA interfaces.
 * </p>
 * <H2>Setup Environment</H2>
 * <p>
 * The RDMFieldDictionary and enumtype.def files could be located in the
 * directory of execution or this application will request dictionary from
 * provider.
 * </p> 
 * <H2>Running the application:</H2>
 * <p>
 * Change directory to the <i>Java</i> directory and issue the following <i>Gradle</i> command.
 * <p>
 * Linux: ./gradlew runVAConsumer -PcommandLineArgs="arguments"<br>
 * Windows: gradlew.bat runVAConsumer -PcommandLineArgs="arguments"<br>
 * <br>
 * Arguments are listed below.
 * </p>
 * <ul>
 * <li>-c specifies a connection to open and a list of items to request:
 * <ul>
 *  <li>hostname:        Hostname of provider to connect to
 *  <li>port:            Port of provider to connect to
 *  <li>service:         Name of service to request items from on this connection
 *  <li>domain:itemName: Domain and name of an item to request
 *       <br>A comma-separated list of these may be specified.
 *       <br>The domain may be any of: mp(MarketPrice), mbo(MarketByOrder), mbp(MarketByPrice), yc(YieldCurve), sl(SymbolList)
 *       <br>The domain may also be any of the private stream domains: mpps(MarketPrice PS), mbops(MarketByOrder PS), mbpps(MarketByPrice PS), ycps(YieldCurve PS)
 *       <br>Example Usage: -c localhost:14002 DIRECT_FEED mp:TRI,mp:GOOG,mpps:FB,mbo:MSFT,mbpps:IBM,sl
 *       <br>&nbsp;&nbsp;(for SymbolList requests, a name can be optionally specified)
 *  <li>-tunnel (optional) enables consumer to open tunnel stream and send basic text messages
 *  <li>-tsServiceName (optional) specifies the service name for tunnel stream messages (if not specified, the service name specified in -c/-tcp is used)"
 *  <li>-tsAuth (optional) specifies that consumer will request authentication when opening the tunnel stream. This applies to basic tunnel streams.
 *  <li>-tsDomain (optional) specifies the domain that consumer will use when opening the tunnel stream. This applies to basic tunnel streams.
 *  </li>
 * </ul>
 * </li>
 * <li>-uname changes the username used when logging into the provider
 *
 * <li>-passwd changes the password used when logging into the provider
 * 
 * <li>-clientId specifies a unique ID for application making the request to EDP token service, also known as AppKey generated using an AppGenerator
 * 
 * <li>-sessionMgnt enables the session management in the Reactor
 *
 * <li>-view specifies each request using a basic dynamic view
 *
 * <li>-post specifies that the application should attempt to send post messages on the first requested Market Price item
 *
 * <li>-offpost specifies that the application should attempt to send post messages on the login stream (i.e., off-stream)
 *
 * <li>-publisherInfo specifies that the application provides its own user id and address
 * 
 * <li>-snapshot specifies each request using non-streaming
 *
 * <li>-x provides an XML trace of messages
 * 
 * <li>-runtime adjusts the running time of the application
 * 
 * <li>-cache will store all open items in cache and periodically dump contents
 *
 * <li>-cacheInterval number of seconds between displaying cache contents, must greater than 0
 *
 * <li>-proxy proxyFlag. if provided, the application will attempt
 * to make an http or encrypted connection through a proxy server (if
 * connectionType is set to http or encrypted).
 *
 * <li>-ph Proxy host name.
 * 
 * <li>-pp Proxy port number.
 * 
 * <li>-plogin User name on proxy server.
 * 
 * <li>-ppasswd Password on proxy server. 
 * 
 * <li>-pdomain Proxy Domain.
 * 
 * <li>-krbfile Proxy KRB file. 
 * 
 * <li>-keyfile keystore file for encryption.
 * 
 * <li>-keypasswd keystore password for encryption.
 * 
 * <li>-at Specifies the Authentication Token. If this is present, the login user name type will be Login.UserIdTypes.AUTHN_TOKEN.
 * 
 * <li>-ax Specifies the Authentication Extended information.
 * 
 * <li>-aid Specifies the Application ID.
 * 
 * </ul>
 */
public class Consumer implements ConsumerCallback, ReactorAuthTokenEventCallback
{
    private final String FIELD_DICTIONARY_FILE_NAME = "RDMFieldDictionary";
    private final String ENUM_TABLE_FILE_NAME = "enumtype.def";
    
    private Reactor reactor;
    private ReactorOptions reactorOptions = ReactorFactory.createReactorOptions();
    private ReactorErrorInfo errorInfo = ReactorFactory.createReactorErrorInfo();
    private ReactorDispatchOptions dispatchOptions = ReactorFactory.createReactorDispatchOptions();
    private ConsumerCmdLineParser consumerCmdLineParser = new ConsumerCmdLineParser();
    private Selector selector;
    
    private long runtime;
    
	ReactorChannelStats reactorChannelStats = ReactorFactory.createReactorChannelStats();
	    
    // default server host name
    private static final String defaultSrvrHostname = "localhost";
    
    // default server port number
    private static final String defaultSrvrPortNo = "14002";
    
    // default service name
    private static final String defaultServiceName = "DIRECT_FEED";
    
    // default item name
    private static final String defaultItemName = "TRI.N";
    
    // default item name 2
    private static final String defaultItemName2 = ".DJI";
    
    private Error error;    // error information
    
    private DataDictionary dictionary;
    
    private boolean fieldDictionaryLoadedFromFile;
	private boolean enumTypeDictionaryLoadedFromFile;
	
	ArrayList<ChannelInfo> chnlInfoList = new ArrayList<ChannelInfo>();

    private TunnelStreamHandler tunnelStreamHandler;
    private String tsServiceName;

	long cacheTime;
	long cacheInterval;
    long statisticTime;
    long statisticInterval;
    //APIQA
    String statisticFilter;
    //END APIQA
	StringBuilder cacheDisplayStr;
	Buffer cacheEntryBuffer;
	
	boolean _finalStatusEvent;
	private long closetime;
	private long closeRunTime; 
	boolean closeHandled;

    private ReactorSubmitOptions submitOptions = ReactorFactory.createReactorSubmitOptions();
	
    public Consumer()
    {
        dictionary = CodecFactory.createDataDictionary();
        
        error = TransportFactory.createError();
        dispatchOptions.maxMessages(1);
        _finalStatusEvent = true;
        closetime = 10; // 10 sec 
        try
        {
            selector = Selector.open();
        }
        catch (Exception e)
        {
        	System.out.println("Selector.open() failed: " + e.getLocalizedMessage());
        	System.exit(ReactorReturnCodes.FAILURE);
        }
    }

    /* Initializes the Value Add consumer application. */
    private void init(String[] args)
    {
        // parse command line
    	if (!consumerCmdLineParser.parseArgs(args))
        {
            System.err.println("\nError loading command line arguments:\n");
            consumerCmdLineParser.printUsage();
            System.exit(CodecReturnCodes.FAILURE);
        }

    	// add default connections to arguments if none specified
        if (consumerCmdLineParser.connectionList().size() == 0 && 
        	!consumerCmdLineParser.enableSessionMgnt())
        {
        	// first connection - localhost:14002 DIRECT_FEED mp:TRI.N
        	List<ItemArg> itemList = new ArrayList<ItemArg>();
        	ItemArg itemArg = new ItemArg(DomainTypes.MARKET_PRICE, defaultItemName, false);
        	itemList.add(itemArg);
        	ConnectionArg connectionArg = new ConnectionArg(ConnectionTypes.SOCKET,
        													defaultServiceName,
        													defaultSrvrHostname,
        													defaultSrvrPortNo,
        													itemList);
        	consumerCmdLineParser.connectionList().add(connectionArg);

        	// second connection - localhost:14002 DIRECT_FEED mp:TRI.N mp:.DJI
        	List<ItemArg> itemList2 = new ArrayList<ItemArg>();
        	ItemArg itemArg2 = new ItemArg(DomainTypes.MARKET_PRICE, defaultItemName2, false);
        	itemList2.add(itemArg);
        	itemList2.add(itemArg2);
        	ConnectionArg connectionArg2 = new ConnectionArg(ConnectionTypes.SOCKET,
        													defaultServiceName,
        													defaultSrvrHostname,
        													defaultSrvrPortNo,
        													itemList2);
        	consumerCmdLineParser.connectionList().add(connectionArg2);
        }

        // display product version information
        System.out.println(Codec.queryVersion().toString());
        System.out.println("Consumer initializing...");

        runtime = System.currentTimeMillis() + consumerCmdLineParser.runtime() * 1000;
        closeRunTime = System.currentTimeMillis() + (consumerCmdLineParser.runtime() + closetime) * 1000;
                
        // load dictionary
        loadDictionary();
        
        // enable Reactor XML tracing if specified
        if (consumerCmdLineParser.enableXmlTracing())
        {
        	reactorOptions.enableXmlTracing();
        }
        
        
        cacheInterval = consumerCmdLineParser.cacheInterval();
        cacheTime = System.currentTimeMillis() + cacheInterval*1000;
        
        statisticInterval = consumerCmdLineParser.statisticInterval();
        statisticTime = System.currentTimeMillis() + statisticInterval*1000;
        
        //APIQA
    	statisticFilter = consumerCmdLineParser.statisticFilter();
    	//END APIQA
        
        // Set reactor statistics to keep track of
        if(statisticInterval > 0)
        {
        	switch(statisticFilter) {
        	case "READ":
        		reactorOptions.statistics(ReactorOptions.StatisticFlags.READ);
        		break;
        	case "WRITE":
        		reactorOptions.statistics(ReactorOptions.StatisticFlags.WRITE);
        		break;
        	case "PING":
        		reactorOptions.statistics(ReactorOptions.StatisticFlags.PING);
        		break;
        	default:
        		reactorOptions.statistics(ReactorOptions.StatisticFlags.READ | ReactorOptions.StatisticFlags.WRITE | ReactorOptions.StatisticFlags.PING);
        	}
        	
        }
        
		// create reactor
	    reactor = ReactorFactory.createReactor(reactorOptions, errorInfo);
	    if (errorInfo.code() != ReactorReturnCodes.SUCCESS)
	    {
        	System.out.println("createReactor() failed: " + errorInfo.toString());
        	System.exit(ReactorReturnCodes.FAILURE);	    	
	    }
	    
        // register selector with reactor's reactorChannel.
        try
        {
			reactor.reactorChannel().selectableChannel().register(selector,
																SelectionKey.OP_READ,
																reactor.reactorChannel());
		}
        catch (ClosedChannelException e)
        {
        	System.out.println("selector register failed: " + e.getLocalizedMessage());
        	System.exit(ReactorReturnCodes.FAILURE);
		}
        
        /* create channel info, initialize channel info, and connect channels
         * for each connection specified */
        //API QA
        int index = 0;
        for (ConnectionArg connectionArg : consumerCmdLineParser.connectionList())
        {
        	// create channel info
        	ChannelInfo chnlInfo = new ChannelInfo();
        	chnlInfo.connectionArg = connectionArg;
        	
        	//APIQA
        	chnlInfo.consumerRole.initDefaultRDMLoginRequest();
        	if (index==0)
        	{
        		// use command line login user name if specified
        		
                if (consumerCmdLineParser.userName() != null && !consumerCmdLineParser.userName().equals(""))
                {
                	LoginRequest loginRequest = chnlInfo.consumerRole.rdmLoginRequest();
                    loginRequest.userName().data(consumerCmdLineParser.userName());
                }
                if (consumerCmdLineParser.passwd() != null)
                {
                	LoginRequest loginRequest = chnlInfo.consumerRole.rdmLoginRequest();
                    loginRequest.password().data(consumerCmdLineParser.passwd());
                    loginRequest.applyHasPassword();
                }
        		index ++;
        	}
        	else
        	{
        		 
        		 if (consumerCmdLineParser.userName2() != null && !consumerCmdLineParser.userName2().equals(""))
                 {
        			 LoginRequest loginRequest = chnlInfo.consumerRole.rdmLoginRequest();
                     loginRequest.userName().data(consumerCmdLineParser.userName2());
                 }
                 if (consumerCmdLineParser.passwd2() != null)
                 {
                	 LoginRequest loginRequest = chnlInfo.consumerRole.rdmLoginRequest();
                     loginRequest.password().data(consumerCmdLineParser.passwd2());
                     loginRequest.applyHasPassword();                    
                  }
        	}
        	//END APIQA
        	// initialize channel info
        	initChannelInfo(chnlInfo);   
	
	        // connect channel
	        int ret;
	        if ((ret = reactor.connect(chnlInfo.connectOptions, chnlInfo.consumerRole, errorInfo)) < ReactorReturnCodes.SUCCESS)
	        {
	        	System.out.println("Reactor.connect failed with return code: " + ret + " error = " + errorInfo.error().text());
	        	System.exit(ReactorReturnCodes.FAILURE);
	        }
	        //APIQA
	        chnlInfo.consumerRole.watchlistOptions().enableWatchlist(true);
	        //END APIQA
	        // add to ChannelInfo list
	        chnlInfoList.add(chnlInfo);
        }
    }

    /* Runs the Value Add consumer application. */
	private void run()		
	{		
		int selectRetVal, selectTime = 1000;
		while (true)
		{
	        Set<SelectionKey> keySet = null;
	        try
	        {
	        	selectRetVal = selector.select(selectTime);
	            if (selectRetVal > 0)
	            {
	                keySet = selector.selectedKeys();
	            }
	        }
	        catch (IOException e)
	        {
	        	System.out.println("select failed: " + e.getLocalizedMessage());
	        	System.exit(ReactorReturnCodes.FAILURE);
	        }
	
	        long currentTime = System.currentTimeMillis();
	        if (currentTime >= cacheTime && cacheInterval > 0)
	        {
	        	cacheTime = System.currentTimeMillis() + cacheInterval*1000;
	        	
	        	for (ChannelInfo chnlInfo : chnlInfoList)
	        	{
	        		if (chnlInfo.cacheInfo.useCache)
	        			displayCache(chnlInfo);
	        	}
	        	
	        	cacheTime = currentTime + cacheInterval*1000;
	        }
	        
	        if (currentTime >= statisticTime && statisticInterval > 0)
	        {
	        	statisticTime = System.currentTimeMillis() + statisticInterval*1000;
	        	
	        	//APIQA
	        	for(int i = 0; i < chnlInfoList.size();i++)
	        	{
	        		ChannelInfo chnlInfo = chnlInfoList.get(i);
	        		
	        		if(reactorOptions.statistics() != 0 && chnlInfo.reactorChannel != null)
	        			displayReactorChannelStats(chnlInfo);
	        	}
	        	//END APIQA
	        	statisticTime = currentTime + statisticInterval*1000;
	        }
	        

	        // nothing to read
	        if (keySet != null)
			{
				Iterator<SelectionKey> iter = keySet.iterator();
				int ret = ReactorReturnCodes.SUCCESS;
				while (iter.hasNext())
				{
					SelectionKey key = iter.next();
					iter.remove();
					try
					{
						if (key.isReadable())
						{
							// retrieve associated reactor channel and dispatch on that channel 
							ReactorChannel reactorChnl = (ReactorChannel)key.attachment();


							// dispatch until no more messages
							while ((ret = reactorChnl.dispatch(dispatchOptions, errorInfo)) > 0) {}
							if (ret == ReactorReturnCodes.FAILURE)
							{
								if (reactorChnl.state() != ReactorChannel.State.CLOSED &&
										reactorChnl.state() != ReactorChannel.State.DOWN_RECONNECTING)
								{
									System.out.println("ReactorChannel dispatch failed: " + ret + "(" + errorInfo.error().text() + ")");
									uninitialize();
									System.exit(ReactorReturnCodes.FAILURE);
								}
							}
						}
					}
					catch (CancelledKeyException e)
					{
					} // key can be canceled during shutdown
				}
			}
	        
	           // Handle run-time
            if (System.currentTimeMillis() >= runtime && !closeHandled)
            {
                System.out.println("Consumer run-time expired, close now...");
                handleClose();
                closeHandled = true;                
            }
            else if (System.currentTimeMillis() >= closeRunTime )
            {
            	 System.out.println("Consumer closetime expired, shutdown reactor.");
            	 break;
            }
	        if (!closeHandled)
	        {
	        	handlePosting();
	        	handleTunnelStream();
	        	
		        // send login reissue if login reissue time has passed
	        	for (ChannelInfo chnlInfo : chnlInfoList)
	        	{
	        		if (chnlInfo.reactorChannel == null ||
	        	    	(chnlInfo.reactorChannel.state() != ReactorChannel.State.UP && 
	        	    	chnlInfo.reactorChannel.state() != ReactorChannel.State.READY))
        	    	{
        	    		continue;
        	    	}
	        		
	        		if (chnlInfo.canSendLoginReissue &&
	        			System.currentTimeMillis() >= chnlInfo.loginReissueTime)
	        		{
						LoginRequest loginRequest = chnlInfo.consumerRole.rdmLoginRequest();
						submitOptions.clear();
						if (chnlInfo.reactorChannel.submit(loginRequest, submitOptions, errorInfo) !=  CodecReturnCodes.SUCCESS)
						{
							System.out.println("Login reissue failed. Error: " + errorInfo.error().text());
						}
						else
						{
							System.out.println("Login reissue sent");
						}
						chnlInfo.canSendLoginReissue = false;
	        		}
	        	}
	        }	        
	        
	        if(closeHandled && tunnelStreamHandler != null && tunnelStreamHandler._chnlInfo != null &&
	           !tunnelStreamHandler._chnlInfo.isTunnelStreamUp) 
	        	break;
		}		
	}

    @Override
	public int reactorAuthTokenEventCallback(ReactorAuthTokenEvent event)
	{
    	if (event.errorInfo().code() != ReactorReturnCodes.SUCCESS)
    	{
    		System.out.println("Retrive an access token failed. Text: " + event.errorInfo().toString());
    	}
    	else
    	{
    		ChannelInfo chnlInfo = (ChannelInfo)event.reactorChannel().userSpecObj();

    		if (chnlInfo.reactorChannel != null)
    		{
    			LoginRequest loginRequest = chnlInfo.consumerRole.rdmLoginRequest();
    			loginRequest.userNameType(Login.UserIdTypes.AUTHN_TOKEN);
    			loginRequest.userName().data(event.reactorAuthTokenInfo().accessToken());
            	// Do not send the password
            	loginRequest.flags(loginRequest.flags() & ~LoginRequestFlags.HAS_PASSWORD);    			
    			loginRequest.applyNoRefresh();
    			
    			submitOptions.clear();

    			if (chnlInfo.reactorChannel.submit(loginRequest, submitOptions, errorInfo) != CodecReturnCodes.SUCCESS)
    			{
    				System.out.println("Login reissue failed. Error: " + errorInfo.error().text());
    			}
    			else
    			{
    				System.out.println("Login reissue sent");
    			}
    		}
    	}
    	return ReactorCallbackReturnCodes.SUCCESS;
	}  	
	
    @Override
	public int reactorChannelEventCallback(ReactorChannelEvent event)
	{
		ChannelInfo chnlInfo = (ChannelInfo)event.reactorChannel().userSpecObj();
		
		switch(event.eventType())
		{
    		case ReactorChannelEventTypes.CHANNEL_UP:
    		{
    			if (event.reactorChannel().selectableChannel() != null)
                    System.out.println("Channel Up Event: " + event.reactorChannel().selectableChannel());
                else
                    System.out.println("Channel Up Event");
    	        // register selector with channel event's reactorChannel
    	        try
    	        {
    				event.reactorChannel().selectableChannel().register(selector,
    																	SelectionKey.OP_READ,
    																	event.reactorChannel());
    			}
    	        catch (ClosedChannelException e)
    	        {
    	        	System.out.println("selector register failed: " + e.getLocalizedMessage());
    	        	return ReactorCallbackReturnCodes.SUCCESS;
    			}
    	        break;
    		}
    		case ReactorChannelEventTypes.FD_CHANGE:
    		{
    	        System.out.println("Channel Change - Old Channel: "
    	                + event.reactorChannel().oldSelectableChannel() + " New Channel: "
    	                + event.reactorChannel().selectableChannel());
    	        
    	        // cancel old reactorChannel select
                SelectionKey key = event.reactorChannel().oldSelectableChannel().keyFor(selector);
                if (key != null)
                    key.cancel();
    
    	        // register selector with channel event's new reactorChannel
    	        try
    	        {
    	        	event.reactorChannel().selectableChannel().register(selector,
    	        													SelectionKey.OP_READ,
    	        													event.reactorChannel());
    	        }
    	        catch (Exception e)
    	        {
    	        	System.out.println("selector register failed: " + e.getLocalizedMessage());
    	        	return ReactorCallbackReturnCodes.SUCCESS;
    	        }
                break;
    		}
    		case ReactorChannelEventTypes.CHANNEL_READY:
    		{
    			// set ReactorChannel on ChannelInfo
    			chnlInfo.reactorChannel = event.reactorChannel();
    			if (event.reactorChannel().selectableChannel() != null)
                    System.out.println("Channel Ready Event: " + event.reactorChannel().selectableChannel());
                else
                    System.out.println("Channel Ready Event");
    			
    			if (isRequestedServiceUp(chnlInfo))
    			{
        			checkAndInitPostingSupport(chnlInfo);
        			
        			if ( !chnlInfo.itemWatchList.isEmpty() )
        			{
        				chnlInfo.itemWatchList.clear();
        				if (chnlInfo.cacheInfo.cache != null)
        					chnlInfo.cacheInfo.cache.clear();
        			}
        			
        			sendMPRequests(chnlInfo);
        			sendMBORequests(chnlInfo);
        			sendMBPRequests(chnlInfo);
        			sendSymbolListRequests(chnlInfo);
        			sendYieldCurveRequests(chnlInfo);
        			chnlInfo.requestsSent = true;
    			}
    			
    			if (isRequestedTunnelStreamServiceUp(chnlInfo))
    			{
                    if (tunnelStreamHandler != null)
                    {
                        if (tunnelStreamHandler.openStream(chnlInfo, errorInfo) != ReactorReturnCodes.SUCCESS)
                        {
                            if (chnlInfo.reactorChannel.state() != ReactorChannel.State.CLOSED &&
                                chnlInfo.reactorChannel.state() != ReactorChannel.State.DOWN_RECONNECTING)
                            {
                                uninitialize();
                                System.exit(ReactorReturnCodes.FAILURE);
                            }
                        }
                    }
    			}
                break;
    		}
    		case ReactorChannelEventTypes.CHANNEL_DOWN_RECONNECTING:
    		{
    			if (event.reactorChannel().selectableChannel() != null)
    				System.out.println("\nConnection down reconnecting: Channel " + event.reactorChannel().selectableChannel());
    			else
    				System.out.println("\nConnection down reconnecting");
    
    			if (event.errorInfo() != null && event.errorInfo().error().text() != null)
    				System.out.println("	Error text: " + event.errorInfo().error().text() + "\n");
    						
    			// allow Reactor to perform connection recovery
    			
                // unregister selectableChannel from Selector
                if (event.reactorChannel().selectableChannel() != null)
                {
                    SelectionKey key = event.reactorChannel().selectableChannel().keyFor(selector);
                    if (key != null)
                        key.cancel();
                }
    			
    			// reset dictionary if not loaded from file
    	        if (fieldDictionaryLoadedFromFile == false &&
    	            enumTypeDictionaryLoadedFromFile == false)
    	        {
    	        	if (chnlInfo.dictionary != null)
    	        	{
    	        		chnlInfo.dictionary.clear();
    	        	}
    	        }
    	        
    	        // reset item request(s) sent flag
    	        chnlInfo.requestsSent = false;
    	        
    	        // reset hasServiceInfo flag
    	        chnlInfo.hasServiceInfo = false;
    	        chnlInfo.hasTunnelStreamServiceInfo = false;
    	        
    	        // reset canSendLoginReissue flag
    	        chnlInfo.canSendLoginReissue = false;
    	        
            	setItemState(chnlInfo, StreamStates.CLOSED_RECOVER, DataStates.SUSPECT, StateCodes.NONE );
            	
                break;
    		}
    		case ReactorChannelEventTypes.CHANNEL_DOWN:
            {
    			if (event.reactorChannel().selectableChannel() != null)
                    System.out.println("\nConnection down: Channel " + event.reactorChannel().selectableChannel());
                else
                    System.out.println("\nConnection down");
    
                if (event.errorInfo() != null && event.errorInfo().error().text() != null)
                    System.out.println("    Error text: " + event.errorInfo().error().text() + "\n");
                
                // unregister selectableChannel from Selector
                if (event.reactorChannel().selectableChannel() != null)
                {
                    SelectionKey key = event.reactorChannel().selectableChannel().keyFor(selector);
                    if (key != null)
                        key.cancel();
                }

                // close ReactorChannel
                if (chnlInfo.reactorChannel != null)
                {
                    chnlInfo.reactorChannel.close(errorInfo);
                }
                break;
            }
            case ReactorChannelEventTypes.WARNING:
                System.out.println("Received ReactorChannel WARNING event\n");
                break;
            default:
            {
                System.out.println("Unknown channel event!\n");
                return ReactorCallbackReturnCodes.SUCCESS;
            }
		}

		return ReactorCallbackReturnCodes.SUCCESS;
	}

	@Override
	public int defaultMsgCallback(ReactorMsgEvent event)
	{
		ChannelInfo chnlInfo = (ChannelInfo)event.reactorChannel().userSpecObj();
		Msg msg = event.msg();
		
        if (msg == null)
        {
            /* The message is not present because an error occurred while decoding it. Print 
             * the error and close the channel. If desired, the un-decoded message buffer
             * is available in event.transportBuffer(). */
            System.out.printf("defaultMsgCallback: %s(%s)\n", event.errorInfo().error().text(), event.errorInfo().location());
            // unregister selectableChannel from Selector
            if (event.reactorChannel().selectableChannel() != null)
            {
                SelectionKey key = event.reactorChannel().selectableChannel().keyFor(selector);
                if (key != null)
                    key.cancel();
            }

            // close ReactorChannel
            if (chnlInfo.reactorChannel != null)
            {
                chnlInfo.reactorChannel.close(errorInfo);
            }
            return ReactorCallbackReturnCodes.SUCCESS;
        }

        // set response message
        chnlInfo.responseMsg = msg;
        
        // set-up decode iterator if message has message body
        if (msg.encodedDataBody() != null && msg.encodedDataBody().data() != null)
        {
            // clear decode iterator
    		chnlInfo.dIter.clear();
    
            // set buffer and version info
    		chnlInfo.dIter.setBufferAndRWFVersion(msg.encodedDataBody(),
    											event.reactorChannel().majorVersion(),
    											event.reactorChannel().minorVersion());
        }

        processResponse(chnlInfo);
        
		return ReactorCallbackReturnCodes.SUCCESS;
	}

	@Override
	public int rdmLoginMsgCallback(RDMLoginMsgEvent event)
	{
		ChannelInfo chnlInfo = (ChannelInfo)event.reactorChannel().userSpecObj();
		LoginMsgType msgType = event.rdmLoginMsg().rdmMsgType();

		switch (msgType)
		{
			case REFRESH:
				System.out.println("Received Login Refresh for Username: " + ((LoginRefresh)event.rdmLoginMsg()).userName());
				System.out.println(event.rdmLoginMsg().toString());
				
				// save loginRefresh
				((LoginRefresh)event.rdmLoginMsg()).copy(chnlInfo.loginRefresh);
					
				// set login stream id in MarketPriceHandler and YieldCurveHandler
				chnlInfo.marketPriceHandler.loginStreamId(event.rdmLoginMsg().streamId());
				chnlInfo.yieldCurveHandler.loginStreamId(event.rdmLoginMsg().streamId());
				
				// get login reissue time from authenticationTTReissue
				if (chnlInfo.loginRefresh.checkHasAuthenticationTTReissue())
				{
					chnlInfo.loginReissueTime = chnlInfo.loginRefresh.authenticationTTReissue() * 1000;
					chnlInfo.canSendLoginReissue = true;
				}
				break;
			case STATUS:
				LoginStatus loginStatus = (LoginStatus)event.rdmLoginMsg();
				System.out.println("Received Login StatusMsg");
				if (loginStatus.checkHasState())
		    	{
					System.out.println("	" + loginStatus.state());
		    	}
				break;
			default:
				System.out.println("Received Unhandled Login Msg Type: " + msgType);
				break;
		}
		
        return ReactorCallbackReturnCodes.SUCCESS;
	}

	@Override
	public int rdmDirectoryMsgCallback(RDMDirectoryMsgEvent event)
	{
		ChannelInfo chnlInfo = (ChannelInfo)event.reactorChannel().userSpecObj();
		DirectoryMsgType msgType = event.rdmDirectoryMsg().rdmMsgType();

		switch (msgType)
		{
			case REFRESH:
				DirectoryRefresh directoryRefresh = (DirectoryRefresh)event.rdmDirectoryMsg();
				processServiceRefresh(directoryRefresh, chnlInfo);
                if (chnlInfo.serviceInfo.action() == MapEntryActions.DELETE)
                {
                    error.text("rdmDirectoryMsgCallback(): DirectoryRefresh Failed: directory service is deleted");
                    return ReactorCallbackReturnCodes.SUCCESS;
                }
				break;
			case UPDATE:
				DirectoryUpdate directoryUpdate = (DirectoryUpdate)event.rdmDirectoryMsg();
                processServiceUpdate(directoryUpdate, chnlInfo);
                if (chnlInfo.serviceInfo.action() == MapEntryActions.DELETE)
                {
                    error.text("rdmDirectoryMsgCallback(): DirectoryUpdate Failed: directory service is deleted");
                    return ReactorCallbackReturnCodes.SUCCESS;
                }
                if (isRequestedServiceUp(chnlInfo) && !chnlInfo.requestsSent)
                {
                    checkAndInitPostingSupport(chnlInfo);
                    
                    if ( !chnlInfo.itemWatchList.isEmpty() )
        			{
        				chnlInfo.itemWatchList.clear();
        				if (chnlInfo.cacheInfo.cache != null)
        					chnlInfo.cacheInfo.cache.clear();
        			}
                    
                    sendMPRequests(chnlInfo);
                    sendMBORequests(chnlInfo);
                    sendMBPRequests(chnlInfo);
                    sendSymbolListRequests(chnlInfo);
                    sendYieldCurveRequests(chnlInfo);
                    chnlInfo.requestsSent = true;
                }
                if (isRequestedTunnelStreamServiceUp(chnlInfo))
                {
                    if ((tunnelStreamHandler != null && tunnelStreamHandler._chnlInfo != null && !tunnelStreamHandler._chnlInfo.isTunnelStreamUp) ||
                    	(tunnelStreamHandler != null && tunnelStreamHandler._chnlInfo == null))
                    {
                        if (tunnelStreamHandler.openStream(chnlInfo, errorInfo) != ReactorReturnCodes.SUCCESS)
                        {
                            if (chnlInfo.reactorChannel.state() != ReactorChannel.State.CLOSED &&
                                chnlInfo.reactorChannel.state() != ReactorChannel.State.DOWN_RECONNECTING)
                            {
                                System.out.println(errorInfo.error().text());
                                uninitialize();
                                System.exit(ReactorReturnCodes.FAILURE);
                            }
                        }
                    }
                }

				break;
			case CLOSE:
				System.out.println("Received Source Directory Close");
				break;
			case STATUS:
				DirectoryStatus directoryStatus = (DirectoryStatus)event.rdmDirectoryMsg();
				System.out.println("\nReceived Source Directory StatusMsg");
				if (directoryStatus.checkHasState())
		    	{
					System.out.println("	" + directoryStatus.state());
		    	}
				break;
			default:
				System.out.println("Received Unhandled Source Directory Msg Type: " + msgType);
		    	break;
		}
		
		return ReactorCallbackReturnCodes.SUCCESS;
	}

    @Override
	public int rdmDictionaryMsgCallback(RDMDictionaryMsgEvent event)
	{
		ChannelInfo chnlInfo = (ChannelInfo)event.reactorChannel().userSpecObj();
		DictionaryMsgType msgType = event.rdmDictionaryMsg().rdmMsgType();
		
		// initialize dictionary
		if (chnlInfo.dictionary == null)
		{
			chnlInfo.dictionary = CodecFactory.createDataDictionary();
		}
		
		switch (msgType)
		{
			case REFRESH:
				DictionaryRefresh dictionaryRefresh = (DictionaryRefresh)event.rdmDictionaryMsg();

				if (dictionaryRefresh.checkHasInfo())
				{
					/* The first part of a dictionary refresh should contain information about its type.
					 * Save this information and use it as subsequent parts arrive. */
					switch(dictionaryRefresh.dictionaryType())
					{
						case Dictionary.Types.FIELD_DEFINITIONS:
							chnlInfo.fieldDictionaryStreamId = dictionaryRefresh.streamId();
							break;
						case Dictionary.Types.ENUM_TABLES:
							chnlInfo.enumDictionaryStreamId = dictionaryRefresh.streamId();
							break;
						default: 
							System.out.println("Unknown dictionary type " + dictionaryRefresh.dictionaryType() + " from message on stream " + dictionaryRefresh.streamId());
							chnlInfo.reactorChannel.close(errorInfo);
							return ReactorCallbackReturnCodes.SUCCESS;
					}
				}

				/* decode dictionary response */

		        // clear decode iterator
				chnlInfo.dIter.clear();

		        // set buffer and version info
				chnlInfo.dIter.setBufferAndRWFVersion(dictionaryRefresh.dataBody(),
													event.reactorChannel().majorVersion(),
													event.reactorChannel().minorVersion());

				System.out.println("Received Dictionary Response: " + dictionaryRefresh.dictionaryName());

				if (dictionaryRefresh.streamId() == chnlInfo.fieldDictionaryStreamId)
				{
					if (chnlInfo.dictionary.decodeFieldDictionary(chnlInfo.dIter, Dictionary.VerbosityValues.VERBOSE, error) == CodecReturnCodes.SUCCESS)
					{
						if (dictionaryRefresh.checkRefreshComplete())
						{
							if (chnlInfo.cacheInfo.useCache)
								initializeCacheDictionary(chnlInfo.cacheInfo,chnlInfo.dictionary);
							
							System.out.println("Field Dictionary complete.");
						}
					}
					else
		    		{
		    			System.out.println("Decoding Field Dictionary failed: " + error.text());
						chnlInfo.reactorChannel.close(errorInfo);
		    		}
				}
				else if (dictionaryRefresh.streamId() == chnlInfo.enumDictionaryStreamId)
				{
					if (chnlInfo.dictionary.decodeEnumTypeDictionary(chnlInfo.dIter, Dictionary.VerbosityValues.VERBOSE, error) == CodecReturnCodes.SUCCESS)
					{
						if (dictionaryRefresh.checkRefreshComplete())
						{
							System.out.println("EnumType Dictionary complete.");
						}
					}
					else
		    		{
		    			System.out.println("Decoding EnumType Dictionary failed: " + error.text());
						chnlInfo.reactorChannel.close(errorInfo);
		    		}
				}
				else
				{
					System.out.println("Received unexpected dictionary message on stream " + dictionaryRefresh.streamId());
				}
				break;
			case STATUS:
				System.out.println("Received Dictionary StatusMsg");
				break;
			default:
				System.out.println("Received Unhandled Dictionary Msg Type: " + msgType);
				break;		
		}
		
		return ReactorCallbackReturnCodes.SUCCESS;
	} 
    
	private void processServiceRefresh(DirectoryRefresh directoryRefresh, ChannelInfo chnlInfo)
	{
        String serviceName = chnlInfo.connectionArg.service();
        System.out.println("Received Source Directory Refresh");
        System.out.println(directoryRefresh.toString());
        for (Service service : directoryRefresh.serviceList())
        {
            if (service.action() == MapEntryActions.DELETE && service.serviceId() == chnlInfo.serviceInfo.serviceId() ) 
            {
                chnlInfo.serviceInfo.action(MapEntryActions.DELETE);
            }
            
            if (service.action() == MapEntryActions.DELETE && service.serviceId() == chnlInfo.tsServiceInfo.serviceId() ) 
            {
                chnlInfo.tsServiceInfo.action(MapEntryActions.DELETE);
            }
            
            if(service.info().serviceName().toString() != null)
            {
                System.out.println("Received serviceName: " + service.info().serviceName() + "\n");
                // cache service requested by the application
                if (service.info().serviceName().toString().equals(serviceName))
                {
                    // save serviceInfo associated with requested service name
                    if (service.copy(chnlInfo.serviceInfo) < CodecReturnCodes.SUCCESS)
                    {
                        System.out.println("Service.copy() failure");
                        uninitialize();
                        System.exit(ReactorReturnCodes.FAILURE);                    
                    }
					chnlInfo.hasServiceInfo = true;
					setItemState(chnlInfo, service.state().status().streamState(), service.state().status().dataState(),
	                		service.state().status().code() );
                }
                if (service.info().serviceName().toString().equals(tsServiceName))
                {
                    // save serviceInfo associated with requested service name
                    if (service.copy(chnlInfo.tsServiceInfo) < CodecReturnCodes.SUCCESS)
                    {
                        System.out.println("Service.copy() failure");
                        uninitialize();
                        System.exit(ReactorReturnCodes.FAILURE);                    
            }
                    
                    chnlInfo.hasTunnelStreamServiceInfo = true;
        }
	}
        }
	}
	
    private void processServiceUpdate(DirectoryUpdate directoryUpdate, ChannelInfo chnlInfo)
    {
        String serviceName = chnlInfo.connectionArg.service();
        String tsServiceName = chnlInfo.connectionArg.tsService();
        System.out.println("Received Source Directory Update");
        System.out.println(directoryUpdate.toString());
        for (Service service : directoryUpdate.serviceList())
        {
            if (service.action() == MapEntryActions.DELETE && service.serviceId() == chnlInfo.serviceInfo.serviceId() ) 
            {
                chnlInfo.serviceInfo.action(MapEntryActions.DELETE);
            }
            
            if (service.action() == MapEntryActions.DELETE && service.serviceId() == chnlInfo.tsServiceInfo.serviceId() ) 
            {
                chnlInfo.tsServiceInfo.action(MapEntryActions.DELETE);
            }
            
            boolean updateServiceInfo = false, updateTSServiceInfo = false;
            if(service.info().serviceName().toString() != null)
            {
                System.out.println("Received serviceName: " + service.info().serviceName() + "\n");
                // update service cache - assume cache is built with previous refresh message
                if (service.info().serviceName().toString().equals(serviceName) ||
                    service.serviceId() == chnlInfo.serviceInfo.serviceId())
                {
                    updateServiceInfo = true;
                }
                if (service.info().serviceName().toString().equals(tsServiceName) ||
                    service.serviceId() == chnlInfo.tsServiceInfo.serviceId())
                {
                	updateTSServiceInfo = true;
            }
            }
            else
            {
            	if (service.serviceId() == chnlInfo.serviceInfo.serviceId())
	            {
	                updateServiceInfo = true;
	            }
                if (service.serviceId() == chnlInfo.tsServiceInfo.serviceId())
	            {
                	updateTSServiceInfo = true;
            }
            }
            
            if (updateServiceInfo)
            {
                // update serviceInfo associated with requested service name
                if (service.copy(chnlInfo.serviceInfo) < CodecReturnCodes.SUCCESS)
                {
                    System.out.println("Service.copy() failure");
                    uninitialize();
                    System.exit(ReactorReturnCodes.FAILURE);                    
                }
                chnlInfo.hasServiceInfo = true;     
                setItemState(chnlInfo, service.state().status().streamState(), service.state().status().dataState(),
                		service.state().status().code() );
            }
            if (updateTSServiceInfo)
            {
                // update serviceInfo associated with requested service name
                if (service.copy(chnlInfo.tsServiceInfo) < CodecReturnCodes.SUCCESS)
                {
                    System.out.println("Service.copy() failure");
                    uninitialize();
                    System.exit(ReactorReturnCodes.FAILURE);                    
        }

                chnlInfo.hasTunnelStreamServiceInfo = true;                
    }
        }
    }
    
    public boolean isRequestedServiceUp(ChannelInfo chnlInfo)
    {
        return  chnlInfo.hasServiceInfo &&
			chnlInfo.serviceInfo.checkHasState() && (!chnlInfo.serviceInfo.state().checkHasAcceptingRequests() ||
                chnlInfo.serviceInfo.state().acceptingRequests() == 1) && chnlInfo.serviceInfo.state().serviceState() == 1;
    }

    public boolean isRequestedTunnelStreamServiceUp(ChannelInfo chnlInfo)
    {
        return  chnlInfo.hasTunnelStreamServiceInfo &&
            chnlInfo.tsServiceInfo.checkHasState() && (!chnlInfo.tsServiceInfo.state().checkHasAcceptingRequests() ||
                chnlInfo.tsServiceInfo.state().acceptingRequests() == 1) && chnlInfo.tsServiceInfo.state().serviceState() == 1;
    }

    private void checkAndInitPostingSupport(ChannelInfo chnlInfo)
    {
        if (!(chnlInfo.shouldOnStreamPost || chnlInfo.shouldOffStreamPost))
            return;

        // set up posting if its enabled 
        
        // ensure that provider supports posting - if not, disable posting
        if (!chnlInfo.loginRefresh.checkHasFeatures() ||
                !chnlInfo.loginRefresh.features().checkHasSupportPost() ||
                chnlInfo.loginRefresh.features().supportOMMPost() == 0)
        {
            // provider does not support posting, disable it
        	chnlInfo.shouldOffStreamPost = false;
        	chnlInfo.shouldOnStreamPost = false;
        	chnlInfo.postHandler.enableOnstreamPost(false);
        	chnlInfo.postHandler.enableOffstreamPost(false);
            System.out.println("Connected Provider does not support OMM Posting.  Disabling Post functionality.");
            return;
        }
        
        if ( consumerCmdLineParser.publisherId() != null && consumerCmdLineParser.publisherAddress() != null)
        	chnlInfo.postHandler.setPublisherInfo(consumerCmdLineParser.publisherId(), consumerCmdLineParser.publisherAddress());

        // This sets up our basic timing so post messages will be sent
        // periodically
        chnlInfo.postHandler.initPostHandler();
    }
	
    // on and off stream posting if enabled
    private void handlePosting()
    {
    	for (ChannelInfo chnlInfo : chnlInfoList)
    	{
	    	if (chnlInfo.loginRefresh == null ||
	    		chnlInfo.serviceInfo == null ||
	    		chnlInfo.reactorChannel == null ||
	    		chnlInfo.reactorChannel.state() != ReactorChannel.State.READY)
	    	{
	    		continue;
	    	}
	    	
	        if (chnlInfo.postHandler.enableOnstreamPost())
	        {
	        	chnlInfo.postItemName.clear();
	            int postStreamId = chnlInfo.marketPriceHandler.getFirstItem(chnlInfo.postItemName);
	            if (postStreamId == 0 || chnlInfo.postItemName.length() == 0)
	            {
	                return;
	            }
	            chnlInfo.postHandler.streamId(postStreamId);
	            chnlInfo.postHandler.serviceId(chnlInfo.serviceInfo.serviceId());
	            chnlInfo.postHandler.dictionary(chnlInfo.dictionary);
	            chnlInfo.postHandler.postItemName().data(chnlInfo.postItemName.data(), chnlInfo.postItemName.position(), chnlInfo.postItemName.length());
	
	            int ret = chnlInfo.postHandler.handlePosts(chnlInfo.reactorChannel, errorInfo);
	            if (ret < CodecReturnCodes.SUCCESS)
	                System.out.println("Error posting onstream: " + error.text());
	        }
	        if (chnlInfo.postHandler.enableOffstreamPost())
	        {
	        	chnlInfo.postHandler.streamId(chnlInfo.loginRefresh.streamId());
	        	chnlInfo.postHandler.postItemName().data("OFFPOST");
	        	chnlInfo.postHandler.serviceId(chnlInfo.serviceInfo.serviceId());
	        	chnlInfo.postHandler.dictionary(chnlInfo.dictionary);
	            int ret = chnlInfo.postHandler.handlePosts(chnlInfo.reactorChannel, errorInfo);
	            if (ret < CodecReturnCodes.SUCCESS)
	                System.out.println("Error posting offstream: " + error.text());
	        }
    	}
    }

    private void handleTunnelStream()
    {
        for (ChannelInfo chnlInfo : chnlInfoList)
        {
            if (chnlInfo.loginRefresh == null ||
                chnlInfo.serviceInfo == null ||
                chnlInfo.reactorChannel == null ||
                chnlInfo.reactorChannel.state() != ReactorChannel.State.READY)
            {
                continue;
            }
            
            if (tunnelStreamHandler != null)
            {
                tunnelStreamHandler.sendMsg(chnlInfo.reactorChannel);                 
            }
        }
    }

    private void processResponse(ChannelInfo chnlInfo)
    {
        switch (chnlInfo.responseMsg.domainType())
        {
            case DomainTypes.MARKET_PRICE:
            	System.out.println("(Channel " + chnlInfo.reactorChannel.selectableChannel() + "):");
                processMarketPriceResp(chnlInfo);
                break;
            case DomainTypes.MARKET_BY_ORDER:
            	System.out.print("(Channel " + chnlInfo.reactorChannel.selectableChannel() + "):");
                processMarketByOrderResp(chnlInfo);
                break;
            case DomainTypes.MARKET_BY_PRICE:
            	System.out.print("(Channel " + chnlInfo.reactorChannel.selectableChannel() + "):");
                processMarketByPriceResp(chnlInfo);
                break;
            case DomainTypes.SYMBOL_LIST:
            	System.out.println("(Channel " + chnlInfo.reactorChannel.selectableChannel() + "):");
                processSymbolListResp(chnlInfo);
                break;
            case DomainTypes.YIELD_CURVE:
            	System.out.println("(Channel " + chnlInfo.reactorChannel.selectableChannel() + "):");
            	processYieldCurveResp(chnlInfo);
                break;
            default:
                System.out.println("Unhandled Domain Type: " + chnlInfo.responseMsg.domainType());
                break;
        }
    }

    private void processSymbolListResp(ChannelInfo chnlInfo)
    {
        if (chnlInfo.symbolListHandler.processResponse(chnlInfo.responseMsg,
        											chnlInfo.dIter,
        											chnlInfo.dictionary) != CodecReturnCodes.SUCCESS)
        {
            System.out.println(errorInfo.error().text());
            uninitialize();
            System.exit(ReactorReturnCodes.FAILURE);
        }
    }

    private void processMarketByPriceResp(ChannelInfo chnlInfo)
    {
        if (chnlInfo.marketByPriceHandler.processResponse(chnlInfo.responseMsg,
        												chnlInfo.dIter,
        												chnlInfo.dictionary,
        												chnlInfo.cacheInfo,
        												errorInfo) != CodecReturnCodes.SUCCESS)
        {
            System.out.println(errorInfo.error().text());
            uninitialize();
            System.exit(ReactorReturnCodes.FAILURE);
        }
    }

    private void processMarketByOrderResp(ChannelInfo chnlInfo)
    {
        if (chnlInfo.marketByOrderHandler.processResponse(chnlInfo.responseMsg,
														chnlInfo.dIter,
														chnlInfo.dictionary,
														chnlInfo.cacheInfo,
														errorInfo) != CodecReturnCodes.SUCCESS)
        {
            System.out.println(errorInfo.error().text());
            uninitialize();
            System.exit(ReactorReturnCodes.FAILURE);
        }
    }

    private void processMarketPriceResp(ChannelInfo chnlInfo)
    {
        if (chnlInfo.marketPriceHandler.processResponse(chnlInfo.responseMsg,
														chnlInfo.dIter,
														chnlInfo.dictionary,
														chnlInfo.cacheInfo,
														errorInfo) != CodecReturnCodes.SUCCESS)
        {
            System.out.println(errorInfo.error().text());
            uninitialize();
            System.exit(ReactorReturnCodes.FAILURE);
        }
    }
    
    private void processYieldCurveResp(ChannelInfo chnlInfo)
    {
        if (chnlInfo.yieldCurveHandler.processResponse(chnlInfo.responseMsg,
													chnlInfo.dIter,
													chnlInfo.dictionary,
													chnlInfo.cacheInfo,
													errorInfo) != CodecReturnCodes.SUCCESS)
        {
            System.out.println(errorInfo.error().text());
            uninitialize();
            System.exit(ReactorReturnCodes.FAILURE);
        }
    }
    
    /* Load dictionary from file. */
	void loadDictionary()
    {
        dictionary.clear();
        if (dictionary.loadFieldDictionary(FIELD_DICTIONARY_FILE_NAME, error) < 0)
        {
            System.out.println("Unable to load field dictionary.  Will attempt to download from provider.\n\tText: "
                    + error.text());
        }
        else
        {
            fieldDictionaryLoadedFromFile = true;
        }

        if (dictionary.loadEnumTypeDictionary(ENUM_TABLE_FILE_NAME, error) < 0)
        {
            System.out.println("Unable to load enum dictionary.  Will attempt to download from provider.\n\tText: "
                        + error.text());
        }
        else
        {
            enumTypeDictionaryLoadedFromFile = true;
        }
    }
	
	private void initChannelInfo(ChannelInfo chnlInfo)
	{
        // set up consumer role   
		chnlInfo.consumerRole.defaultMsgCallback(this);
		chnlInfo.consumerRole.channelEventCallback(this);
		chnlInfo.consumerRole.loginMsgCallback(this);
		chnlInfo.consumerRole.directoryMsgCallback(this);
        if (fieldDictionaryLoadedFromFile == false ||
        	enumTypeDictionaryLoadedFromFile == false)
        {
        	chnlInfo.consumerRole.dictionaryMsgCallback(this);
        }

        // initialize consumer role to default
        //APIQA commented out
        //chnlInfo.consumerRole.initDefaultRDMLoginRequest();
        //END APIQA
        chnlInfo.consumerRole.initDefaultRDMDirectoryRequest();
        
        /*APIQA commented out
		// use command line login user name if specified
        if (consumerCmdLineParser.userName() != null && !consumerCmdLineParser.userName().equals(""))
        {
            LoginRequest loginRequest = chnlInfo.consumerRole.rdmLoginRequest();
            loginRequest.userName().data(consumerCmdLineParser.userName());
        }
        if (consumerCmdLineParser.passwd() != null)
        {
            LoginRequest loginRequest = chnlInfo.consumerRole.rdmLoginRequest();
            loginRequest.password().data(consumerCmdLineParser.passwd());
            loginRequest.applyHasPassword();
        }
        //END APIQA */
        if (consumerCmdLineParser.clientId() != null && !consumerCmdLineParser.clientId().equals(""))
        {
        	chnlInfo.consumerRole.clientId().data(consumerCmdLineParser.clientId());
        }
        
        // use command line authentication token and extended authentication information if specified
        if (consumerCmdLineParser.authenticationToken() != null && !consumerCmdLineParser.authenticationToken().equals(""))
        {
            LoginRequest loginRequest = chnlInfo.consumerRole.rdmLoginRequest();
            loginRequest.userNameType(Login.UserIdTypes.AUTHN_TOKEN);
            loginRequest.userName().data(consumerCmdLineParser.authenticationToken());

            if (consumerCmdLineParser.authenticationExtended() != null && !consumerCmdLineParser.authenticationExtended().equals(""))
            {
            	loginRequest.applyHasAuthenticationExtended();
                loginRequest.authenticationExtended().data(consumerCmdLineParser.authenticationExtended());
            }
        }
        
        // use command line application id if specified
        if (consumerCmdLineParser.applicationId() != null && !consumerCmdLineParser.applicationId().equals(""))
        {
            LoginRequest loginRequest = chnlInfo.consumerRole.rdmLoginRequest();
            loginRequest.attrib().applicationId().data(consumerCmdLineParser.applicationId());
        }
        
        // if unable to load from file, enable consumer to download dictionary
        if (fieldDictionaryLoadedFromFile == false ||
            enumTypeDictionaryLoadedFromFile == false)
        {
        	chnlInfo.consumerRole.dictionaryDownloadMode(DictionaryDownloadModes.FIRST_AVAILABLE);
        }

        if (fieldDictionaryLoadedFromFile == true &&
        	enumTypeDictionaryLoadedFromFile == true)
        {
        	chnlInfo.dictionary = dictionary;
        }
        chnlInfo.shouldOffStreamPost = consumerCmdLineParser.enableOffpost();
        // this application requires at least one market price item to be
        // requested for on-stream posting to be performed
        chnlInfo.shouldOnStreamPost = consumerCmdLineParser.enablePost();
        if (chnlInfo.shouldOnStreamPost)
        {
        	boolean mpItemFound = false;
        	if (chnlInfo.connectionArg.itemList() != null)
        	{
	        	for (ItemArg itemArg  : chnlInfo.connectionArg.itemList())
	        	{
	        		if (itemArg.domain() == DomainTypes.MARKET_PRICE)
	        		{
	        			mpItemFound = true;
	        			break;
	        		}
	        	}
        	}
            if (mpItemFound == false)
            {
                System.out.println("\nPosting will not be performed for this channel as no Market Price items were requested");
                chnlInfo.shouldOnStreamPost = false;
            }
        }

                 
        chnlInfo.postHandler.enableOnstreamPost(chnlInfo.shouldOnStreamPost);
        chnlInfo.postHandler.enableOffstreamPost(chnlInfo.shouldOffStreamPost);
        chnlInfo.marketPriceHandler.snapshotRequest(consumerCmdLineParser.enableSnapshot());
        chnlInfo.marketByOrderHandler.snapshotRequest(consumerCmdLineParser.enableSnapshot());
        chnlInfo.marketByPriceHandler.snapshotRequest(consumerCmdLineParser.enableSnapshot());
        chnlInfo.yieldCurveHandler.snapshotRequest(consumerCmdLineParser.enableSnapshot());
        chnlInfo.symbolListHandler.snapshotRequest(consumerCmdLineParser.enableSnapshot());
        chnlInfo.marketPriceHandler.viewRequest(consumerCmdLineParser.enableView());
        // create item lists from those specified on command line
        createItemLists(chnlInfo);
        
        // set up reactor connect options
        chnlInfo.connectOptions.reconnectAttemptLimit(-1); // attempt to recover forever
        chnlInfo.connectOptions.reconnectMinDelay(1000); // 1 second minimum
        chnlInfo.connectOptions.reconnectMaxDelay(60000); // 60 second maximum
        chnlInfo.connectOptions.connectionList().get(0).connectOptions().majorVersion(Codec.majorVersion());
        chnlInfo.connectOptions.connectionList().get(0).connectOptions().minorVersion(Codec.minorVersion());
        chnlInfo.connectOptions.connectionList().get(0).connectOptions().connectionType(chnlInfo.connectionArg.connectionType());
        
        if (consumerCmdLineParser.enableSessionMgnt())
        {
         	chnlInfo.connectOptions.connectionList().get(0).enableSessionManagement(true);
         	// register for authentication callback
         	chnlInfo.connectOptions.connectionList().get(0).reactorAuthTokenEventCallback(this);
        }

        chnlInfo.connectOptions.connectionList().get(0).connectOptions().unifiedNetworkInfo().serviceName(chnlInfo.connectionArg.port());
        chnlInfo.connectOptions.connectionList().get(0).connectOptions().unifiedNetworkInfo().address(chnlInfo.connectionArg.hostname());

        chnlInfo.connectOptions.connectionList().get(0).connectOptions().userSpecObject(chnlInfo);
        chnlInfo.connectOptions.connectionList().get(0).connectOptions().guaranteedOutputBuffers(1000);
        // add backup connection if specified
        if (consumerCmdLineParser.backupHostname() != null && consumerCmdLineParser.backupPort() != null)
        {
        	ReactorConnectInfo connectInfo = ReactorFactory.createReactorConnectInfo();
        	chnlInfo.connectOptions.connectionList().add(connectInfo);
            chnlInfo.connectOptions.connectionList().get(1).connectOptions().majorVersion(Codec.majorVersion());
            chnlInfo.connectOptions.connectionList().get(1).connectOptions().minorVersion(Codec.minorVersion());
            chnlInfo.connectOptions.connectionList().get(1).connectOptions().connectionType(chnlInfo.connectionArg.connectionType());
            chnlInfo.connectOptions.connectionList().get(1).connectOptions().unifiedNetworkInfo().serviceName(consumerCmdLineParser.backupPort());
            chnlInfo.connectOptions.connectionList().get(1).connectOptions().unifiedNetworkInfo().address(consumerCmdLineParser.backupHostname());
            chnlInfo.connectOptions.connectionList().get(1).connectOptions().userSpecObject(chnlInfo);
            chnlInfo.connectOptions.connectionList().get(1).connectOptions().guaranteedOutputBuffers(1000);
            
            if (consumerCmdLineParser.enableSessionMgnt())
            {
             	chnlInfo.connectOptions.connectionList().get(1).enableSessionManagement(true);
             	// register for authentication callback
             	chnlInfo.connectOptions.connectionList().get(1).reactorAuthTokenEventCallback(this);

             	ConnectOptions cOpt = chnlInfo.connectOptions.connectionList().get(1).connectOptions();
             	cOpt.connectionType(ConnectionTypes.ENCRYPTED);
             	cOpt.tunnelingInfo().tunnelingType("encrypted");
             	setEncryptedConfiguration(cOpt);
            }            
        }

        // handler encrypted or http connection 
        chnlInfo.shouldEnableEncrypted = consumerCmdLineParser.enableEncrypted();
        chnlInfo.shouldEnableHttp = consumerCmdLineParser.enableHttp(); 
         
        if (chnlInfo.shouldEnableEncrypted)
        {
        	ConnectOptions cOpt = chnlInfo.connectOptions.connectionList().get(0).connectOptions();
        	cOpt.connectionType(ConnectionTypes.ENCRYPTED);
            cOpt.tunnelingInfo().tunnelingType("encrypted"); 
            setEncryptedConfiguration(cOpt);        	           	        	
        }        
        else if (chnlInfo.shouldEnableHttp)
        {
        	ConnectOptions cOpt = chnlInfo.connectOptions.connectionList().get(0).connectOptions();
            cOpt.connectionType(ConnectionTypes.HTTP);
            cOpt.tunnelingInfo().tunnelingType("http"); 
            setHTTPConfiguration(cOpt);
        } 
        
        // handle basic tunnel stream configuration
        if (chnlInfo.connectionArg.tunnel() && tunnelStreamHandler == null)
        {
            tsServiceName = chnlInfo.connectionArg.tsService();
            tunnelStreamHandler = new TunnelStreamHandler(chnlInfo.connectionArg.tunnelAuth(), chnlInfo.connectionArg.tunnelDomain());
        }

        if (consumerCmdLineParser.cacheOption())
        {
        	initializeCache(chnlInfo.cacheInfo);
        	if (chnlInfo.dictionary != null)
        		initializeCacheDictionary(chnlInfo.cacheInfo, chnlInfo.dictionary);
        	
        	if (cacheDisplayStr == null)
        	{
        		cacheDisplayStr = new StringBuilder();
        		cacheEntryBuffer = CodecFactory.createBuffer();
        		cacheEntryBuffer.data(ByteBuffer.allocate(6144)); 
        	}
        }
	}
	
	/*
     * initializeCache
     */
    private void initializeCache(CacheInfo cacheInfo)
    {
    	cacheInfo.useCache = true;
    	cacheInfo.cacheOptions.maxItems(10000);
    	cacheInfo.cacheDictionaryKey.data("cacheDictionary1");
    	
    	cacheInfo.cache = CacheFactory.createPayloadCache(cacheInfo.cacheOptions, cacheInfo.cacheError);
    	if (cacheInfo.cache == null)
    	{
			System.out.println("Error: Failed to create cache. Error (" + cacheInfo.cacheError.errorId() + 
						") : " + cacheInfo.cacheError.text());
			cacheInfo.useCache = false;
		}
    	
    	cacheInfo.cursor = CacheFactory.createPayloadCursor();
    	if (cacheInfo.cursor == null)
    	{
			System.out.println("Error: Failed to create cache entry cursor.");
			cacheInfo.useCache = false;
		}
    }
    
    /*
     * unintializeCache
     */
    private void uninitializeCache(CacheInfo cacheInfo)
    {
    	if (cacheInfo.cache != null)
    		cacheInfo.cache.destroy();
    	cacheInfo.cache = null;

    	if (cacheInfo.cursor != null)
    		cacheInfo.cursor.destroy();
    	cacheInfo.cursor = null;
    }
    
    /*
     * initalizeCacheDictionary
     */
    private void initializeCacheDictionary(CacheInfo cacheInfo, DataDictionary dictionary)
    {
    	if (dictionary != null)
		{
    		if ( cacheInfo.cache.setDictionary(dictionary,	cacheInfo.cacheDictionaryKey.toString(),
    										cacheInfo.cacheError) != CodecReturnCodes.SUCCESS )
    		{
    			System.out.println("Error: Failed to bind RDM Field dictionary to cache. Error (" + cacheInfo.cacheError.errorId() + 
						") : " + cacheInfo.cacheError.text());
				cacheInfo.useCache = false;
    		}
		}
		else
		{
			System.out.println("Error: No RDM Field dictionary for cache.\n");
			cacheInfo.useCache = false;
		}
    }
    
    private void displayCache(ChannelInfo chnlInfo)
    {
    	System.out.println("\nStarting Cache Display ");

    	if (chnlInfo.reactorChannel.channel() != null)
    	{
    		cacheDisplayStr.setLength(0);
    		cacheDisplayStr.append("Channel :");
    		cacheDisplayStr.append(chnlInfo.reactorChannel.channel().selectableChannel());
    		System.out.println(cacheDisplayStr.toString());
    	}
    	
    	if (chnlInfo.dictionary == null)
    	{
    		System.out.println("\tDictionary for decoding cache entries is not available\n");
    		return;
    	}

    	if (chnlInfo.cacheInfo.cache != null)
    	{
    		cacheDisplayStr.setLength(0);
    		cacheDisplayStr.append("Total Items in Cache: ");
    		cacheDisplayStr.append(chnlInfo.cacheInfo.cache.entryCount());
    		cacheDisplayStr.append("\n");
    		System.out.println(cacheDisplayStr.toString());
    	}

    	displayCacheDomain(chnlInfo, DomainTypes.MARKET_PRICE, false);
    	displayCacheDomain(chnlInfo, DomainTypes.MARKET_PRICE, true);

    	displayCacheDomain(chnlInfo, DomainTypes.MARKET_BY_ORDER, false);
    	displayCacheDomain(chnlInfo, DomainTypes.MARKET_BY_ORDER, true);

    	displayCacheDomain(chnlInfo, DomainTypes.MARKET_BY_PRICE, false);
    	displayCacheDomain(chnlInfo, DomainTypes.MARKET_BY_PRICE, true);

    	displayCacheDomain(chnlInfo, DomainTypes.YIELD_CURVE, false);
    	displayCacheDomain(chnlInfo, DomainTypes.YIELD_CURVE, true);

    	System.out.println("Cache Display Complete\n");
    }

    private void displayCacheDomain(ChannelInfo chnlInfo, int domainType, boolean isPrivateStream)
    {
		Iterator<Map.Entry<StreamIdKey, WatchListEntry>> iter = chnlInfo.itemWatchList.iterator();
	    while (iter.hasNext())
	    {
	        WatchListEntry entry = iter.next().getValue();
		
			if (entry.cacheEntry != null && entry.domainType == domainType && entry.isPrivateStream == isPrivateStream)
			{
				cacheDisplayStr.setLength(0);
				cacheDisplayStr.append("ItemName: ");
				cacheDisplayStr.append(entry.itemName);
		    	cacheDisplayStr.append("\n");
		    	cacheDisplayStr.append("Domain:\t");
		    	cacheDisplayStr.append(DomainTypes.toString(domainType));
				if (isPrivateStream)
					cacheDisplayStr.append("\tPrivate Stream");
				cacheDisplayStr.append("\n");

		    	cacheDisplayStr.append(entry.itemState.toString());
		    	cacheDisplayStr.append("\n");
		    	System.out.println(cacheDisplayStr.toString());
		    	
		    	int ret = decodeEntryFromCache(chnlInfo, entry.cacheEntry, domainType);
				if (ret != CodecReturnCodes.SUCCESS)
				{
					cacheDisplayStr.setLength(0);
					cacheDisplayStr.append("Error decoding cache content: "); 
		    		cacheDisplayStr.append(ret);		
		    		System.out.println(cacheDisplayStr.toString());
				}
			}
			else if (entry.domainType == domainType && entry.isPrivateStream == isPrivateStream)
			{
				if ( entry.itemState.streamState() == StreamStates.CLOSED )
					continue;

				cacheDisplayStr.setLength(0);
				cacheDisplayStr.append(entry.itemName); 
	    		cacheDisplayStr.append("\tno data in cache\n");		
	    		System.out.println(cacheDisplayStr.toString());
			}
		}
    }
    
    private int decodeEntryFromCache(ChannelInfo chnlInfo, PayloadEntry cacheEntry, int domainType)
    {
    	int ret = CodecReturnCodes.SUCCESS;
    	EncodeIterator eIter = CodecFactory.createEncodeIterator();
    	DecodeIterator dIter = CodecFactory.createDecodeIterator();
    	int majorVersion;
    	int minorVersion;

    	cacheEntryBuffer.data().clear();
    	if (chnlInfo.reactorChannel != null)
    	{
    		majorVersion = chnlInfo.reactorChannel.majorVersion();
    		minorVersion = chnlInfo.reactorChannel.minorVersion();
    	}
    	else
    	{
    		majorVersion =  chnlInfo.connectOptions.connectionList().get(0).connectOptions().majorVersion();
    		minorVersion =  chnlInfo.connectOptions.connectionList().get(0).connectOptions().minorVersion();
    	}

    	eIter.clear();
    	eIter.setBufferAndRWFVersion(cacheEntryBuffer, majorVersion, minorVersion);

    	chnlInfo.cacheInfo.cursor.clear();
    	if ( (ret = cacheEntry.retrieve(eIter, chnlInfo.cacheInfo.cursor, chnlInfo.cacheInfo.cacheError)) != CodecReturnCodes.SUCCESS)
    	{
    		cacheDisplayStr.setLength(0);
	    	cacheDisplayStr.append("Failed retrieving cache entry.\n\tError ");
	    	cacheDisplayStr.append(chnlInfo.cacheInfo.cacheError.errorId());
	    	cacheDisplayStr.append(" : ");
	    	cacheDisplayStr.append(chnlInfo.cacheInfo.cacheError.text());
	    	System.out.println(cacheDisplayStr.toString());
    		return ret;
    	}
    	else
    	{
    		dIter.clear();
    		dIter.setBufferAndRWFVersion(cacheEntryBuffer, majorVersion, minorVersion);
    		cacheDisplayStr.setLength(0);
    		
    		switch (domainType)
    		{
    		case DomainTypes.MARKET_PRICE:
    			ret = chnlInfo.marketPriceHandler.decodePayload(dIter, chnlInfo.dictionary, cacheDisplayStr);
    			break;

    		case DomainTypes.MARKET_BY_ORDER:
    			ret = chnlInfo.marketByOrderHandler.decodePayload(dIter, chnlInfo.dictionary, cacheDisplayStr);
    			break;

    		case DomainTypes.MARKET_BY_PRICE:
    			ret = chnlInfo.marketByPriceHandler.decodePayload(dIter, chnlInfo.dictionary, cacheDisplayStr);
    			break;

    		case DomainTypes.YIELD_CURVE:
    			ret = chnlInfo.yieldCurveHandler.decodePayload(dIter, chnlInfo.dictionary);
    			break;

    		default:
    			break;
    		}
    		if (ret > CodecReturnCodes.SUCCESS)
    			ret = CodecReturnCodes.SUCCESS;
    	}

    	return ret;
    }
    
    private void displayReactorChannelStats(ChannelInfo chnlInfo)
    {
    	ReactorChannelStats stats = ReactorFactory.createReactorChannelStats();
		chnlInfo.reactorChannel.getReactorChannelStats(stats);
		
		reactorChannelStats.bytesRead(overflowSafeAggregate(reactorChannelStats.bytesRead(), stats.bytesRead()));
		reactorChannelStats.uncompressedBytesRead(overflowSafeAggregate(reactorChannelStats.uncompressedBytesRead(), stats.uncompressedBytesRead()));
		reactorChannelStats.bytesWritten(overflowSafeAggregate(reactorChannelStats.bytesWritten(), stats.bytesWritten()));
		reactorChannelStats.uncompressedBytesWritten(overflowSafeAggregate(reactorChannelStats.uncompressedBytesWritten(), stats.uncompressedBytesWritten()));
		reactorChannelStats.pingsReceived(overflowSafeAggregate(reactorChannelStats.pingsReceived(), stats.pingsReceived()));
		reactorChannelStats.pingsSent(overflowSafeAggregate(reactorChannelStats.pingsSent(), stats.pingsSent()));
		
		//System.out.println("Message Details:");
                //APIQA
		Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
    	System.out.println("Statistic Time: "+ sdf.format(cal.getTime()));
    	//END APIQA
        System.out.println("Reactor channel statistic: Channel fd=" + chnlInfo.reactorChannel.channel().hashCode());
		System.out.printf("Bytes read=%d\n", reactorChannelStats.bytesRead());
		System.out.printf("Uncompressed bytes read=%d\n\n", reactorChannelStats.uncompressedBytesRead());
		System.out.printf("Bytes written=%d\n", reactorChannelStats.bytesWritten());
		System.out.printf("Uncompressed bytes written=%d\n\n", reactorChannelStats.uncompressedBytesWritten());
		System.out.printf("Pings sent=%d\n", reactorChannelStats.pingsSent());
		System.out.printf("Pings received=%d\n\n", reactorChannelStats.pingsReceived());
    }
    
    int overflowSafeAggregate(int a, int b)
    {
    	long sum = (long)a + (long)b;
    	if (sum < Integer.MAX_VALUE)
    		return (int)sum;
    	else
    		return Integer.MAX_VALUE;
    }

    private void setItemState(ChannelInfo chnlInfo, int streamState, int dataState, int stateCode )
    {
		Iterator<Map.Entry<StreamIdKey, WatchListEntry>> iter = chnlInfo.itemWatchList.iterator();
	    while (iter.hasNext())
	    {
	        WatchListEntry entry = iter.next().getValue();
	        entry.itemState.streamState(streamState);
	        entry.itemState.dataState(dataState);
	        entry.itemState.code(stateCode);
	    }
    }
    
    private void setEncryptedConfiguration(ConnectOptions options)
    {
    	setHTTPConfiguration(options);
    	
    	String keyFile = consumerCmdLineParser.keyStoreFile();
    	String keyPasswd = consumerCmdLineParser.keystorePassword();
        if (keyFile == null)
        {
        	System.err.println("Error: Keystore file not provided.");  
        	System.exit(CodecReturnCodes.FAILURE);        		        		        		
        }                   
        if (keyPasswd == null)
        {
        	System.err.println("Error: Keystore password not provided.");  
        	System.exit(CodecReturnCodes.FAILURE);        		        		        		
        }          
    	    	
    	options.tunnelingInfo().KeystoreFile(keyFile);
        options.tunnelingInfo().KeystorePasswd(keyPasswd);   
    }

    
    private void setHTTPConfiguration(ConnectOptions options)
    {    	
        options.tunnelingInfo().objectName("");
        options.tunnelingInfo().KeystoreType("JKS");
        options.tunnelingInfo().SecurityProtocol("TLS");
        options.tunnelingInfo().SecurityProvider("SunJSSE");
        options.tunnelingInfo().KeyManagerAlgorithm("SunX509");
        options.tunnelingInfo().TrustManagerAlgorithm("PKIX");
    	
        if (consumerCmdLineParser.enableProxy())
        {
         	String proxyHostName = consumerCmdLineParser.proxyHostname();
            if ( proxyHostName == null)
            {
            	System.err.println("Error: Proxy hostname not provided.");  
            	System.exit(CodecReturnCodes.FAILURE);        		        		        		
            }           
            String proxyPort = consumerCmdLineParser.proxyPort();
            if ( proxyPort == null)
            {
            	System.err.println("Error: Proxy port number not provided.");  
            	System.exit(CodecReturnCodes.FAILURE);        		        		        		
            }                             	

  
            options.tunnelingInfo().HTTPproxy(true);
            options.tunnelingInfo().HTTPproxyHostName(proxyHostName);
            try
            {
            	options.tunnelingInfo().HTTPproxyPort(Integer.parseInt(proxyPort));
            }
            catch(Exception e)
            {
               	System.err.println("Error: Proxy port number not provided.");  
            	System.exit(CodecReturnCodes.FAILURE);            	
            }
        }
   
        // credentials
        if (options.tunnelingInfo().HTTPproxy())
        {
            setCredentials(options);           
        }
    }    
    
    /*
     * For BASIC authentication we need: HTTPproxyUsername, HTTPproxyPasswd For
     * NTLM authentication we need: HTTPproxyUsername, HTTPproxyPasswd,
     * HTTPproxyDomain, HTTPproxyLocalHostname For Negotiate/Kerberos we need:
     * HTTPproxyUsername, HTTPproxyPasswd, HTTPproxyDomain,
     * HTTPproxyKRB5configFile
     */
    private void setCredentials(ConnectOptions options)
    {
        String localIPaddress = null;
        String localHostName = null;

    	String proxyUsername = consumerCmdLineParser.proxyUsername();
        if ( proxyUsername == null)
        {
        	System.err.println("Error: Proxy username not provided.");  
        	System.exit(CodecReturnCodes.FAILURE);        		        		        		
        }    
              
        String proxyPasswd = consumerCmdLineParser.proxyPassword();
        if ( proxyPasswd == null)
        {
        	System.err.println("Error: Proxy password not provided.");  
        	System.exit(CodecReturnCodes.FAILURE);        		        		        		
        }     
        String proxyDomain = consumerCmdLineParser.proxyDomain();
        if ( proxyDomain == null)
        {
        	System.err.println("Error: Proxy domain not provided.");  
        	System.exit(CodecReturnCodes.FAILURE);        		        		        		
        }             
    	    	
        options.credentialsInfo().HTTPproxyUsername(proxyUsername);
        options.credentialsInfo().HTTPproxyPasswd(proxyPasswd);
        options.credentialsInfo().HTTPproxyDomain(proxyDomain);
        
        try
        {
            localIPaddress = InetAddress.getLocalHost().getHostAddress();
            localHostName = InetAddress.getLocalHost().getHostName();
        }
        catch (UnknownHostException e)
        {
            localHostName = localIPaddress;
        }
        options.credentialsInfo().HTTPproxyLocalHostname(localHostName);
        
        String proxyKrbfile = consumerCmdLineParser.krbFile();
        if (proxyKrbfile == null)
        {
        	System.err.println("Error: Proxy krbfile not provided.");  
        	System.exit(CodecReturnCodes.FAILURE);        		        		        		
        }                              
        options.credentialsInfo().HTTPproxyKRB5configFile(proxyKrbfile);          
             
    }	

   
	private void createItemLists(ChannelInfo chnlInfo)
	{
        // add specified items to item watch list
	    if (chnlInfo.connectionArg.itemList() != null)
	    {
        for (ItemArg itemArg : chnlInfo.connectionArg.itemList())
        {
        	switch (itemArg.domain())
        	{
        		case DomainTypes.MARKET_PRICE:
	        		if (!itemArg.enablePrivateStream())
	        		{
	        			chnlInfo.mpItemList.add(itemArg.itemName());
	        		}
	        		else
	        		{
	        			chnlInfo.mppsItemList.add(itemArg.itemName());	        			
	        		}
	        		break;
        		case DomainTypes.MARKET_BY_ORDER:
	        		if (!itemArg.enablePrivateStream())
	        		{
	        			chnlInfo.mboItemList.add(itemArg.itemName());
	        		}
	        		else
	        		{
	        			chnlInfo.mbopsItemList.add(itemArg.itemName());	        			
	        		}
	        		break;
        		case DomainTypes.MARKET_BY_PRICE:
	        		if (!itemArg.enablePrivateStream())
	        		{
	        			chnlInfo.mbpItemList.add(itemArg.itemName());
	        		}
	        		else
	        		{
	        			chnlInfo.mbppsItemList.add(itemArg.itemName());	        			
	        		}
	        		break;
        		case DomainTypes.YIELD_CURVE:
	        		if (!itemArg.enablePrivateStream())
	        		{
	        			chnlInfo.ycItemList.add(itemArg.itemName());
	        		}
	        		else
	        		{
	        			chnlInfo.ycpsItemList.add(itemArg.itemName());	        			
	        		}
	        		break;
        		case DomainTypes.SYMBOL_LIST:
        			chnlInfo.slItemList.add(itemArg.itemName());
	        		break;
        		default:
	        		break;
        	}
        }
	}
	}

    private void sendSymbolListRequests(ChannelInfo chnlInfo)
    {
        if (chnlInfo.slItemList.size() == 0)
            return;

        if (!chnlInfo.serviceInfo.checkHasInfo())
        {
            uninitialize();
            System.exit(ReactorReturnCodes.FAILURE);
        }

        Service.ServiceInfo info = chnlInfo.serviceInfo.info();
        if (info.qosList().size() > 0)
        {
            Qos qos = info.qosList().get(0);
            chnlInfo.symbolListHandler.qos().dynamic(qos.isDynamic());
            chnlInfo.symbolListHandler.qos().rate(qos.rate());
            chnlInfo.symbolListHandler.qos().timeliness(qos.timeliness());
        }
        else
        {
            chnlInfo.symbolListHandler.qos().dynamic(false);
            chnlInfo.symbolListHandler.qos().rate(QosRates.TICK_BY_TICK);
            chnlInfo.symbolListHandler.qos().timeliness(QosTimeliness.REALTIME);
        }
        chnlInfo.symbolListHandler.capabilities().addAll(info.capabilitiesList());
        chnlInfo.symbolListHandler.serviceId(chnlInfo.serviceInfo.serviceId());
        String cmdSLName = chnlInfo.slItemList.get(0);
        if (cmdSLName == null)
        {
        	chnlInfo.symbolListHandler.symbolListName().data(info.itemList().data(), info.itemList().position(), info.itemList().length());
        }
        else
        {
        	chnlInfo.symbolListHandler.symbolListName().data(cmdSLName);
        }
        if (chnlInfo.symbolListHandler.sendRequest(chnlInfo.reactorChannel, errorInfo) != CodecReturnCodes.SUCCESS)
        {
            if (chnlInfo.reactorChannel.state() != ReactorChannel.State.CLOSED &&
                chnlInfo.reactorChannel.state() != ReactorChannel.State.DOWN_RECONNECTING)
            {
                System.out.println(errorInfo.error().text());
                uninitialize();
                System.exit(ReactorReturnCodes.FAILURE);
            }
        }
    }

    private void sendMBPRequests(ChannelInfo chnlInfo)
    {
        if (chnlInfo.marketByPriceHandler.sendItemRequests(chnlInfo.reactorChannel, chnlInfo.mbpItemList, false, chnlInfo.loginRefresh, chnlInfo.serviceInfo, errorInfo) != CodecReturnCodes.SUCCESS)
        {
            if (chnlInfo.reactorChannel.state() != ReactorChannel.State.CLOSED &&
                chnlInfo.reactorChannel.state() != ReactorChannel.State.DOWN_RECONNECTING)
            {
                System.out.println(errorInfo.error().text());
                uninitialize();
                System.exit(ReactorReturnCodes.FAILURE);
            }
        }

        if (chnlInfo.mbppsItemList.size() > 0 && !chnlInfo.mbppsRequestSent)
        {
            if (chnlInfo.marketByPriceHandler.sendItemRequests(chnlInfo.reactorChannel, chnlInfo.mbppsItemList, true, chnlInfo.loginRefresh, chnlInfo.serviceInfo, errorInfo) != CodecReturnCodes.SUCCESS)
            {
                if (chnlInfo.reactorChannel.state() != ReactorChannel.State.CLOSED &&
                    chnlInfo.reactorChannel.state() != ReactorChannel.State.DOWN_RECONNECTING)
                {
                    System.out.println(errorInfo.error().text());
                    uninitialize();
                    System.exit(ReactorReturnCodes.FAILURE);
                }
            }
            chnlInfo.mbppsRequestSent = true;
        }
    }

    private void sendMBORequests(ChannelInfo chnlInfo)
    {
        if (chnlInfo.marketByOrderHandler.sendItemRequests(chnlInfo.reactorChannel, chnlInfo.mboItemList, false, chnlInfo.loginRefresh, chnlInfo.serviceInfo, errorInfo) != CodecReturnCodes.SUCCESS)
        {
            if (chnlInfo.reactorChannel.state() != ReactorChannel.State.CLOSED &&
                chnlInfo.reactorChannel.state() != ReactorChannel.State.DOWN_RECONNECTING)
            {
                System.out.println(errorInfo.error().text());
                uninitialize();
                System.exit(ReactorReturnCodes.FAILURE);
            }
        }

        if (chnlInfo.mbopsItemList.size() > 0 && !chnlInfo.mbopsRequestSent)
        {
            if (chnlInfo.marketByOrderHandler.sendItemRequests(chnlInfo.reactorChannel, chnlInfo.mbopsItemList, true, chnlInfo.loginRefresh, chnlInfo.serviceInfo, errorInfo) != CodecReturnCodes.SUCCESS)
            {
                if (chnlInfo.reactorChannel.state() != ReactorChannel.State.CLOSED &&
                    chnlInfo.reactorChannel.state() != ReactorChannel.State.DOWN_RECONNECTING)
                {
                    System.out.println(errorInfo.error().text());
                    uninitialize();
                    System.exit(ReactorReturnCodes.FAILURE);
                }
            }
            chnlInfo.mbopsRequestSent = true;
        }
    }

    private void sendMPRequests(ChannelInfo chnlInfo)
    {
        if (chnlInfo.marketPriceHandler.sendItemRequests(chnlInfo.reactorChannel, chnlInfo.mpItemList, false, chnlInfo.loginRefresh, chnlInfo.serviceInfo, errorInfo) != CodecReturnCodes.SUCCESS)
        {
            if (chnlInfo.reactorChannel.state() != ReactorChannel.State.CLOSED &&
                chnlInfo.reactorChannel.state() != ReactorChannel.State.DOWN_RECONNECTING)
            {
                System.out.println(errorInfo.error().text());
                uninitialize();
                System.exit(ReactorReturnCodes.FAILURE);
            }
        }

        if (chnlInfo.mppsItemList.size() > 0 && !chnlInfo.mppsRequestSent)
        {
            if (chnlInfo.marketPriceHandler.sendItemRequests(chnlInfo.reactorChannel, chnlInfo.mppsItemList, true, chnlInfo.loginRefresh, chnlInfo.serviceInfo, errorInfo) != CodecReturnCodes.SUCCESS)
            {
                if (chnlInfo.reactorChannel.state() != ReactorChannel.State.CLOSED &&
                    chnlInfo.reactorChannel.state() != ReactorChannel.State.DOWN_RECONNECTING)
                {
                    System.out.println(errorInfo.error().text());
                    uninitialize();
                    System.exit(ReactorReturnCodes.FAILURE);
                }
            }
            chnlInfo.mppsRequestSent = true;
        }
    }

    private void sendYieldCurveRequests(ChannelInfo chnlInfo)
    {
        if (chnlInfo.yieldCurveHandler.sendItemRequests(chnlInfo.reactorChannel, chnlInfo.ycItemList, false, chnlInfo.loginRefresh, chnlInfo.serviceInfo, errorInfo) != CodecReturnCodes.SUCCESS)
        {
            if (chnlInfo.reactorChannel.state() != ReactorChannel.State.CLOSED &&
                chnlInfo.reactorChannel.state() != ReactorChannel.State.DOWN_RECONNECTING)
            {
                System.out.println(errorInfo.error().text());
                uninitialize();
                System.exit(ReactorReturnCodes.FAILURE);
            }
        }

        if (chnlInfo.ycpsItemList.size() > 0 && !chnlInfo.ycpsRequestSent)
        {
            if (chnlInfo.yieldCurveHandler.sendItemRequests(chnlInfo.reactorChannel, chnlInfo.ycpsItemList, true, chnlInfo.loginRefresh, chnlInfo.serviceInfo, errorInfo) != CodecReturnCodes.SUCCESS)
            {
                if (chnlInfo.reactorChannel.state() != ReactorChannel.State.CLOSED &&
                    chnlInfo.reactorChannel.state() != ReactorChannel.State.DOWN_RECONNECTING)
                {
                    System.out.println(errorInfo.error().text());
                    uninitialize();
                    System.exit(ReactorReturnCodes.FAILURE);
                }
            }
            chnlInfo.ycpsRequestSent = true;
        }
    }    
    
    private void closeItemStreams(ChannelInfo chnlInfo)
    {
        // have offstream posting post close status
    	if (chnlInfo.shouldOffStreamPost)
    	{
    		chnlInfo.postHandler.streamId(chnlInfo.loginRefresh.streamId());
    		chnlInfo.postHandler.postItemName().data("OFFPOST");
    		chnlInfo.postHandler.serviceId(chnlInfo.serviceInfo.serviceId());
    		chnlInfo.postHandler.dictionary(chnlInfo.dictionary);
    		chnlInfo.postHandler.closeOffStreamPost(chnlInfo.reactorChannel, errorInfo);
    	}

        // close item streams if opened
    	chnlInfo.marketPriceHandler.closeStreams(chnlInfo.reactorChannel, errorInfo);
    	chnlInfo.marketByOrderHandler.closeStreams(chnlInfo.reactorChannel, errorInfo);
    	chnlInfo.marketByPriceHandler.closeStreams(chnlInfo.reactorChannel, errorInfo);
    	chnlInfo.symbolListHandler.closeStream(chnlInfo.reactorChannel, errorInfo);
    	chnlInfo.yieldCurveHandler.closeStreams(chnlInfo.reactorChannel, errorInfo);
	}

    /* Uninitializes the Value Add consumer application. */
	private void uninitialize()
	{
        System.out.println("Consumer unitializing and exiting...");
        
    	for (ChannelInfo chnlInfo : chnlInfoList)
    	{
	        // close items streams
	        closeItemStreams(chnlInfo);
	
            // close tunnel streams
            if (tunnelStreamHandler != null &&
                chnlInfo.reactorChannel != null)
            {
                if (tunnelStreamHandler.closeStreams(chnlInfo, _finalStatusEvent, errorInfo) != ReactorReturnCodes.SUCCESS)
                {
                    System.out.println("tunnelStreamHandler.closeStream() failed with errorText: " + errorInfo.error().text());
                }
            }
    
	        // close ReactorChannel
	        if (chnlInfo.reactorChannel != null)
	        {
	        	chnlInfo.reactorChannel.close(errorInfo);
	        }
	        
	        uninitializeCache(chnlInfo.cacheInfo);
    	}
        
        // shutdown reactor
    	if (reactor != null)
    	{
    	    reactor.shutdown(errorInfo);
    	}
	}
	
	
	private void handleClose()
	{
		System.out.println("Consumer closes streams...");
	        		 		                
		for (ChannelInfo chnlInfo : chnlInfoList)
		{
			closeItemStreams(chnlInfo);
		
			// close tunnel streams
			if (tunnelStreamHandler != null && chnlInfo.reactorChannel != null)
			{
				if (tunnelStreamHandler.closeStreams(chnlInfo, _finalStatusEvent, errorInfo) != ReactorReturnCodes.SUCCESS)
				{
					System.out.println("tunnelStreamHandler.closeStream() failed with errorText: " + errorInfo.error().text());
	            }
	        }	    
		}	        						
	}
	
	public static void main(String[] args) throws Exception
    {		
        Consumer consumer = new Consumer();
        consumer.init(args);
        consumer.run(); 
        consumer.uninitialize();
        System.exit(0);
    }
}