Skip to content
Connect > Client Libraries

Java Client

The Java client classes, shipped in every 3forge Enterprise install as part of lib/amicore.jar, let a Java program publish objects to a Relay over mutual TLS, answer commands, and subscribe to Center tables.

Overview

The Java classes are a separate implementation from the Python and C++ clients, with no cluster object, no shards, and no outbox. Each class uses one connection:

  • AmiClient: publishes objects and registers commands over the Relay connection.
  • AmiCenterClient: subscribes to tables and runs queries over the Center connection, and needs a license file.

To run SQL from Java without a license file, use the JDBC driver: see JDBC Access.

Prerequisites

  • A Java 8 or later JDK. The classes are in the install's lib/amicore.jar; add it to the classpath.
  • A client keystore whose key the server accepts, and the server's public key, keys/3forge.pub. See Creating a Java keystore and Authorizing a client.

The classes on this page are in these packages:

Package Classes
com.f1.ami.client AmiClient, AmiClientListener, AmiClientCommandDef, RawAmiClient, AmiCenterClient, AmiCenterClientSubscription
com.f1.ami.amicommon.centerclient AmiCenterClientListener, AmiCenterQueryResponseListener, AmiCenterClientObjectMessage
com.f1.ami.amicommon.msg AmiCenterQueryDsRequest, AmiCenterQueryDsResponse
com.f1.ami.amicommon AmiCenterDefinition
com.f1.base Password, SFile
com.f1.utils BasicResourceOpener
com.f1.utils.impl KeyHelper

Publishing an object

These steps publish one object to a Relay and confirm it was stored.

  1. Save the following code as Publish.java, with client.jks and 3forge.pub in the same directory:

    import com.f1.ami.client.AmiClient;
    import com.f1.ami.client.AmiClientListener;
    import com.f1.base.Password;
    import com.f1.utils.BasicResourceOpener;
    import com.f1.utils.impl.KeyHelper;
    
    import java.util.Map;
    import javax.net.ssl.SSLContext;
    import javax.net.ssl.SSLSocket;
    
    public class Publish {
        public static void main(String[] args) throws Exception {
            SSLContext ssl = KeyHelper.loadOrGenerateClientSSLContext(
                    BasicResourceOpener.INSTANCE.toFile("client.jks"),
                    Password.valueOf("changeit"),
                    BasicResourceOpener.INSTANCE.toFile("3forge.pub"));
            SSLSocket socket = (SSLSocket) ssl.getSocketFactory().createSocket("localhost", 3289);
            socket.startHandshake();
    
            AmiClient client = new AmiClient();
            client.addListener(new AmiClientListener() {
                public void onMessageReceived(AmiClient c, long now, long seqnum, int status, CharSequence message) {
                    System.out.println("status=" + status + " " + message);
                }
                public void onMessageSent(AmiClient c, CharSequence message) { }
                public void onConnect(AmiClient c) { }
                public void onDisconnect(AmiClient c) { }
                public void onCommand(AmiClient c, String requestId, String cmd, String userName,
                        String objectType, String objectId, Map<String, Object> params) { }
                public void onLoggedIn(AmiClient c) { }
            });
            client.start(socket, "my_app", AmiClient.ENABLE_AUTO_PROCESS_INCOMING);
    
            client.startObjectMessage("Orders", "ord-1")
                    .addMessageParamString("sym", "IBM")
                    .addMessageParamLong("qty", 100L)
                    .sendMessageAndFlush();
            Thread.sleep(1000);
            client.close();
        }
    }
    
  2. Compile and run it, replacing the install path. On Windows, separate the classpath entries with ; instead of ::

    javac -cp /path/to/amicore/lib/amicore.jar Publish.java
    java -cp /path/to/amicore/lib/amicore.jar:. Publish
    
  3. Check that the output shows status=0 Welcome to 3forge AMI v1.0, then status=0 OK, object accepted.

  4. Confirm that the row was stored: run SELECT * FROM Orders, and it returns the row, with ord-1 in the I column.

A warning about a closed socket logged by close() does not mean the publish failed. The row stays in the table after the program exits.

KeyHelper.loadOrGenerateClientSSLContext presents the keystore's key and pins the server against 3forge.pub. If the keystore file does not exist, it creates one, with a sibling .pub file holding the ssh-rsa line to authorize.

Connecting

AmiClient presents a client certificate only through a socket the program has already opened, as in the steps above. Its start forms:

Form What it does
start(socket, loginId, options) Uses the program's TLS socket, so it can present a client certificate. Never reconnects
start(host, port, loginId, options) Opens a plain connection. Against a secured port it reports onConnect and onLoggedIn, then logs General error: missing @ for string '...' with unreadable characters between the quotes, disconnects, and reconnects at once, hundreds of times a second
start(host, port, loginId, options, file, password), with file an SFile and password a String or Password The file pins the server. The password is not used, and no client certificate is sent, so against a secured port the client disconnects and reconnects continuously, and messages sent meanwhile are lost

onLoggedIn fires when the client sends its login, not when the server accepts it, and with the forms that take a file it can fire after onDisconnect. It does not confirm a connection. The first reply, Welcome to 3forge AMI v1.0, does.

To connect by host and port with a client certificate, use RawAmiClient.connect(resourceOpener, host, port, logErrorOnRetries, serverPubFile, clientKeystore, keystorePassword, keystoreAlias, autoflush). It returns true when connected, and throws if the keystore password is wrong.

Option on AmiClient Value Effect
ENABLE_AUTO_PROCESS_INCOMING 2 Starts a thread that reads replies and calls the listener. Without it, nothing arrives unless the program calls pumpIncomingEvent()
ENABLE_QUIET 4 The Relay sends no replies
DISABLE_AUTO_RECONNECT 8 No reconnection after a drop. start(socket, ...) always sets it
ENABLE_SEND_TIMESTAMPS 32 Adds the time in milliseconds to each message sent, e.g: O@1795090757281\|T=...
ENABLE_SEND_SEQNUM 64 Sends a sequence number with each message; replies then read ACK
LOG_CONNECTION_RETRY_ERRORS 128 Logs every failed reconnect attempt. Without it, only the first is logged
LOG_MESSAGES 256 Logs every message sent (>>) and received (<<), at INFO
ENABLE_AUTO_FLUSH_OUTGOING 512 Sends buffered messages automatically, with the host-and-port start forms only. start(socket, ...) ignores it, so call flush() or sendMessageAndFlush()

Message methods

A message is built and sent with these AmiClient methods:

  • startObjectMessage(type, id): start an object.
  • startDeleteMessage(type, id): start the deletion of an object.
  • addMessageParamString, addMessageParamLong, addMessageParamInt, addMessageParamDouble, addMessageParamBoolean, and the other addMessageParam methods: add a field.
  • sendMessage() or sendMessageAndFlush(): send the message.

The type names the table. A new type creates its table; an existing table needs an I column and a column for every field. The reply OK, object accepted arrives before the object reaches the Center, so it does not show the row was stored. See Publishing and the acknowledgement.

A message built before start or after close(), or while the start(host, port, loginId, options) form is reconnecting, throws IllegalStateException("not connected"). With the forms that take a file, a message sent while the client is reconnecting raises no exception and is lost. The client keeps no queue of unsent messages.

Commands

A command adds an action that the platform can call back into the program.

1
2
3
client.sendCommandDefinition(new AmiClientCommandDef("restart_feed")
        .setName("Restart feed")
        .setHelp("Restarts the market data feed"));

The Relay replies OK, command accepted. The listener's onCommand receives the request, and the program answers with startResponseMessage(requestId, AmiClient.RESPONSE_STATUS_OKAY, "done") followed by sendMessageAndFlush(). A command is removed when the client disconnects, and is not registered again on reconnect.

A user runs the command from the right-click menu of a real-time table panel in the Web. To accept several rows, set setSelectMode(min, max). The arguments are the same as in Python, see What a command call receives, with 2 differences:

  • params holds typed values: o is a Long, and V is a list with one map per selected row, e.g: [{O=o2, o=38000270}, {O=o3, o=38000271}].
  • objectType and objectId are null for a command that takes several rows, not empty.

Against a Relay on Windows, the Java client needs no option: it receives replies and command calls as sent.

Table subscriptions

AmiCenterClient subscribes to tables on the Center port, 3270 by default. It runs inside a container that needs a license file, so start the JVM with -Df1.license.file=<path to f1license.txt>. Without one, the program prints License File not found and exits with code 23.

1
2
3
AmiCenterClient center = new AmiCenterClient(BasicResourceOpener.INSTANCE, "my_app");
center.connect("C1", "localhost", 3270, ssl, listener);
center.subscribe("C1", Collections.singletonList(new AmiCenterClientSubscription("Quotes")));

ssl is the SSLContext from Publishing an object, and listener implements AmiCenterClientListener, whose 6 methods are onCenterConnect, onSchemaChanged, onCenterMessage, onCenterMessageBatchDone, onCenterDisconnect, and onUnsubscribed. On a subscription, the callbacks arrive in this order:

  1. onCenterConnect when the connection is ready.
  2. onSchemaChanged with every table on the Center, and again after each subscription.
  3. onCenterMessage with the subscribed rows, each like ADD:<id>:Quotes{sym=IBM, px=183.5}. Later changes arrive as UPD:<id>:Quotes{px=95.0} with the changed columns, and DEL:<id>:Quotes{}.
  4. onCenterMessageBatchDone after each batch.

A refused login on the Center connection is written to the log only: no callback fires, and subscribe returns normally.

Queries

AmiCenterClient can also run SQL, with the same license requirement:

1
2
3
4
5
6
7
8
9
AmiCenterQueryDsRequest request = center.newQueryRequest("SELECT sym, px FROM Quotes");
center.query("C1", request, new AmiCenterQueryResponseListener() {
    public void onQueryResponse(AmiCenterQueryDsRequest r, AmiCenterQueryDsResponse response) {
        System.out.println(response.getOk() + " " + response.getTables());
    }
    public void onQueryError(AmiCenterQueryDsRequest r, Throwable t) {
        t.printStackTrace();
    }
});

A SQL error arrives in onQueryResponse, with getOk() returning false, not in onQueryError.

What this does not support

  • Sending a client certificate from AmiClient by host and port: the host-and-port start forms never send one. A program opens the TLS socket itself, or uses RawAmiClient.
  • Queuing messages while disconnected: AmiClient throws instead.
  • Subscribing or querying without a license: AmiCenterClient needs a license file.
  • Reporting a refused Center login to the listener: the refusal is logged only.