---
source_url: https://www.pubnub.com/docs/sdks/java/api-reference/misc
title: Utility Methods API for Java SDK
updated_at: 2026-05-20T11:07:01.206Z
sdk_name: PubNub Java SDK
sdk_version: 6.4.5
---

> Documentation Index
> For a curated overview of PubNub documentation, see: https://www.pubnub.com/docs/llms.txt
> For the full list of all documentation pages, see: https://www.pubnub.com/docs/llms-full.txt


# Utility Methods API for Java SDK

PubNub Java SDK, use the latest version: 6.4.5

Install:

```bash
Add PubNub dependency to your build@6.4.5
```

:::warning Breaking changes in v9.0.0
PubNub Java SDK version 9.0.0 unifies the codebases for Java and [Kotlin](https://www.pubnub.com/docs/sdks/kotlin) SDKs, introduces a new way of instantiating the PubNub client, and changes asynchronous API callbacks and emitted [status events](https://www.pubnub.com/docs/sdks/java/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](https://www.pubnub.com/docs/sdks/kotlin/migration-guides/kotlin-v9-migration-guide).
:::

The methods on this page are utility methods that don't fit into other categories.

## Create push payload

This method creates the push payload for use in the appropriate endpoint calls.

### Method(s)

```java
PushPayloadHelper helper = new PushPayloadHelper();
    helper.setApnsPayload(PushPayloadHelper.APNSPayload());
    helper.setFcmPayloadV2(PushPayloadHelper.FCMPayloadV2());
    helper.setCommonPayload(HashMap<String, Object>());

Map<String, Object> payload = helper.build();
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| helper.setApnsPayload() | APNSPayload | Optional |  | Set APNs and APNs2 Payload. Associated devices will receive only the data supplied here within the `pn_apns` key. |
| helper.setFcmPayloadV2() | FCMPayloadV2 | Optional |  | Set FCM Payload V2. Associated devices will receive only the data supplied here within the `pn_fcm` key. |
| helper.setCommonPayload() | Map<String, | Optional |  | Set common Payload. Native PubNub subscribers will receive the data provided here, together with the `pn_apns`, and `pn_fcm` objects. |
| helper.build() | Map<String, | Yes |  | Builds the payload from the values set using the parameters. |

### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

#### Create push payload

```java
import com.pubnub.api.PubNubException;
import com.pubnub.api.java.PubNub;
import com.pubnub.api.java.v2.PNConfiguration;
import com.pubnub.api.UserId;
import com.pubnub.api.enums.PNPushEnvironment;
import com.pubnub.api.java.v2.entities.Channel;
import com.pubnub.api.models.consumer.push.payload.PushPayloadHelper;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class CreatePushPayloadApp {
    public static void main(String[] args) throws PubNubException {
        // Configure PubNub instance
        PNConfiguration.Builder configBuilder = PNConfiguration.builder(new UserId("demoUserId"), "demo");
        configBuilder.publishKey("demo");
        configBuilder.secure(true);

        PubNub pubnub = PubNub.create(configBuilder.build());

        // Create an instance of PushPayloadHelper
        PushPayloadHelper pushPayloadHelper = new PushPayloadHelper();

        // Setup FCM parameters (FCMPayload)
        PushPayloadHelper.FCMPayloadV2 fcmPayload = new PushPayloadHelper.FCMPayloadV2();
        PushPayloadHelper.FCMPayloadV2.Notification fcmNotification = new PushPayloadHelper.FCMPayloadV2.Notification();
        fcmNotification.setTitle("Notification title");
        fcmNotification.setBody("Notification body text");
        fcmNotification.setImage("http://example.com/image.png");
        fcmPayload.setNotification(fcmNotification);

        Map<String, String> fcmData = new HashMap<>();
        fcmData.put("city", "sf");
        fcmData.put("count", "71");
        fcmData.put("is_private", "true");
        fcmData.put("token", "bk3RNwTe3H0:CI2k_HvvDMExdFQ3P1...");
        fcmData.put("topic", "/topic/news/");
        fcmPayload.setData(fcmData);

        // Set FCM payload
        pushPayloadHelper.setFcmPayloadV2(fcmPayload);

        // Setup APNs parameters
        PushPayloadHelper.APNSPayload apnsPayload = new PushPayloadHelper.APNSPayload();
        PushPayloadHelper.APNSPayload.APS aps = new PushPayloadHelper.APNSPayload.APS();
        aps.setAlert("Alert");
        aps.setBadge(1);
        aps.setSound("Ding");
        apnsPayload.setAps(aps);

        PushPayloadHelper.APNSPayload.APNS2Configuration.Target target = new PushPayloadHelper.APNSPayload.APNS2Configuration.Target();
        target.setEnvironment(PNPushEnvironment.DEVELOPMENT);
        target.setTopic("com.meetings.chat.app");
        target.setExcludeDevices(Arrays.asList("device1", "device2"));

        PushPayloadHelper.APNSPayload.APNS2Configuration apns2Configuration = new PushPayloadHelper.APNSPayload.APNS2Configuration();
        apns2Configuration.setCollapseId("invitations");
        apns2Configuration.setExpiration("2019-12-13T22:06:09Z");
        apns2Configuration.setVersion("v1");
        apns2Configuration.setTargets(Arrays.asList(target));

        // Set APNs2 Configurations
        apnsPayload.setApns2Configurations(Arrays.asList(apns2Configuration));

        Map<String, Object> apnsCustom = new HashMap<>();
        apnsCustom.put("apns_key_1", "value_1");
        apnsCustom.put("apns_key_2", "value_2");
        apnsPayload.setCustom(apnsCustom);

        // Set APNS payload
        pushPayloadHelper.setApnsPayload(apnsPayload);

        // Common payload for native PubNub subscribers
        Map<String, Object> commonPayload = new HashMap<>();
        commonPayload.put("message", "Hello");
        commonPayload.put("such", "object");
        commonPayload.put("type", 7);
        pushPayloadHelper.setCommonPayload(commonPayload);

        // Build the payload and publish
        Map<String, Object> payload = pushPayloadHelper.build();

        Channel channel = pubnub.channel("foo");
        channel.publish(payload)
                .async(result -> {
                    result.onSuccess(res -> {
                        System.out.println("Message published successfully.");
                    }).onFailure(exception -> {
                        System.out.println("Error publishing message: " + exception.getMessage());
                    });
                });
    }
}
```

### Response

The `PushPayloadHelper#build()` operation returns a `Map<String, Object>` which can be passed directly as the `message()` parameter to the `pubnub.publish()` method.

## Destroy

Destroy frees up the threads and allows for clean exit.

### Method(s)

```java
destroy()
```

### Sample code

```java
pubNub.destroy();
```

### Returns

None

## Get subscribed channel groups

Returns all the subscribed channel groups in a `List of type String`.

### Method(s)

To `Get Subscribe Channel Groups` you can use the following method(s) in the Java SDK:

```java
public final List<String> getSubscribedChannelGroups()
```

### Sample code

#### Get subscribed channel groups

```java
List<String> groups = pubNub.getSubscribedChannelGroups();
```

### Response

`List<String>`

```json
["channelGroup1", "channelGroup2"]
```

## Get subscribed channels

Returns all the subscribed channels in a `List of type String`.

### Method(s)

To `Get Subscribed Channels` you can use the following method(s) in the Java SDK:

```java
public final List<String> getSubscribedChannels()
```

### Sample code

#### Get subscribed channels

```java
List<String> channels = pubNub.getSubscribedChannels();
```

### Response

`List<String>`

```json
["channel1", "channel2"]
```

## Disconnect

Call the `disconnect` method to force the SDK to stop all requests to PubNub server when there are active subscribe channels.

### Method(s)

To `disconnect` the data transmission you can use the following method(s) in Java SDK.

```java
disconnect()
```

This method doesn't take any arguments.

### Sample code

```java
pubNub.disconnect();
```

## Reconnect

Call the `reconnect` method to force the SDK to try and reach out PubNub.

### Method(s)

To `reconnect` the data you can use the following method(s) in Java SDK.

```java
reconnect(long timetoken)
```

| Parameter | Description |
| --- | --- |
| `timetoken`Type: `long` | Timetoken to reconnect from. |

### Sample code

```java
pubNub.reconnect();
// or
Long timetoken = 17276954606232118L; // Example timetoken received in publish/signal response
pubNub.reconnect(timetoken);
```

## Timetoken to date

The `timetokenToInstant()` method of the `TimetokenUtil` class converts a PubNub timetoken (a unique identifier for each message sent and received in a PubNub channel that is a number of 100-nanosecond intervals since January 1, 1970) to an `Instant` object representing the corresponding date and time.

Use this method when you want to display the timetoken of each message or event in the message history in a human-readable format.

### Method signature

```java
Instant TimetokenUtil.timetokenToInstant(long timetoken)
```

#### Input

| Parameter | Description |
| --- | --- |
| `timetoken` *Type: `long`Default: n/a | Represents the PubNub timetoken to convert into a human-readable date format. |

#### Output

| Type | Description |
| --- | --- |
| `Instant` | The human-readable date representation of the timetoken. |

### Sample code

Convert a timetoken value of `17276954606232118` to a human-readable date and time format.

```java
long timetoken = 17276954606232118L;
Instant instant = TimetokenUtil.timetokenToInstant(timetoken);
LocalDateTime localDateTimeInUTC = LocalDateTime.ofInstant(instant, java.time.ZoneId.of("UTC"));

System.out.println("PubNub timetoken: " + timetoken);
System.out.println("Current date: " + localDateTimeInUTC.toLocalDate());
System.out.println("Current time: " + localDateTimeInUTC.toLocalTime());
```

The output of the method is as follows:

```bash
PubNub timetoken: 17276954606232118
Current date: 2024-09-30
Current time: 11:24:20.623211800
```

## Date to timetoken

The `instantToTimetoken()` method of the `TimetokenUtil` class converts the `Instant` object representing the corresponding date and time into a PubNub timetoken (a unique identifier for each message sent and received in a PubNub channel that is a number of 100-nanosecond intervals since January 1, 1970).

Use this method to represent a specific date and time as a PubNub timetoken value, for example, to retrieve messages from a PubNub channel at a particular date and time.

### Method signature

```java
long TimetokenUtil.instantToTimetoken(Instant instant)
```

#### Input

| Parameter | Description |
| --- | --- |
| `instant` *Type: `Instant`Default: n/a | Represents the date and time to convert into a PubNub timetoken. |

#### Output

| Type | Description |
| --- | --- |
| `long` | Converted timetoken value. |

### Sample code

Convert a human-readable date and time, `September 30, 2024 12:12:24 GMT`, to a timetoken.

```java
LocalDateTime localDateTime = LocalDateTime.of(2024, 9, 30, 12, 12, 44, 123456789); // Example date and time
Instant instant = localDateTime.atOffset(java.time.ZoneOffset.UTC).toInstant();
long timetoken = TimetokenUtil.instantToTimetoken(instant);

System.out.println("Current date: " + localDateTime.toLocalDate());
System.out.println("Current time: " + localDateTime.toLocalTime());
System.out.println("PubNub timetoken: " + timetoken);
```

```bash
Current date: 2024-09-30
Current time: 12:12:44.123456789
PubNub timetoken: 17276983641234567
```

## Unix timestamp to timetoken

The `unixToTimetoken()` method of the `TimetokenUtil` class converts a Unix timestamp (a number of seconds since January 1, 1970) to a PubNub timetoken (a unique identifier for each message sent and received in a PubNub channel that is a number of 100-nanosecond intervals since January 1, 1970).

Use this method when you need a timetoken to [retrieve historical messages](https://www.pubnub.com/docs/sdks/java/api-reference/storage-and-playback) with a specific timestamp range from Message Persistence.

### Method signature

This method takes the following parameters:

```java
long TimetokenUtil.unixToTimetoken(long unixTime)
```

#### Input

| Parameter | Description |
| --- | --- |
| `unixTime` *Type: `long`Default: n/a | Represents the Unix timestamp to convert into a PubNub timetoken. |

#### Output

| Type | Description |
| --- | --- |
| `long` | Converted timetoken value. |

### Sample code

Convert a Unix timestamp value of `1727866935316` representing `2024-10-02 11:02:15.316` to PubNub timetoken:

```java
long unixTime = 1727866935316L;
long timetoken = TimetokenUtil.unixToTimetoken(unixTime);
Instant instant = TimetokenUtil.timetokenToInstant(timetoken);
LocalDateTime localDateTimeInUTC = LocalDateTime.ofInstant(instant, java.time.ZoneId.of("UTC"));

System.out.println("PubNub timetoken: " + timetoken);
System.out.println("Current date: " + localDateTimeInUTC.toLocalDate());
System.out.println("Current time: " + localDateTimeInUTC.toLocalTime());
```

The output of the method is as follows:

```bash
PubNub timetoken: 17278669353160000
Current date: 2024-10-02
Current time: 11:02:15.316
```

## Timetoken to Unix timestamp

The `timetokenToUnix()` method of the `TimetokenUtil` class converts a PubNub timetoken (a unique identifier for each message sent and received in a PubNub channel that is a number of 100-nanosecond intervals since January 1, 1970) to a Unix timestamp (a number of seconds since January 1, 1970).

Use this method to convert PubNub timetoken for use in another context or system that requires a Unix timestamp.

### Method signature

```java
long TimetokenUtil.timetokenToUnix(long timetoken)
```

#### Input

| Parameter | Description |
| --- | --- |
| `timetoken` *Type: `long`Default: n/a | Represents the PubNub timetoken to convert into a Unix timestamp. |

#### Output

| Type | Description |
| --- | --- |
| `long` | Converted Unix timestamp value. |

### Sample code

Convert a PubNub timetoken `17276954606232118` representing `2024-09-30 11:24:20.623211800` to Unix time:

```java
long timetoken = 17276954606232118L;
long unixTime = TimetokenUtil.timetokenToUnix(timetoken);
Instant instant = Instant.ofEpochMilli(unixTime);
LocalDateTime localDateTime = instant.atZone(java.time.ZoneOffset.UTC).toLocalDateTime();

System.out.println("Current date: " + localDateTime.toLocalDate());
System.out.println("Current time: " + localDateTime.toLocalTime());
System.out.println("PubNub timetoken: " + timetoken);
```

The output of the method is as follows:

```bash
Current date: 2024-09-30
Current time: 11:24:20.623
PubNub timetoken: 17276954606232118
```