File size: 38,426 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 |
package com.thomsonreuters.upa.valueadd.examples.provider;
import java.io.IOException;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
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.DecodeIterator;
import com.thomsonreuters.upa.codec.Msg;
import com.thomsonreuters.upa.codec.MsgClasses;
import com.thomsonreuters.upa.shared.DirectoryRejectReason;
import com.thomsonreuters.upa.shared.LoginRejectReason;
import com.thomsonreuters.upa.shared.DictionaryRejectReason;
import com.thomsonreuters.upa.shared.provider.ItemRejectReason;
import com.thomsonreuters.upa.rdm.Directory;
import com.thomsonreuters.upa.rdm.DomainTypes;
import com.thomsonreuters.upa.transport.BindOptions;
import com.thomsonreuters.upa.transport.Error;
import com.thomsonreuters.upa.transport.IoctlCodes;
import com.thomsonreuters.upa.transport.Server;
import com.thomsonreuters.upa.transport.Transport;
import com.thomsonreuters.upa.transport.TransportFactory;
import com.thomsonreuters.upa.transport.TransportReturnCodes;
import com.thomsonreuters.upa.valueadd.cache.CacheFactory;
import com.thomsonreuters.upa.valueadd.domainrep.rdm.dictionary.DictionaryMsg;
import com.thomsonreuters.upa.valueadd.domainrep.rdm.dictionary.DictionaryRequest;
import com.thomsonreuters.upa.valueadd.domainrep.rdm.directory.DirectoryMsg;
import com.thomsonreuters.upa.valueadd.domainrep.rdm.directory.DirectoryRequest;
import com.thomsonreuters.upa.valueadd.domainrep.rdm.login.LoginMsg;
import com.thomsonreuters.upa.valueadd.domainrep.rdm.login.LoginRequest;
import com.thomsonreuters.upa.valueadd.examples.common.CacheInfo;
import com.thomsonreuters.upa.valueadd.reactor.ProviderCallback;
import com.thomsonreuters.upa.valueadd.reactor.ProviderRole;
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.ReactorAcceptOptions;
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.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.TunnelStreamListenerCallback;
import com.thomsonreuters.upa.valueadd.reactor.TunnelStreamRequestEvent;
/**
* <p>
* This is a main class to run the UPA Value Add Provider application.
* </p>
* <H2>Summary</H2>
* <p>
* The purpose of this application is to demonstrate interactively providing
* data to OMM Consumer applications using ValueAdd components. It is a
* single-threaded server application.
* </p>
* <p>
* The provider application implements callbacks that process requests
* received by the consumer. It creates a Server and a Reactor and
* waits for connections. It accepts these connections into the Reactor
* and responds to messages through its Login, Directory, Dictionary, and
* default message callbacks.
* </p>
* <p>
* This provider supports providing Level I Market Price, Level II Market By
* Order, Level II Market By Price, and Symbol List data. Level II Market By
* Price refresh messages are sent as multi-part messages. An update
* message is sent between each part of the multi-part refresh message.
* </p>
* <p>
* Batch requests are supported by this application. The login response message indicates
* that batch support is present. Batch requests are accepted and a stream is opened
* for each item in the batch request.
* </p>
* <p>
* Posting requests are supported by this application for items that have already been
* opened by a consumer. On-stream and off-stream posts are accepted and sent out to any
* consumer that has the item open. Off-stream posts for items that have not already
* been opened by a consumer are rejected (in this example).
* </p>
* <p>
* Symbol List requests are expected to use a symbol list name of "_UPA_ITEM_LIST". The
* symbol list name is provided in the source directory response for the consumer to use.
* </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 must be located in the
* directory of execution.
* </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 runVAProvider -PcommandLineArgs="arguments"<br>
* Windows: gradlew.bat runVAProvider -PcommandLineArgs="arguments"<br>
* <br>
* Arguments are listed below.
* </p>
* <ul>
* <li>-p server port number (defaults to 14002)
* <li>-i interface name (defaults to null)
* <li>-s service name (defaults to DIRECT_FEED)
* <li>-id service id (defaults to 1)
* <li>-x provides an XML trace of messages
* <li>-cache application supports apply/retrieve data to/from cache
* <li>-supportView application sets supportView on LoginResp
* <li>-openWindow application sets openWindow on DirResp
* <li>-runtime application runtime in seconds (default is 1200)
* </ul>
*/
public class Provider implements ProviderCallback, TunnelStreamListenerCallback
{
// client sessions over this limit gets rejected with NAK mount
static final int NUM_CLIENT_SESSIONS = 5;
private static final int UPDATE_INTERVAL = 1;
private BindOptions bindOptions = TransportFactory.createBindOptions();
private Reactor reactor;
private ReactorOptions reactorOptions = ReactorFactory.createReactorOptions();
private ReactorAcceptOptions reactorAcceptOptions = ReactorFactory.createReactorAcceptOptions();
private ProviderRole providerRole = ReactorFactory.createProviderRole();
private ReactorErrorInfo errorInfo = ReactorFactory.createReactorErrorInfo();
private ReactorDispatchOptions dispatchOptions = ReactorFactory.createReactorDispatchOptions();
private ProviderCmdLineParser providerCmdLineParser = new ProviderCmdLineParser();
private Selector selector;
private Error error = TransportFactory.createError();
private DecodeIterator dIter = CodecFactory.createDecodeIterator();
private DictionaryHandler dictionaryHandler;
private DirectoryHandler directoryHandler;
private LoginHandler loginHandler;
private ItemHandler itemHandler;
private HashMap<ReactorChannel, TunnelStreamHandler> _tunnelStreamHandlerHashMap = new HashMap<ReactorChannel, TunnelStreamHandler>();
private int clientSessionCount = 0;
ArrayList<ReactorChannel> reactorChannelList = new ArrayList<ReactorChannel>();
private String portNo;
private String serviceName;
private int serviceId;
private long runtime;
private CacheInfo cacheInfo = new CacheInfo();
private boolean supportView;
private int openWindow;
private long closetime;
private long closeRunTime;
boolean closeHandled;
/* default server port number */
private static final String defaultSrvrPortNo = "14002";
/* default service name */
private static final String defaultServiceName = "DIRECT_FEED";
/* default service id */
private static final int defaultServiceId = 1;
/* default supportView */
private static final boolean defaultSupportView = false;
/* default openWindows */
private static final int defaultOpenWindow = 256;
boolean _finalStatusEvent;
public Provider()
{
dictionaryHandler = new DictionaryHandler();
directoryHandler = new DirectoryHandler();
loginHandler = new LoginHandler();
itemHandler = new ItemHandler(dictionaryHandler, loginHandler);
providerRole.channelEventCallback(this);
providerRole.defaultMsgCallback(this);
providerRole.dictionaryMsgCallback(this);
providerRole.directoryMsgCallback(this);
providerRole.loginMsgCallback(this);
providerRole.tunnelStreamListenerCallback(this);
_finalStatusEvent = true;
closetime = 10;
}
/*
* Initializes the Value Add consumer application. Parses command line arguments,
* loads the dictionaries, creates a reactor and a binds a server for listening.
* It also initializes Login, Directory, Dictionary and Item Handlers.
*/
private void init(String[] args)
{
// parse command line
if (!providerCmdLineParser.parseArgs(args))
{
System.err.println("\nError loading command line arguments:\n");
providerCmdLineParser.printUsage();
System.exit(ReactorReturnCodes.FAILURE);
}
if (providerCmdLineParser.portNo() != null)
{
portNo = providerCmdLineParser.portNo();
}
else
{
portNo = defaultSrvrPortNo;
}
if (providerCmdLineParser.serviceName() != null)
{
serviceName = providerCmdLineParser.serviceName();
}
else
{
serviceName = defaultServiceName;
}
if (providerCmdLineParser.serviceId() != 0)
{
serviceId = providerCmdLineParser.serviceId();
}
else
{
serviceId = defaultServiceId;
}
if (providerCmdLineParser.supportView() != false)
{
supportView = providerCmdLineParser.supportView();
}
else
{
supportView = defaultSupportView;
}
if (providerCmdLineParser.openWindow() > 0)
{
openWindow = providerCmdLineParser.openWindow();
}
else
{
openWindow = defaultOpenWindow;
}
runtime = System.currentTimeMillis() + (providerCmdLineParser.runtime() * 1000);
closeRunTime = System.currentTimeMillis() + (providerCmdLineParser.runtime() + closetime) * 1000;
System.out.println("portNo: " + portNo);
System.out.println("interfaceName: " + providerCmdLineParser.interfaceName());
System.out.println("serviceName: " + serviceName);
System.out.println("serviceId: " + serviceId);
// load dictionary
if (!dictionaryHandler.loadDictionary(error))
{
System.out.println("Error loading dictionary: " + error.text());
System.exit(ReactorReturnCodes.FAILURE);
}
if (providerCmdLineParser.cacheOption())
{
initializeCache();
initializeCacheDictionary();
}
// enable Reactor XML tracing if specified
if (providerCmdLineParser.enableXmlTracing())
{
reactorOptions.enableXmlTracing();
}
// open selector
try
{
selector = Selector.open();
}
catch (Exception exception)
{
System.out.println("Unable to open selector: " + exception.getMessage());
System.exit(ReactorReturnCodes.FAILURE);
}
// create reactor
reactor = ReactorFactory.createReactor(reactorOptions, errorInfo);
if (errorInfo.code() != ReactorReturnCodes.SUCCESS)
{
System.out.println("createReactor() failed: " + errorInfo.toString());
System.exit(ReactorReturnCodes.FAILURE);
}
// bind server
bindOptions.guaranteedOutputBuffers(500);
bindOptions.majorVersion(Codec.majorVersion());
bindOptions.minorVersion(Codec.minorVersion());
bindOptions.protocolType(Codec.protocolType());
bindOptions.serviceName(portNo);
bindOptions.interfaceName(providerCmdLineParser.interfaceName());
Server server = Transport.bind(bindOptions, error);
if (server == null)
{
System.out.println("Error initializing server: " + error.text());
System.exit(ReactorReturnCodes.FAILURE);
}
System.out.println("\nServer bound on port " + server.portNumber());
// register server for ACCEPT
try
{
server.selectableChannel().register(selector, SelectionKey.OP_ACCEPT, server);
}
catch (ClosedChannelException e)
{
System.out.println("selector register failed: " + e.getLocalizedMessage());
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);
}
// initialize handlers
loginHandler.init();
loginHandler.supportView(supportView);
directoryHandler.init();
directoryHandler.serviceName(serviceName);
directoryHandler.openWindow(openWindow);
itemHandler.init(cacheInfo);
directoryHandler.serviceId(serviceId);
itemHandler.serviceId(serviceId);
}
/*
* Runs the Value Add consumer application. Polls socket events from server socket.
* Accepts new client connections and reads requests from already established client
* connection. Checks for runtime expiration. If there is no activity on the socket,
* periodically sends item updates to connected client sessions that has requested
* market price items.
*/
private void run()
{
int ret = 0;
// main loop
while (true)
{
Set<SelectionKey> keySet = null;
try
{
if (selector.select(UPDATE_INTERVAL * 1000) > 0)
{
keySet = selector.selectedKeys();
}
}
catch (IOException e1)
{
System.out.println(e1.getMessage());
cleanupAndExit();
}
// nothing to read
if (keySet == null)
{
/* Send market price updates for each connected channel */
itemHandler.updateItemInfo();
for (ReactorChannel reactorChnl : reactorChannelList)
{
if (reactorChnl != null && reactorChnl.state() == ReactorChannel.State.READY)
{
ret = itemHandler.sendItemUpdates(reactorChnl, errorInfo);
if (ret != CodecReturnCodes.SUCCESS)
{
if (reactorChnl.state() != ReactorChannel.State.CLOSED &&
reactorChnl.state() != ReactorChannel.State.DOWN)
{
System.out.println(errorInfo.error().text());
cleanupAndExit();
}
}
}
}
}
else // notification occurred
{
Iterator<SelectionKey> iter = keySet.iterator();
while (iter.hasNext())
{
SelectionKey key = iter.next();
iter.remove();
if(!key.isValid())
continue;
if (key.isAcceptable()) // accept new connection
{
Server server = (Server)key.attachment();
clientSessionCount++;
reactorAcceptOptions.clear();
reactorAcceptOptions.acceptOptions().userSpecObject(server);
if (clientSessionCount <= NUM_CLIENT_SESSIONS)
{
reactorAcceptOptions.acceptOptions().nakMount(false);
}
else
{
reactorAcceptOptions.acceptOptions().nakMount(true);
}
if (reactor.accept(server, reactorAcceptOptions, providerRole, errorInfo) == ReactorReturnCodes.FAILURE)
{
System.out.println("Reactor accept error, text: " + errorInfo.error().text());
cleanupAndExit();
}
}
else if (key.isReadable()) // read from reactor channel
{
// 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)
{
System.out.println("ReactorChannel dispatch failed");
cleanupAndExit();
}
}
}
}
}
// Handle run-time
if (System.currentTimeMillis() >= runtime && !closeHandled)
{
System.out.println("Provider run-time expired, close now...");
sendCloseStatusMessages();
closeHandled = true;
}
else if (System.currentTimeMillis() >= closeRunTime )
{
System.out.println("Provider run-time expired...");
break;
}
if(closeHandled && allTunnelStreamsClosed())
{
break;
}
}
}
@Override
public int reactorChannelEventCallback(ReactorChannelEvent event)
{
ReactorChannel reactorChannel = event.reactorChannel();
switch(event.eventType())
{
case ReactorChannelEventTypes.CHANNEL_UP:
{
/* A channel that we have requested via Reactor.accept() has come up.
* Register selector so we can be notified to start calling dispatch() for
* this channel. */
System.out.println("\nConnection up!");
Server server = (Server)reactorChannel.userSpecObj();
System.out.println("Server " + server.selectableChannel() +
": New client on Channel " + reactorChannel.channel().selectableChannel());
// register selector with channel event's reactorChannel
try
{
reactorChannel.selectableChannel().register(selector,
SelectionKey.OP_READ,
reactorChannel);
}
catch (ClosedChannelException e)
{
System.out.println("selector register failed: " + e.getLocalizedMessage());
return ReactorCallbackReturnCodes.SUCCESS;
}
int rcvBufSize = 65535;
int sendBufSize = 65535;
/* Change size of send/receive buffer since it's small by default on some platforms */
if (reactorChannel.ioctl(IoctlCodes.SYSTEM_WRITE_BUFFERS, sendBufSize, errorInfo) != TransportReturnCodes.SUCCESS)
{
System.out.println("channel.ioctl() failed: " + error.text());
return ReactorCallbackReturnCodes.SUCCESS;
}
if (reactorChannel.ioctl(IoctlCodes.SYSTEM_READ_BUFFERS, rcvBufSize, errorInfo) != TransportReturnCodes.SUCCESS)
{
System.out.println("channel.ioctl() failed: " + error.text());
return ReactorCallbackReturnCodes.SUCCESS;
}
break;
}
case ReactorChannelEventTypes.CHANNEL_READY:
/* The channel has exchanged the messages necessary to setup the connection
* and is now ready for general use. For an RDM Provider, this normally immediately
* follows the CHANNEL_UP event. */
reactorChannelList.add(reactorChannel);
break;
case ReactorChannelEventTypes.FD_CHANGE:
/* The notifier representing the ReactorChannel has been changed.
* Update notifiers. */
System.out.println("Channel Change - Old Channel: "
+ reactorChannel.oldSelectableChannel() + " New Channel: "
+ 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
{
reactorChannel.selectableChannel().register(selector,
SelectionKey.OP_READ,
reactorChannel);
}
catch (Exception e)
{
System.out.println("selector register failed: " + e.getLocalizedMessage());
return ReactorCallbackReturnCodes.SUCCESS;
}
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");
// send close status messages to all item streams
itemHandler.sendCloseStatusMsgs(reactorChannel, errorInfo);
// send close status message to source directory stream
directoryHandler.sendCloseStatus(reactorChannel, errorInfo);
// send close status messages to dictionary streams
dictionaryHandler.sendCloseStatusMsgs(reactorChannel, errorInfo);
// close the tunnel stream
TunnelStreamHandler tunnelStreamHandler = _tunnelStreamHandlerHashMap.get(reactorChannel);
if (tunnelStreamHandler != null)
{
tunnelStreamHandler.closeStream(_finalStatusEvent, errorInfo);
}
/* It is important to make sure that no more interface calls are made using the channel after
* calling ReactorChannel.close(). Because this application is single-threaded, it is safe
* to call it inside callback functions. */
removeClientSessionForChannel(reactorChannel);
break;
}
case ReactorChannelEventTypes.WARNING:
System.out.println("Received ReactorChannel WARNING event\n");
break;
default:
System.out.println("Unknown channel event!\n");
cleanupAndExit();
}
return ReactorCallbackReturnCodes.SUCCESS;
}
@Override
public int defaultMsgCallback(ReactorMsgEvent event)
{
Msg msg = event.msg();
ReactorChannel reactorChannel = event.reactorChannel();
if (msg == null)
{
System.out.printf("defaultMsgCallback() received error: %s(%s)\n", event.errorInfo().error().text(), event.errorInfo().location());
removeClientSessionForChannel(reactorChannel);
return ReactorCallbackReturnCodes.SUCCESS;
}
// clear decode iterator
dIter.clear();
// set buffer and version info
if (msg.encodedDataBody().data() != null)
{
dIter.setBufferAndRWFVersion(msg.encodedDataBody(), reactorChannel.majorVersion(), reactorChannel.minorVersion());
}
switch (msg.domainType())
{
case DomainTypes.MARKET_PRICE:
case DomainTypes.MARKET_BY_ORDER:
case DomainTypes.MARKET_BY_PRICE:
case DomainTypes.YIELD_CURVE:
case DomainTypes.SYMBOL_LIST:
if (itemHandler.processRequest(reactorChannel, msg, dIter, errorInfo) != CodecReturnCodes.SUCCESS)
{
removeClientSessionForChannel(reactorChannel);
break;
}
break;
default:
switch (msg.msgClass())
{
case MsgClasses.REQUEST:
if (itemHandler.sendItemRequestReject(reactorChannel, msg.streamId(), msg.domainType(), ItemRejectReason.DOMAIN_NOT_SUPPORTED, false, errorInfo) != CodecReturnCodes.SUCCESS)
removeClientSessionForChannel(reactorChannel);
break;
case MsgClasses.CLOSE:
System.out.println("Received close message with streamId=" + msg.streamId() + " and unsupported Domain '" + msg.domainType() + "'");
break;
default:
System.out.println("Received unhandled Msg Class: " + MsgClasses.toString(msg.msgClass()) + " with streamId=" + msg.streamId() + " and unsupported Domain '" + msg.domainType() + "'");
break;
}
break;
}
return ReactorCallbackReturnCodes.SUCCESS;
}
@Override
public int rdmLoginMsgCallback(RDMLoginMsgEvent event)
{
LoginMsg loginMsg = event.rdmLoginMsg();
ReactorChannel reactorChannel = event.reactorChannel();
if (loginMsg == null)
{
System.out.printf("loginMsgCallback() received error: %s(%s)\n", event.errorInfo().error().text(), event.errorInfo().location());
if (event.msg() != null)
{
if (loginHandler.sendRequestReject(reactorChannel, event.msg().streamId(), LoginRejectReason.LOGIN_RDM_DECODER_FAILED, errorInfo) != CodecReturnCodes.SUCCESS)
removeClientSessionForChannel(reactorChannel);
return ReactorCallbackReturnCodes.SUCCESS;
}
else
{
removeClientSessionForChannel(reactorChannel);
return ReactorCallbackReturnCodes.SUCCESS;
}
}
switch(loginMsg.rdmMsgType())
{
case REQUEST:
{
LoginRequest loginRequest = (LoginRequest)loginMsg;
if (loginHandler.getLoginRequestInfo(reactorChannel, loginRequest) == null)
{
removeClientSessionForChannel(reactorChannel);
break;
}
System.out.println("\nReceived Login Request for Username: " + loginRequest.userName());
/* send login response */
if (loginHandler.sendRefresh(reactorChannel, loginRequest, errorInfo) != CodecReturnCodes.SUCCESS)
removeClientSessionForChannel(reactorChannel);
break;
}
case CLOSE:
System.out.println("\nReceived Login Close for StreamId " + loginMsg.streamId());
/* close login stream */
loginHandler.closeStream(loginMsg.streamId());
break;
default:
System.out.println("\nReceived unhandled login msg type: " + loginMsg.rdmMsgType());
break;
}
return ReactorCallbackReturnCodes.SUCCESS;
}
@Override
public int rdmDirectoryMsgCallback(RDMDirectoryMsgEvent event)
{
DirectoryMsg directoryMsg = event.rdmDirectoryMsg();
ReactorChannel reactorChannel = event.reactorChannel();
if (directoryMsg == null)
{
System.out.printf("directoryMsgCallback() received error: %s(%s)\n", event.errorInfo().error().text(), event.errorInfo().location());
if (event.msg() != null)
{
if (directoryHandler.sendRequestReject(reactorChannel, event.msg().streamId(), DirectoryRejectReason.DIRECTORY_RDM_DECODER_FAILED, errorInfo) != CodecReturnCodes.SUCCESS)
removeClientSessionForChannel(reactorChannel);
return ReactorCallbackReturnCodes.SUCCESS;
}
else
{
removeClientSessionForChannel(reactorChannel);
return ReactorCallbackReturnCodes.SUCCESS;
}
}
switch(directoryMsg.rdmMsgType())
{
case REQUEST:
{
DirectoryRequest directoryRequest = (DirectoryRequest)directoryMsg;
/* Reject any request that does not request at least the Info, State, and Group filters. */
if (((directoryRequest.filter() & Directory.ServiceFilterFlags.INFO) == 0) ||
((directoryRequest.filter() & Directory.ServiceFilterFlags.STATE) == 0) ||
((directoryRequest.filter() & Directory.ServiceFilterFlags.GROUP) == 0))
{
if (directoryHandler.sendRequestReject(reactorChannel, event.msg().streamId(), DirectoryRejectReason.INCORRECT_FILTER_FLAGS, errorInfo) != CodecReturnCodes.SUCCESS)
removeClientSessionForChannel(reactorChannel);
break;
}
if (directoryHandler.getDirectoryRequest(reactorChannel, directoryRequest) == null)
{
removeClientSessionForChannel(reactorChannel);
break;
}
System.out.println("\nReceived Source Directory Request");
/* send source directory response */
if (directoryHandler.sendRefresh(reactorChannel, directoryRequest, errorInfo) != CodecReturnCodes.SUCCESS)
removeClientSessionForChannel(reactorChannel);
break;
}
case CLOSE:
{
System.out.println("\nReceived Source Directory Close for StreamId " + directoryMsg.streamId());
/* close source directory stream */
directoryHandler.closeStream(directoryMsg.streamId());
break;
}
default:
System.out.println("\nReceived unhandled Source Directory msg type: " + directoryMsg.rdmMsgType());
break;
}
return ReactorCallbackReturnCodes.SUCCESS;
}
@Override
public int rdmDictionaryMsgCallback(RDMDictionaryMsgEvent event)
{
int ret;
DictionaryMsg dictionaryMsg = event.rdmDictionaryMsg();
ReactorChannel reactorChannel = event.reactorChannel();
if (dictionaryMsg == null)
{
System.out.printf("dictionaryMsgCallback() received error: %s(%s)\n", event.errorInfo().error().text(), event.errorInfo().location());
if (event.msg() != null)
{
if (dictionaryHandler.sendRequestReject(reactorChannel, event.msg().streamId(), DictionaryRejectReason.DICTIONARY_RDM_DECODER_FAILED, errorInfo) != CodecReturnCodes.SUCCESS)
removeClientSessionForChannel(reactorChannel);
return ReactorCallbackReturnCodes.SUCCESS;
}
else
{
removeClientSessionForChannel(reactorChannel);
return ReactorCallbackReturnCodes.SUCCESS;
}
}
switch(dictionaryMsg.rdmMsgType())
{
case REQUEST:
{
DictionaryRequest dictionaryRequest = (DictionaryRequest)dictionaryMsg;
if (dictionaryHandler.getDictionaryRequestInfo(reactorChannel, dictionaryRequest) == null)
{
removeClientSessionForChannel(reactorChannel);
break;
}
System.out.println("\nReceived Dictionary Request for DictionaryName: " + dictionaryRequest.dictionaryName());
if (DictionaryHandler.fieldDictionaryDownloadName.equals(dictionaryRequest.dictionaryName()))
{
/* Name matches field dictionary. Send the field dictionary refresh. */
if ((ret = dictionaryHandler.sendFieldDictionaryResponse(reactorChannel, dictionaryRequest, errorInfo)) != CodecReturnCodes.SUCCESS)
{
System.out.println("sendFieldDictionaryResponse() failed: " + ret);
removeClientSessionForChannel(reactorChannel);
}
}
else if (DictionaryHandler.enumTypeDictionaryDownloadName.equals(dictionaryRequest.dictionaryName()))
{
/* Name matches the enum types dictionary. Send the enum types dictionary refresh. */
if ((ret = dictionaryHandler.sendEnumTypeDictionaryResponse(reactorChannel, dictionaryRequest, errorInfo)) != CodecReturnCodes.SUCCESS)
{
System.out.println("sendEnumTypeDictionaryResponse() failed: " + ret);
removeClientSessionForChannel(reactorChannel);
}
}
else
{
if (dictionaryHandler.sendRequestReject(reactorChannel, event.msg().streamId(), DictionaryRejectReason.UNKNOWN_DICTIONARY_NAME, errorInfo) != CodecReturnCodes.SUCCESS)
{
removeClientSessionForChannel(reactorChannel);
}
}
break;
}
case CLOSE:
System.out.println("\nReceived Dictionary Close for StreamId " + dictionaryMsg.streamId());
/* close dictionary stream */
dictionaryHandler.closeStream(dictionaryMsg.streamId());
break;
default:
System.out.println("\nReceived Unhandled Dictionary Msg Type: " + dictionaryMsg.rdmMsgType());
break;
}
return ReactorCallbackReturnCodes.SUCCESS;
}
@Override
public int listenerCallback(TunnelStreamRequestEvent event)
{
TunnelStreamHandler tunnelStreamHandler = new TunnelStreamHandler();
_tunnelStreamHandlerHashMap.put(event.reactorChannel(), tunnelStreamHandler);
tunnelStreamHandler.processNewStream(event);
return ReactorCallbackReturnCodes.SUCCESS;
}
/*
* Sends close status messages to all streams on all channels.
*/
private void sendCloseStatusMessages()
{
// send close status messages to all streams on all channels
for (ReactorChannel reactorChnl : reactorChannelList)
{
if ((reactorChnl != null))
{
// send close status messages to all item streams
if (itemHandler.sendCloseStatusMsgs(reactorChnl, errorInfo) != CodecReturnCodes.SUCCESS)
System.out.println("Error sending item close: " + errorInfo.error().text());
// close tunnel stream
TunnelStreamHandler tunnelStreamHandler = _tunnelStreamHandlerHashMap.get(reactorChnl);
if (tunnelStreamHandler != null)
{
if (tunnelStreamHandler.closeStream(_finalStatusEvent, errorInfo) != CodecReturnCodes.SUCCESS)
System.out.println("Error closing tunnel stream: " + errorInfo.error().text());
}
// send close status message to source directory stream
if (directoryHandler.sendCloseStatus(reactorChnl, errorInfo) != CodecReturnCodes.SUCCESS)
System.out.println("Error sending directory close: " + errorInfo.error().text());
// send close status messages to dictionary streams
if (dictionaryHandler.sendCloseStatusMsgs(reactorChnl, errorInfo) != CodecReturnCodes.SUCCESS)
System.out.println("Error sending dictionary close: " + errorInfo.error().text());
}
}
}
/*
* Removes a client session for a channel.
*/
private void removeClientSessionForChannel(ReactorChannel reactorChannel)
{
if (reactorChannel.selectableChannel() != null)
{
SelectionKey key = reactorChannel.selectableChannel().keyFor(selector);
if (key != null)
key.cancel();
}
reactorChannelList.remove(reactorChannel);
dictionaryHandler.closeStream(reactorChannel);
directoryHandler.closeStream(reactorChannel);
loginHandler.closeStream(reactorChannel);
itemHandler.closeStream(reactorChannel);
reactorChannel.close(errorInfo);
clientSessionCount--;
}
/*
* initializeCache
*/
private void initializeCache()
{
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()
{
if (cacheInfo.cache != null)
cacheInfo.cache.destroy();
cacheInfo.cache = null;
if (cacheInfo.cursor != null)
cacheInfo.cursor.destroy();
cacheInfo.cursor = null;
}
/*
* initalizeCacheDictionary
*/
private void initializeCacheDictionary()
{
DataDictionary dictionary = dictionaryHandler.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 boolean allTunnelStreamsClosed()
{
boolean ret = true;
for (TunnelStreamHandler tunnelStreamHandler : _tunnelStreamHandlerHashMap.values())
{
if (tunnelStreamHandler.isStreamClosed() != true)
{
ret = false;
break;
}
}
return ret;
}
/*
* Cleans up and exits.
*/
private void cleanupAndExit()
{
uninitializeCache();
uninitialize();
System.exit(ReactorReturnCodes.FAILURE);
}
/* Uninitializes the Value Add consumer application. */
private void uninitialize()
{
// shutdown reactor
reactor.shutdown(errorInfo);
}
public static void main(String[] args) throws Exception
{
Provider provider = new Provider();
provider.init(args);
provider.run();
provider.uninitialize();
System.exit(ReactorReturnCodes.SUCCESS);
}
}
|