Just a second...

Start subscribing with Java

Create a Java™ client within minutes that connects to Diffusion™ Cloud. This example creates a client that prints the value of a topic to the console when the topic is updated.

To complete this example, you need a Diffusion Cloud service. For more information about getting a Diffusion Cloud service, see Getting started with Diffusion Cloud.

You also require either a named user that has a role with the select_topic and read_topic permissions or that anonymous client connections are assigned a role with the select_topic and read_topic permissions. For example, the "CLIENT" role. For more information about roles and permissions, see Role-based authorization.

This example steps through the lines of code required to subscribe to a topic. There are several different topic types which provide data in different formats. This example shows you how to subscribe to a JSON topic. The full code example is provided after the steps.
  1. Include the client jar file on the build classpath of your Java client. You can use one of the following methods:
    • You can use Maven to declare the dependency. First add the Push Technology public repository to your pom.xml file:
      <repositories>
          <repository>
              <id>push-repository</id>
              <url>https://download.pushtechnology.com/maven/</url>
          </repository>
      </repositories>
      Next declare the following dependency in your pom.xml file:
      <dependency>
          <groupId>com.pushtechnology.diffusion</groupId>
          <artifactId>diffusion-client</artifactId>
          <version>6.7.4</version>
      </dependency>

      Where version is the Diffusion Cloud version, for example 6.7.4.

    • If you are not using Maven, you can include the diffusion-client-version.jar file that is located here: Download the Java client libraries.
    A diffusion-api-version.jar is also provided. This file contains only the development interfaces without any client library capabilities and can be used for developing and compiling your Java clients. However, to run your Diffusion Java client you must use the diffusion-client-version.jar file.
  2. Create a client class that imports the following packages and classes:
    import com.pushtechnology.diffusion.client.Diffusion;
    import com.pushtechnology.diffusion.client.content.Content;
    import com.pushtechnology.diffusion.client.features.Topics;
    import com.pushtechnology.diffusion.client.features.Topics.ValueStream;
    import com.pushtechnology.diffusion.client.session.Session;
    import com.pushtechnology.diffusion.client.topics.details.TopicSpecification;
    import com.pushtechnology.diffusion.datatype.json.JSON;
    
    public class SubscribingClient {
    
    }
  3. Create a main method for the client.
    public class SubscribingClient {
              public static void main(String... arguments) throws Exception {
              
    }
  4. In the main method, connect to Diffusion Cloud.
            // Connect anonymously
            // Replace 'host' with your hostname
            final Session session = Diffusion.sessions().open("ws://localhost:80");
    Or you can connect securely, using Secure Sockets Layer (SSL):
            final Session session = Diffusion.sessions().open("wss://host:443");
    Or you can connect with a principal and credentials if that principal is assigned a role with the read_topic permission:
        final Session session = Diffusion.sessions().principal("principal")
        .password("password").open("wss://host:443");
    Replace the host, principal, and password values with your own information.
  5. Next, in the main method, get the Topics feature.
            // Get the Topics feature to subscribe to topics
            final Topics topics = session.feature(Topics.class);
    The Topics feature enables a client to subscribe to a topic or fetch its state. For more information, see .
  6. Within the SubscribingClient class, create an inner class that extends ValueStream.Default<JSON> and overrides the onValue method.
    This inner class defines the behavior that occurs when a topic that the client subscribes to is updated. In this example, the value stream prints the topic name and the value of the update to the console.
        private static class ValueStreamPrintLn extends ValueStream.Default<Content> {
            @Override
            public void onValue(
                String topicPath,
                TopicSpecification specification,
                Content oldValue,
                Content newValue) {
                System.out.println(topicPath + ":   " + newValue.asString());
            }
        }
  7. Back in the main method of the SubscribingClient class, use the addStream method to associate an instance of the value stream that you created with the JSON topic you want to subscribe to.
    // Add a new stream for 'foo/counter'
              topics.addStream("foo/counter", JSON.class, new Topics.ValueStream.Default<JSON>() {
                @Override
                public void onSubscription(String topicPath, TopicSpecification specification) {
                  System.out.println("Subscribed to: " + topicPath);
                }
                
                @Override
                public void onValue(String topicPath, TopicSpecification specification, JSON oldValue, JSON newValue) {
                  System.out.println(topicPath + " : " + newValue.toJsonString());
                }
              });
  8. Next, use the subscribe method to subscribe to the topic foo/counter.
            // Subscribe to the topic 'foo/counter'
            topics.subscribe("foo/counter", new Topics.CompletionCallback.Default());
  9. Use a Thread.sleep() to hold the client open for a minute while the updates are received and output.
            // Wait for a minute while the stream prints updates
            Thread.sleep(60000);
  10. Compile and run your client.
    Ensure that the diffusion-client-version.jar file is included in your compiled client or on its classpath.
    We recommend that you run your client using the Java Development Kit (JDK) rather than the Java Runtime Environment (JRE). The JDK includes additional diagnostic capabilities that might be useful.

The client outputs the value to the console every time the value of the foo/counter topic is updated. You can update the value of the foo/counter topic by using the Diffusion Cloud Dashboard's test client or by creating a publishing client to update the topic. To create and publish to the foo/counter topic, you require a user with the modify_topic and update_topic permissions. For more information, see Start publishing with Java.

Full example

The completed SubscribingClient class contains the following code:
import com.pushtechnology.diffusion.client.Diffusion;
import com.pushtechnology.diffusion.client.Diffusion;
import com.pushtechnology.diffusion.client.content.Content;
import com.pushtechnology.diffusion.client.features.Topics;
import com.pushtechnology.diffusion.client.features.Topics.ValueStream;
import com.pushtechnology.diffusion.client.session.Session;
import com.pushtechnology.diffusion.client.topics.details.TopicSpecification;
import com.pushtechnology.diffusion.datatype.json.JSON;

/**
 * A client that subscribes to the topic 'foo/counter.
 *
 * @author Push Technology Limited
 * @since 5.9
 */
public class SubscribingClient {

    /**
     * Main.
     */
    public static void main(String... arguments) throws Exception {

        // Connect anonymously
        // Replace 'host' with your hostname
        final Session session = Diffusion.sessions().open("ws://host:80");

        // Get the Topics feature to subscribe to topics
        final Topics topics = session.feature(Topics.class);

        // Add a new stream for 'foo/counter'
        topics.addStream("foo/counter", JSON.class, new Topics.ValueStream.Default<JSON>() {
            @Override
            public void onSubscription(String topicPath, TopicSpecification specification) {
                System.out.println("Subscribed to: " + topicPath);
            }

            @Override
            public void onValue(String topicPath, TopicSpecification specification, JSON oldValue, JSON newValue) {
                System.out.println(topicPath + " : " + newValue.toJsonString());
            }
        });

        // Subscribe to the topic 'foo/counter'
        topics.subscribe("foo/counter", new Topics.CompletionCallback.Default());

        // Wait for a minute while the stream prints updates
        Thread.sleep(60000);
    }

    /**
     * A topic stream that prints updates to the console.
     */
    private static class ValueStreamPrintLn extends ValueStream.Default<Content> {
        @Override
        public void onValue(
            String topicPath,
            TopicSpecification specification,
            Content oldValue,
            Content newValue) {
            System.out.println(topicPath + ":   " + newValue.asString());
        }
    }
}