Samples :: Scheduler

Simple Acceptor

Description

This sample acts as a simple acceptor for other scheduler samples.

“SimpleAcceptor” application must be started first.

Directory Contents

Item Description
conf/sample/SimpleAcceptor.properties application configuration file
conf/logback.xml logger configuration file

Usage

  • Run the sample:
    • win: 1-SimpleAcceptor.bat
    • linux: 1-SimpleAcceptor.sh
  • Clean everything:
    • win: clean.bat
    • linux: clean.sh

Source Code

import biz.onixs.cme.ilink3.testing.Emulator;
import biz.onixs.cme.ilink3.testing.TestUtility;
import biz.onixs.util.settings.PropertyBasedSettings;
import biz.onixs.util.settings.Settings;
import org.junit.jupiter.api.Assertions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SimpleAcceptor {
    private static final Logger LOG = LoggerFactory.getLogger(SimpleAcceptor.class);
    private static final String SETTINGS_RESOURCE = "sample/SimpleAcceptor.properties";

    private void run() {
        try {
            //
            LOG.info("Loading settings from: {}", SETTINGS_RESOURCE);
            final Settings settings = new PropertyBasedSettings(SETTINGS_RESOURCE);

            LOG.info("Creates an Emulator object configured as acceptor");
            final Emulator emulator = new Emulator(new TestUtility());
            emulator.setPort(settings.getInteger("ListenPort"));

            LOG.info("Accepts an incoming TCP connection and prepares for message exchange");
            emulator.acceptConnection();

            LOG.info("Accepts a \"Negotiate\" message from the initiator");
            emulator.acceptNegotiation();

            LOG.info("Accepts an \"Establish\" message, finalizing the session setup");
            emulator.acceptEstablishment(1);

            LOG.info("Accepts a \"Terminate\" message, ending the session");
            emulator.acceptTerminate();

            // Asserts that the Emulator's connection is now closed.
            Assertions.assertTrue(emulator.isConnectionClosed());
        } catch (final Exception e) {
            LOG.error(e.getMessage(), e);
        }
    }

    public static void main(final String[] args) {
        try {
            LOG.info("SimpleAcceptor");
            LOG.info("The application is starting...");
            final SimpleAcceptor acceptor = new SimpleAcceptor();
            acceptor.run();
        } catch (Throwable throwable) {
            LOG.error(throwable.getMessage(), throwable);
        } finally {
            LOG.info("The application is stopped.");
        }
    }
}

Scheduler Sample

Description

This sample demonstrates the usage of the Session Scheduler functionality.

This sample can be run together with the “SimpleAcceptor” app. The “SimpleAcceptor” must be started first.

Directory Contents

Item Description
conf/sample/Scheduler.properties handler and application configuration file
conf/logback.xml logger configuration file

Usage

  • Run the sample:
    • win: 2-Scheduler.bat
    • linux: 2-Scheduler.sh
  • Clean everything:
    • win: clean.bat
    • linux: clean.sh

Source Code


import biz.onixs.cme.ilink3.handler.Handler;
import biz.onixs.cme.ilink3.handler.Session;
import biz.onixs.cme.ilink3.handler.session.*;
import biz.onixs.cme.ilink3.handler.session.ErrorListener;
import biz.onixs.cme.ilink3.scheduler.*;
import biz.onixs.sbe.IMessage;
import biz.onixs.util.settings.PropertyBasedSettings;
import biz.onixs.util.settings.Settings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.time.DayOfWeek;
import java.time.LocalTime;

/**
 * Scheduler sample.
 */
public class Scheduler implements InboundSessionMessageListener, InboundApplicationMessageListener,
        OutboundSessionMessageListener, OutboundApplicationMessageListener, WarningListener, ErrorListener, Runnable {
    private static final Logger LOG = LoggerFactory.getLogger(Scheduler.class);
    private static final String SETTINGS_RESOURCE = "sample/Scheduler.properties";
    private final DemoSessionStateChangeListener stateChangeListener = new DemoSessionStateChangeListener();
    private final int marketSegmentId;
    private final String host;
    private final int port;
    private final Settings settings;
    private Session session = null;
    private SessionScheduler scheduler = null;

    public Scheduler(final int marketSegmentId, final String host, final int port, final Settings settings) {
        this.marketSegmentId = marketSegmentId;
        this.host = host;
        this.port = port;
        this.settings = settings;
    }

    public void run() {
        try {
            LOG.info("Starting the Handler...");
            Handler.init(settings);
            //
            createAndStartScheduler();
            //
            createSession();
            //
            subscribeListeners();
            //
            final SessionSchedule schedule = createSchedule();
            final SessionConnection connection = createSessionConnectionSettings();
            scheduler.register(session, schedule, connection);
            LOG.info("Initiator session is registered in the scheduler.");
            //
            LOG.info("Waiting to connect...");
            stateChangeListener.waitEstablished();
            LOG.info("Connected.");
            //
            LOG.info("Waiting to disconnect...");
            stateChangeListener.waitDisconnected();
            LOG.info("Disconnected.");
            //
            scheduler.unregister(session);
        } catch (final Exception e) {
            LOG.error(e.getMessage(), e);
        } finally {
            if (null != scheduler) {
                try {
                    scheduler.stop();
                } catch (final SessionSchedulerException e) {
                    LOG.error("Scheduler stop error", e);
                }
            }
            LOG.info("Handler shutdown ...");
            if (Handler.isInited()) {
                Handler.getInstance().shutdown();
            }
            LOG.info("The application is stopped.");
        }
    }

    private void createSession() {
        final SessionSettings sessionSettings = new SessionSettings();
        sessionSettings.init(settings);
        session = new Session(sessionSettings, marketSegmentId);
    }

    private void subscribeListeners() {
        session.addStateChangeListener(stateChangeListener);
        session.setOutboundSessionMessageListener(this);
        session.setOutboundApplicationMessageListener(this);
        session.setInboundSessionMessageListener(this);
        session.setInboundApplicationMessageListener(this);
        session.setErrorListener(this);
        session.setWarningListener(this);
    }

    /**
     * Creates and configures the scheduler instance.
     */
    private void createAndStartScheduler() throws SessionSchedulerException {
        scheduler = new SessionScheduler();
        scheduler.addLogoutNotification(1);
        scheduler.addLogoutNotification(2);
        scheduler.getListenerManager().addErrorListener(new DemoErrorListener());
        scheduler.getListenerManager().addLogoutNotificationListener(new DemoLogoutNotificationListener());
        scheduler.start();
    }

    /**
     * Creates and configures the initiator connection settings.
     */
    private SessionConnection createSessionConnectionSettings() {
        final SessionConnection connection = new SessionConnection();
        final InetSocketAddress address = InetSocketAddress.createUnresolved(host, port);
        connection.addAddress(address);
        return connection;
    }

    /**
     * Creates and configures the simple session schedule.
     * Features:
     * <ul>
     * <li>logon and logout every day from Monday till Sunday</li>
     * <li>logon time is set to 5 seconds from now</li>
     * <li>logout time is set to 10 seconds from now</li>
     * </ul>
     */
    private static SessionSchedule createSchedule() {
        final SingleDayLengthSchedule schedule = new SingleDayLengthSchedule();
        final LocalTime now = LocalTime.now();
        schedule.setLogonTime(now.plusSeconds(5))
                .setLogoutTime(now.plusSeconds(15))
                .setFirstDay(DayOfWeek.MONDAY)
                .setLastDay(DayOfWeek.SUNDAY);
        return schedule;
    }

    @Override
    public void onInboundSessionMessage(final Object sender, final InboundSessionMessageArgs args) {
        final IMessage message = args.getMsg();
        LOG.info("Incoming session-level message: {}", message);
        // Processing of the incoming session-level message...
    }

    @Override
    public void onInboundApplicationMessage(final Object sender, final InboundApplicationMessageArgs args) {
        final IMessage message = args.getMsg();
        LOG.info("Incoming application-level message: {}", message);
        // Processing of the incoming application-level message...
    }

    @Override
    public void onOutboundSessionMessage(final Object sender, final OutboundSessionMessageArgs args) {
        final IMessage message = args.getMsg();
        LOG.info("Outgoing session-level message: {}", message);
    }

    @Override
    public void onOutboundApplicationMessage(final Object sender, final OutboundApplicationMessageArgs args) {
        final IMessage message = args.getMsg();
        LOG.info("Outgoing application-level message: {}", message);
    }

    @Override
    public void onWarning(final Object sender, final WarningArgs args) {
        LOG.warn("{}", args.getDescription());
    }

    @Override
    public void onError(final Object sender, final ErrorArgs args) {
        LOG.error("{}", args.getDescription());
    }

    private static void configureSettings(Settings settings) throws IOException {
        settings.setString(SessionSettings.SESSION_PROP, "XXX");
        settings.setString(SessionSettings.FIRM_PROP, "001");
        settings.setString(SessionSettings.ACCESS_KEY_PROP, "dGVzdHRlc3R0ZXN0dA==");
        settings.setString(SessionSettings.SECRET_KEY_PROP, "dGVzdHRlc3R0ZXN0dGVzdHRlc3R0");
        settings.setInteger(SessionSettings.KEEP_ALIVE_INTERVAL_PROP, 50);
        settings.setInteger(SessionSettings.RECONNECT_ATTEMPTS_PROP, 0);
        settings.setString(SessionSettings.TRADING_SYSTEM_VERSION_PROP, "1.1.0");
        settings.setString(SessionSettings.TRADING_SYSTEM_NAME_PROP, "Trading System");
        settings.setString(SessionSettings.TRADING_SYSTEM_VENDOR_PROP, "OnixS");
    }

    public static void main(final String[] args) throws IOException {
        LOG.info("Scheduler Sample");
        LOG.info("The application is starting...");
        LOG.info("Loading settings from: {}", SETTINGS_RESOURCE);
        final Settings settings = new PropertyBasedSettings(SETTINGS_RESOURCE);
        //
        int marketSegmentId;
        String host;
        int port;
        //
        if (3 > args.length) {
            LOG.info("Emulator is used, remote usage: [MarketSegmentId] [Host] [Port]");
            marketSegmentId = 59;
            host = settings.getString("CounterpartyHost");
            port = settings.getInteger("CounterpartyPort");
            configureSettings(settings);
        } else {
            marketSegmentId = Integer.parseInt(args[0]);
            host = args[1];
            port = Integer.parseInt(args[2]);
        }
        final Scheduler scheduler = new Scheduler(marketSegmentId, host, port, settings);
        scheduler.run();
    }
}

Source Codes Used In Samples

import biz.onixs.cme.ilink3.scheduler.ErrorListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DemoErrorListener implements ErrorListener {
    private static final Logger LOG = LoggerFactory.getLogger(DemoErrorListener.class);

    @Override
    public void onError(final ErrorArgs args) {
        LOG.error("onError(): {}", args);
    }

    /**
     * Logon error event callback.
     *
     * @param args event arguments
     */
    @Override
    public void onLogonError(final LogonErrorArgs args) {
        LOG.error("onLogonError(): {}", args);
    }
}
import biz.onixs.cme.ilink3.scheduler.LogoutNotification;
import biz.onixs.cme.ilink3.scheduler.LogoutNotificationListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Demo logout notification listener implementation.
 */
public class DemoLogoutNotificationListener implements LogoutNotificationListener {
    private static final Logger LOG = LoggerFactory.getLogger(DemoLogoutNotificationListener.class);

    @Override
    public void onLogoutNotification(final LogoutNotification notification) {
        LOG.info("{}: logout notification: {} seconds left", notification.getSession(), notification.getInterval());
    }
}
import biz.onixs.cme.ilink3.handler.SessionState;
import biz.onixs.cme.ilink3.handler.session.StateChangeArgs;
import biz.onixs.cme.ilink3.handler.session.StateChangeListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.Semaphore;

public class DemoSessionStateChangeListener implements StateChangeListener {
    private static final Logger LOG = LoggerFactory.getLogger(DemoSessionStateChangeListener.class);
    private final Semaphore semaphoreIsEstablished = new Semaphore(0);
    private final Semaphore semaphoreIsDisconnected = new Semaphore(0);

    @Override
    public void onStateChange(final Object sender, final StateChangeArgs args) {
        final SessionState prevState = args.getPrevState();
        final SessionState newState = args.getNewState();
        if (prevState != SessionState.TERMINATED && SessionState.TERMINATED == newState) {
            semaphoreIsDisconnected.release();
        } else if (SessionState.ESTABLISHED == newState) {
            semaphoreIsEstablished.release();
        }
    }

    public void waitEstablished() throws InterruptedException {
        semaphoreIsEstablished.acquire();
    }

    public void waitDisconnected() throws InterruptedException {
        semaphoreIsDisconnected.acquire();
    }
}