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

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
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

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
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

22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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);
    }
}
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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());
    }
}
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
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();
    }
}