Newer Version Available

This content describes an older version of this product. View Latest

Learn More About EMP Connector

Let’s take a closer look at the components of EMP Connector.

Authenticating

User credential information is passed in to the login function. The login function’s return value is passed in to the main connector class later.

1BayeuxParameters params = login("<username>", "<password>");

For OAuth authentication, use the BayeuxParameters constructor to override the methods in the BayeuxParameters class and provide the token and URL values.

1BayeuxParameters params = new BayeuxParameters() {
2
3    @Override
4    public String bearerToken() {
5        return "<token>";
6    }
7
8    @Override
9    public URL host() {
10        try {
11            return new URL("<URL>");
12        } catch (MalformedURLException e) {
13            throw new IllegalArgumentException(
14                String.format("Unable to create url: %s", argv[0]), e);
15        }
16    }
17};

Listening to Events

To listen to events, the connector uses the Java event in a lambda expression. This statement prints the event message to the output for each received event notification. Place this statement before the statement that subscribes to the topic.

1Consumer<Map<String, Object>> consumer = event -> System.out.println(
2        String.format("Received:\n%s", event));

Subscribing to a Topic

The EmpConnector class is the main class that exposes the functionality of starting a connection and subscribing. The class contains functions to create a connection, subscribe to a topic, cancel a subscription, and stop a connection.

1// Instantiate the EMP connector
2EmpConnector connector = new EmpConnector(params);
3
4// Wait for handshake with Streaming API
5connector.start().get(5, TimeUnit.SECONDS);
6
7// Subscribe to a topic
8// Block and wait for the subscription to succeed for 5 seconds
9TopicSubscription subscription = connector.subscribe("/topic/myTopic", 
10    replayFrom, consumer).get(5, TimeUnit.SECONDS);

To end a subscription, call these functions.

1// Cancel a subscription
2subscription.cancel();
3
4// Stop the connector
5connector.stop();