Java API & SDK Docs 10.4.7

Breaking changes in v9.0.0

PubNub Java SDK version 9.0.0 unifies the codebases for Java and Kotlin SDKs, introduces a new way of instantiating the PubNub client, and changes asynchronous API callbacks and emitted status events. These changes can impact applications built with previous versions (< 9.0.0) of the Java SDK.

For more details about what has changed, refer to Java/Kotlin SDK migration guide.

In this guide, we'll create a simple "Hello, World" application that demonstrates the core concepts of PubNub

PubNub

PubNub is a real-time messaging platform that provides APIs and SDKs for building scalable applications. It handles the complex infrastructure of real-time communication, including:

:

  • Setting up a connection
  • Sending messages
  • Receiving messages in real-time

Overview

This guide will help you get up and running with PubNub in your Java application. You'll learn how to set up PubNub, configure event listeners, subscribe to channels, and publish messages in a Java environment.

Chat applications

If you want to create a mobile chat application with PubNub, refer to Kotlin Chat SDK for details on all available chat features.

Prerequisites

Before we dive in, make sure you have:

  • A basic understanding of Java
  • An IDE like IntelliJ IDEA or Eclipse
  • Java 8 or later installed
  • A PubNub account (we'll help you set this up!)

Setup

Get your PubNub keys

First things first – you'll need your PubNub keys to get started. Here's how to get them:

  • Sign in or create an account on the PubNub Admin Portal.
  • Create a new app (or use an existing one).
  • Find your publish

    Publish Key

    A unique identifier that allows your application to send messages to PubNub channels. It's part of your app's credentials and should be kept secure.
    and subscribe

    Subscribe Key

    A unique identifier that allows your application to receive messages from PubNub channels. It's part of your app's credentials and should be kept secure.
    keys in the app's dashboard.

When you create a new app, PubNub automatically generates your first set of keys. While you can use the same keys for development and production, we recommend creating separate keysets for each environment for better security and management.

Install the SDK

SDK version

Always use the latest SDK version to have access to the newest features and avoid security vulnerabilities, bugs, and performance issues.

You can install the PubNub Java SDK in several ways:

Maven

Add the following dependency to your pom.xml:

<dependency>
<groupId>com.pubnub</groupId>
<artifactId>pubnub-gson</artifactId>
<version>10.4.7</version>
</dependency>

Gradle

Add the following to your build.gradle file:

implementation group: 'com.pubnub', name: 'pubnub-gson', version: '10.4.7'

Source code

You can also download the source code directly from GitHub.

Steps

Initialize PubNub

In your Java application, create a new class (e.g., App.java) and initialize PubNub.

Make sure to replace the demo keys with your app's publish and subscribe keys from the Admin Portal.

import com.pubnub.api.PubNubException;
import com.pubnub.api.UserId;
import com.pubnub.api.java.PubNub;
import com.pubnub.api.java.v2.PNConfiguration;

public class App {
private static PubNub pubnub;

public static void main(String[] args) throws PubNubException {
// Initialize PubNub
PNConfiguration.Builder configBuilder = PNConfiguration.builder(new UserId("javaUser"), "demo");
configBuilder.publishKey("demo");
configBuilder.secure(true);
pubnub = PubNub.create(configBuilder.build());

show all 18 lines
PNConfiguration class in Java

From version 10.0.0 of the Java SDK onward, the correct import for the PNConfiguration class is com.pubnub.api.java.v2.PNConfiguration.

For more information, refer to the Configuration section of the SDK documentation.

Set up event listeners

Listeners help your app react to events and messages. You can implement custom app logic to respond to each type of message or event.

There are two main types of listeners you'll need to set up:

  • Status listener - for connection state changes and operational events
  • Event listener - for messages and presence events

Add listeners to handle connection status and incoming messages:

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.pubnub.api.enums.PNStatusCategory;
import com.pubnub.api.java.v2.callbacks.StatusListener;
import com.pubnub.api.java.v2.entities.Channel;
import com.pubnub.api.java.v2.subscriptions.Subscription;
import com.pubnub.api.models.consumer.PNStatus;
import com.pubnub.api.java.v2.callbacks.EventListener;
import com.pubnub.api.models.consumer.message.PNMessageResult;
import com.pubnub.api.models.consumer.presence.PNPresenceEventResult;

// Define a channel
Channel channel = pubnub.channel("myChannel");

// 1. Add a status listener to monitor connection state changes and operational events
show all 70 lines

For more information, refer to the Listeners section of the SDK documentation.

Create a subscription

To receive messages, you need to subscribe to a channel:

import com.pubnub.api.java.v2.entities.Channel;
import com.pubnub.api.java.v2.subscriptions.Subscription;

// Define a channel name
final String channelName = "myChannel";

// Create a channel using the PubNub instance
Channel channel = pubnub.channel(channelName);

// Create a subscription for the channel
Subscription subscription = channel.subscription();

// Subscribe to the channel to start receiving messages
subscription.subscribe();
System.out.println("Subscribed to channel: " + channelName);

You can also subscribe to multiple channels at once using a subscription set:

import java.util.Set;
import java.util.Collections;
import com.pubnub.api.java.v2.subscriptions.SubscriptionSet;
import com.pubnub.api.java.v2.subscriptions.EmptyOptions;

// Create a subscription set with multiple channels
SubscriptionSet subscriptionSet = pubnub.subscriptionSetOf(
Set.of("channel1", "channel2", "channel3"),
Collections.emptySet(),
EmptyOptions.INSTANCE);

// Subscribe to all channels in the set
subscriptionSet.subscribe();

Publish messages

When you publish a message to a channel, PubNub delivers that message to everyone who is subscribed to that channel.

A message can be any type of JSON-serializable data (such as objects, arrays, integers, strings) that is smaller than 32 KiB.

To send a message to a channel, use the publish() method on your channel object:

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;

// Create message payload using Gson
final JsonObject messageJsonObject = new JsonObject();
JsonElement jsonElement = new JsonPrimitive("Hello World");
messageJsonObject.add("msg", jsonElement);

// Publish the message to the channel
channel.publish(messageJsonObject)
.async(result -> {
result.onSuccess(res -> {
System.out.println("Message successfully published with timetoken: " + res.getTimetoken());
}).onFailure(exception -> {
show all 18 lines

You can also publish messages with additional options:

channel.publish(messageJsonObject)
.customMessageType("text-message") // Add a custom message type
.shouldStore(true) // Store the message in history
.meta(metadataObject) // Add metadata for filtering
.async(result -> {
// Handle results
});

For more information, refer to the Publish and Subscribe section of the SDK documentation, and to Publishing a Message.

Run the app

To run your Java application:

  1. Save your complete code in a file like App.java.
  2. Compile the file: javac -cp "path/to/dependencies/*" App.java.
  3. Run the application: java -cp ".:path/to/dependencies/*" App.

You should see output similar to:

PubNub initialized successfully
Subscribed to channel: myChannel
Connected to PubNub
Message to send: {"msg":"Hello World"}
Message successfully published with timetoken: 16789012345678901
Received on channel: myChannel
Received message: {"msg":"Hello World"}
The content of the message is: Hello World

Since you're both publishing and subscribing to the same channel in this example, you'll receive the messages you publish.

Add a delay to prevent the application from exiting immediately:

// Add a delay so the program doesn't exit immediately
// This gives time to receive published messages
try {
System.out.println("Waiting for messages. Program will exit in 60 seconds...");
Thread.sleep(60000); // 60 seconds
} catch (InterruptedException e) {
e.printStackTrace();
}

// Clean up before exiting
pubnub.disconnect();
System.out.println("Disconnected from PubNub");

Complete example

Here's the complete working example that puts everything together:

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import com.pubnub.api.PubNubException;
import com.pubnub.api.UserId;
import com.pubnub.api.enums.PNStatusCategory;
import com.pubnub.api.java.PubNub;
import com.pubnub.api.java.v2.PNConfiguration;
import com.pubnub.api.java.v2.callbacks.StatusListener;
import com.pubnub.api.java.v2.entities.Channel;
import com.pubnub.api.java.v2.subscriptions.Subscription;
import com.pubnub.api.models.consumer.PNStatus;

public class App {
public static void main(String[] args) throws PubNubException {
show all 99 lines

Troubleshooting

If you don't see the expected output, here are some common issues and how to fix them:

IssuePossible Solutions
No connection message
  • Check your internet connection.
  • Verify your publish and subscribe keys are correct.
  • Make sure you're not behind a firewall blocking PubNub's connections.
Message not received
  • Double-check that you're subscribed to the correct channel.
  • Verify that the message was actually sent (check for any error messages).
  • Make sure you're waiting long enough for the message to be delivered.
  • Ensure your message listener is properly set up.
Build errors
  • Ensure you've added the PubNub dependency correctly.
  • Check that you're using a compatible version of Java (Java 8+).
  • Make sure all imports are correct.
  • Verify you're using the right package names (v2 classes).
Gson deserialization errors
  • Check that your message structure matches what you're trying to extract.
  • Use try/catch blocks when processing messages to handle potential JSON parsing exceptions.
Thread exceptions
  • Avoid blocking the main thread with long-running operations.
  • Handle InterruptedException properly when using Thread.sleep().
  • Consider using an executor service for complex applications.

Next steps

Great job! 🎉 You've successfully created your first PubNub Java application. Here are some exciting things you can explore next:

Last updated on