Give Feedback for the page

JavaJava V4 API Reference for Realtime Apps

 

These docs are for PubNub 4.0 for Java which is our latest and greatest! For the docs of the older versions of the SDK, please check PubNub 3.0 for Java and PubNub 3.0 for Android.

If you have questions about the PubNub for Java SDK, please contact us at support@pubnub.com.

Java V4 complete API reference for building Realtime Applications on PubNub, including basic usage and sample code.

PNConfiguration instance is storage for user-provided information which describe further PubNub client behaviour. Configuration instance contain additional set of properties which allow to perform precise PubNub client configuration.
To create configuration instance you can use the following function in the Java V4 SDK:
  1. PropertiesTypeRequiredDefaultsDescription
    setSubscribeKeyStringYessubscribeKey from admin panel.
    setPublishKeyStringOptionalpublishKey from admin panel (only required if publishing).
    setSecretKeyStringOptionalsecretKey (only required for access operations, keep away from Android).
    setCipherKeyStringOptionalIf cipher is passed, all communicatons to/from PubNub will be encrypted.
    setUuidStringOptionalSDK generated uuidUUID to be used as a device identifier, a default UUID is generated if not passed.
    setLogVerbosityPNLogVerbosityOptionalPNLogVerbosity.NONESet PNLogVerbosity.BODY to enable debugging. To disable debugging use the option PNLogVerbosity.NONE
    setAuthKeyStringOptionalNot setIf Access Manager is utilized, client will use this authKey in all restricted requests.
    setCacheBustingBooleanOptionalIf operating behind a misbehaving proxy, allow the client to shuffle the subdomains.
    setSecureBooleanOptionaltrueUse SSL.
    setConnectTimeoutIntOptional5How long to wait before giving up connection to client.
    setSubscribeTimeoutIntOptional310How long to keep the subscribe loop running before disconnect.
    setNonSubscribeRequestTimeoutIntOptional10On non subscribe operations, how long to wait for server response.
    setFilterExpressionStringOptionalNot setFeature to subscribe with a custom filter expression.
    setHeartbeatNotificationOptionsPNHeartbeatNotificationOptionsOptionalPNHeartbeatNotificationOptions.FAILURES

    Heartbeat notifications, by default, the SDK will alert on failed heartbeats (equivalent to: PNHeartbeatNotificationOptions.FAILURES).

    Other options such as all heartbeats (PNHeartbeatNotificationOptions.ALL) or no heartbeats (PNHeartbeatNotificationOptions.NONE) are supported.

    setOriginStringOptionalCustom origin if needed.
    setReconnectionPolicyPNReconnectionPolicyOptionalPNReconnectionPolicy.NONE

    Set to PNReconnectionPolicy.LINEAR for automatic reconnects. Use option PNReconnectionPolicy.NONE to disable automatic reconnects.


    Use option PNReconnectionPolicy.EXPONENTIAL to set exponential retry interval.

    setPresenceTimeoutIntOptional0The setting with set the custom presence server timeout.
    setPresenceTimeoutWithCustomIntervalIntOptional0The setting with set the custom presence server timeout along with the custom interval to send the ping back to the server.
    setProxyProxyOptionalInstruct the SDK to use a proxy configuration when communicating with PubNub servers.
    setMaximumReconnectionRetriesIntOptionalinfinityThe config sets how many times to retry to reconnect before giving up.
PNConfiguration pnConfiguration = new PNConfiguration();
// subscribeKey from admin panel
pnConfiguration.setSubscribeKey("SubscribeKey"); // required
// publishKey from admin panel (only required if publishing)
pnConfiguration.setPublishKey("PublishKey"); 
// secretKey (only required for access operations, keep away from Android)
pnConfiguration.setSecretKey("SecretKey");
// if cipherKey is passed, all communicatons to/from pubnub will be encrypted
pnConfiguration.setCipherKey("cipherKey");
// UUID to be used as a device identifier, a default UUID is generated 
// if not passed
pnConfiguration.setUuid("customUUID");
// Enable Debugging
pnConfiguration.setLogVerbosity(PNLogVerbosity.BODY);
// if Access Manager is utilized, client will use this authKey in all restricted
// requests
pnConfiguration.setAuthKey("authKey");
// use SSL.
pnConfiguration.setSecure(true);
// how long to wait before giving up connection to client
pnConfiguration.setConnectTimeout(100);
// how long to keep the subscribe loop running before disconnect
pnConfiguration.setSubscribeTimeout(310);
// on non subscribe operations, how long to wait for server response
pnConfiguration.setNonSubscribeRequestTimeout(300);
// PSV2 feature to subscribe with a custom filter expression
pnConfiguration.setFilterExpression("such=wow");
// heartbeat notifications, by default, the SDK will alert on failed heartbeats.
// other options such as all heartbeats or no heartbeats are supported.
pnConfiguration.setHeartbeatNotificationOptions(PNHeartbeatNotificationOptions.All);
pnConfiguration.setPresenceTimeoutWithCustomInterval(120,59);
pnConfiguration.setPresenceTimeout(120);
Add PubNub to your project using one of the procedures defined under How to Get It.
This function is used for initializing the PubNub Client API context. This function must be called before attempting to utilize any API functionality in order to establish account level credentials such as publishKey and subscribeKey.
To Initialize Pubnub you can use the following method(s) in the Java V4 SDK:
  1. ParameterTypeRequiredDescription
    pnConfigurationPNConfigurationYesGoto Configuration for more details.
PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.setSubscribeKey("my_subkey");
pnConfiguration.setPublishKey("my_pubkey");
pnConfiguration.setSecure(true);  

PubNub pubnub = new PubNub(pnConfiguration);
It returns the Pubnub instance for invoking PubNub APIs like publish(), subscribe(), history(), hereNow(), etc.
  1. PNConfiguration pnConfiguration = new PNConfiguration();
    pnConfiguration.setSubscribeKey("SubscribeKey");
    pnConfiguration.setPublishKey("PublishKey");
    pnConfiguration.setSecure(false);
      
    PubNub pubnub = new PubNub(pnConfiguration);
  2. In the case where a client will only read messages and never publish to a channel, you can simply omit the publishKey when initializing the client:
    PNConfiguration pnConfiguration = new PNConfiguration();
    pnConfiguration.setSubscribeKey("my_subkey");
    PubNub pubnub = new PubNub(pnConfiguration);
  3. Under certain circumstances it useful to use a custom UUID to help in identifying your users.
    PNConfiguration pnConfiguration = new PNConfiguration();
    pnConfiguration.setSubscribeKey("my_subkey");
    pnConfiguration.setPublishKey("my_pubkey");
    pnConfiguration.setUuid("Stephen");  
    PubNub pubnub = new PubNub(pnConfiguration);
    
  4. This examples demonstrates how to enable PubNub Transport Layer Encryption with SSL. Just initialize the client with ssl set to true. The hard work is done, now the PubNub API takes care of the rest. Just subscribe and publish as usual and you are good to go.
    PNConfiguration pnConfiguration = new PNConfiguration();
    pnConfiguration.setSubscribeKey("my_subkey");
    pnConfiguration.setPublishKey("my_pubkey");
    pnConfiguration.setSecure(true);  
    
    PubNub pubnub = new PubNub(pnConfiguration);
  5. For applications that will administer PAM permissions, the API is initialized with the secretKey as in the following example:
    PNConfiguration pnConfiguration = new PNConfiguration();
    pnConfiguration.setSubscribeKey("my_subkey");
    pnConfiguration.setPublishKey("my_pubkey");
    pnConfiguration.setSecretKey("my_secretkey");
    pnConfiguration.setSecure(true);  
    
    PubNub pubnub = new PubNub(pnConfiguration);
    
    Now that the pubnub object is instantiated the client will be able to access the PAM functions. The pubnub object will use the secretKey to sign all PAM messages to the PubNub Network.
     
    Anyone with the secretKey can grant and revoke permissions to your app. Never let your secretKey be discovered, and to only exchange it / deliver it securely. Only use the secretKey on secure server-side platforms.
These functions are used to set/get a user ID on the fly.
To set/get UUID you can use the following method(s) in Java V4 SDK
  1. ParameterTypeRequiredDefaultsDescription
    uuidStringYesSDK generated uuidUUID to be used as a device identifier, a default UUID is generated if not passed.
  2. This method doesn't take any arguments.
PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.setUuid("customUUID");
PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.getUuid();
Setter and getter for users auth key.
  1. ParameterTypeRequiredDescription
    Auth KeyStringYesIf Access Manager is utilized, client will use this authKey in all restricted requests.
  2. This method doesn't take any arguments.
PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.setAuthKey("authKey");
pnConfiguration.getAuthKey();
None.
To set/get filters you can use the following methods.
  1. ParameterTypeRequiredDescription
    filterExpressionStringYesPSV2 feature to subscribe with a custom filter expression
  2. This method doesn't take any arguments.
PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.setFilterExpression("such=wow");
pnConfiguration.getFilterExpression();
The publish() function is used to send a message to all subscribers of a channel. To publish a message you must first specify a valid publishKey at initialization. A successfully published message is replicated across the PubNub Real-Time Network and sent simultaneously to all subscribed clients on a channel.
Messages in transit can be secured from potential eavesdroppers with SSL/TLS by setting ssl to true during initialization.
 
Publish Anytime
It is not required to be subscribed to a channel in order to publish to that channel.
Message Data:
The message argument can contain any JSON serializable data, including: Objects, Arrays, Ints and Strings. Message data should not contain special Java V4 classes or functions as these will not serialize. String content can include any single-byte or multi-byte UTF-8 character.
Message Size:
The maximum number of characters per message is 32K by default. The maximum message size is based on the final escaped character count, including the channel name. An ideal message size is under 1800 bytes which allows a message to be compressed and sent using single IP datagram (1.5KB) providing optimal network performance.
If the message you publish exceeds the configured size, you will receive the following message:
Message Too Large Error
["PUBLISHED",[0,"Message Too Large","13524237335750949"]]
Message Publish Rate:
Messages can be published as fast as bandwidth conditions will allow. There is a soft limit based on max throughput since messages will be discarded if the subscriber cannot keep pace with the publisher.
For example, if 200 messages are published simultaneously before a subscriber has had a chance to receive any messages, the subscriber may not receive the first 100 messages because the message queue has a limit of only 100 messages stored in memory.
Publishing to Multiple Channels.
It is not possible to publish a message to multiple channels simultaneously. The message must be published to one channel at a time.
Publishing Messages Reliably.
There are some best practices to ensure messages are delivered when publishing to a channel:
  • Publish to any given channel in a serial manner (i.e. not concurrently).
  • Check that the return code is success (e.g. [1,"Sent","136074940..."])
  • Publish the next message only after receiving a success return code.
  • If a failure code is returned ([0,"blah","<timetoken>"]), retry the publish.
  • Avoid exceeding the in-memory queue's capacity of 100 messages. An overflow situation (aka missed messages) can occur if slow subscribers fail to keep up with the publish pace in a given period of time.
  • Throttle publish bursts in accordance with your app's latency needs e.g. Publish no faster than 5 msgs per second to any one channel.
 
Do Not JSON serialize!
It is important to note that you should not JSON serialize when sending signals/messages via PUBNUB. Why? Because the serialization is done for you automatically. Instead just pass the full object as the message payload. PubNub takes care of everything for you.
 

Single string messages are automatically sent to APNS if mobile push is enabled and devices are registered for push on that channel. So if you use encryption (cipher key in the init) and publish the message, then it will be sent to APNS if there is a device(s) registered to that channel.

This is a legacy feature and will be deprecated soon.

To Publish a message you can use the following method(s) in the Java V4 SDK:
  1. ParameterTypeRequiredDefaultsDescription
    messageObjectYesThe payload.
    channelStringYesDestination of the message.
    shouldStoreBooleanOptionalaccount default

    Store in history.

    If shouldStore is not specified, then the history configuration on the key is used.

    metaObjectOptionalNot setMeta data object which can be used with the filtering ability.
    usePOSTBooleanOptional falseUse POST to publish.
    ttlIntegerOptional
    Set a per message time to live in storage.
    1. If shouldStore = true, and ttl = 0, the message stored with no expiry time.
    2. If shouldStore = true and ttl = X (X is an Integer value), the message is stored with an expiry time of X hours.
    3. If shouldStore = false, the ttl parameter is ignored.
    4. If ttl is not specified, then expiration of the message defaults back to the expiry value for the key.
    syncCommandOptionalBlock the thread, exception thrown if something goes wrong.
    asyncPNCallbackOptionalPNCallback of type PNPublishResult

Publish a message to a channel:

pubnub.publish()
    .message(Arrays.asList("hello", "there"))
    .channel("my_channel")
    .shouldStore(true)
    .usePOST(true)
    .async(new PNCallback<PNPublishResult>() {
        @Override
        public void onResponse(PNPublishResult result, PNStatus status) {
            if (status.isError()) {
                // something bad happened.
                System.out.println("error happened while publishing: " + status.toString());
            } else {
                System.out.println("publish worked! timetoken: " + result.getTimetoken());
            }
        }
    });
 
Before running the above publish example, either using the Debug Console, or in a separate script running in a separate terminal window, subscribe to the same channel that is being published to.
The publish() operation returns a PNPublishResult which contains the following operations:
MethodTypeDescription
getTimetoken()LongReturns a long representation of the time token when the message was published.
  1. pubnub.publish()
        .message(Arrays.asList("hello", "there"))
        .channel("suchChannel")
        .shouldStore(true)
        .meta(<Object>) // optional meta data object which can be used with the filtering ability.
        .usePOST(true)
        .async(new PNCallback<PNPublishResult>() {
            @Override
            public void onResponse(PNPublishResult result, PNStatus status) {
                // handle publish result, status always present, result if successful
                // status.isError to see if error happened
            }
        });
  2. JsonObject position = new JsonObject();
    position.addProperty("lat", 32L);
    position.addProperty("lng", 32L);
    
    System.out.println("before pub: " + position);
    pubnub.publish()
        .message(position)
        .channel("my_channel")
        .async(new PNCallback<PNPublishResult>() {
            @Override
            public void onResponse(PNPublishResult result, PNStatus status) {
                // handle publish result, status always present, result if successful
                // status.isError() to see if error happened
                if(!status.isError()) {
                    System.out.println("pub timetoken: " + result.getTimetoken());
                }
                System.out.println("pub status code: " + status.getStatusCode());
            }
        });
  3. JsonArray position = new JsonArray();
    position.add(32L);
    
    System.out.println("before pub: " + position);
    pubnub.publish()
        .message(position)
        .channel("my_channel")
        .async(new PNCallback<PNPublishResult>() {
            @Override
            public void onResponse(PNPublishResult result, PNStatus status) {
                //  handle publish result, status always present, result if successful
                //  status.isError to see if error happened
                if(!status.isError()) {
                    System.out.println("pub timetoken: " + result.getTimetoken());
                }
                System.out.println("pub status code: " + status.getStatusCode());
            }
        });
  4. JSONObject position = new JSONObject();
    position.put("lat", 32L);
    position.put("lng", 32L);
    
    System.out.println("before pub: " + position);
    pubnub.publish()
        .message(position.toMap())
        .channel("my_channel")
        .async(new PNCallback<PNPublishResult>() {
            @Override
            public void onResponse(PNPublishResult result, PNStatus status) {
                // handle publish result, status always present, result if successful
                // status.isError to see if error happened
                if(!status.isError()) {
                    System.out.println("pub timetoken: " + result.getTimetoken());
                }
                System.out.println("pub status code: " + status.getStatusCode());
            }
        });
  5. JSONArray position = new JSONArray();
    position.put(32L);
    
    System.out.println("before pub: " + position);
    pubnub.publish()
        .message(position.toList())
        .channel("my_channel")
        .async(new PNCallback<PNPublishResult>() {
            @Override
            public void onResponse(PNPublishResult result, PNStatus status) {
                //  handle publish result, status always present, result if successful
                //  status.isError to see if error happened
                if(!status.isError()) {
                    System.out.println("pub timetoken: " + result.getTimetoken());
                }
                System.out.println("pub status code: " + status.getStatusCode());
            }
        });
  6. PNPublishResult result = pubnub.publish()
                                 .channel("coolChannel")
                                 .message("test")
                                 .shouldStore(true)
                                 .ttl(10)
                                 .sync();
The fire endpoint allows the client to send a message to BLOCKS Event Handlers. These messages will go directly to any Event Handlers registered on the channel that you fire to and will trigger their execution. The content of the fired request will be available for processing within the Event Handler. The message sent via fire() is not replicated, and so will not be received by any subscribers to the channel. The message is also not stored in history.
To Fire a message you can use the following method(s) in the Java V4 SDK:
  1. ParameterTypeRequiredDefaultsDescription
    messageObjectYesThe payload.
    channelStringYesDestination of the message.
    metaObjectOptionalNot setMeta data object which can be used with the filtering ability.
    usePOSTBooleanOptional falseUse POST to publish.
    syncCommandOptionalBlock the thread, exception thrown if something goes wrong.
    asyncPNCallbackOptionalPNCallback of type PNPublishResult

Fire a message to a channel:

pubnub.fire()
    .message(Arrays.asList("hello", "there"))
    .channel("my_channel")
    .usePOST(true)
    .async(new PNCallback<PNPublishResult>() {
        @Override
        public void onResponse(PNPublishResult result, PNStatus status) {
            if (status.isError()) {
                // something bad happened.
                System.out.println("error happened while publishing: " + status.toString());
            } else {
                System.out.println("publish worked! timetoken: " + result.getTimetoken());
            }
        }
    });
This function causes the client to create an open TCP socket to the PubNub Real-Time Network and begin listening for messages on a specified channel. To subscribe to a channel the client must send the appropriate subscribeKey at initialization.
By default a newly subscribed client will only receive messages published to the channel after the subscribe() call completes.
If a client gets disconnected from a channel, it can automatically attempt to reconnect to that channel and retrieve any available messages that were missed during that period. This can be achieved by setting setReconnectionPolicy to PNReconnectionPolicy.LINEAR, when initializing the client.
To Subscribe to a channel you can use the following method(s) in the Java V4 SDK:
  1. ParameterTypeRequiredDescription
    channelsArrayOptionalSubscribe to channels, Either channel or channelGroup is required
    channelGroupsArrayOptionalSubscribe to channel groups, Either channel or channelGroup is required
    withTimetokenLongOptionalPass a timetoken
    withPresence()CommandOptionalAlso subscribe to related presence information
    execute()CommandYesCommand that will execute subscribe.
Subscribe to a channel:
pubnub.subscribe()
    .channels(Arrays.asList("my_channel")) // subscribe to channels
    .execute();
The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method.
 

PNMessageResult is returned in the Listeners.

The subscribe() operation returns a PNMessageResult for messages which contains the following operations:
MethodTypeDescription
getMessage()JsonElementThe message sent on the channel.
getSubscription()StringThe channel group or wildcard subscription match (if exists).
getChannel()StringThe channel for which the message belongs.
getTimetoken()LongTimetoken for the message.
getUserMetadata()ObjectUser metadata.
The subscribe() operation returns a PNPresenceEventResult from presence which contains the following operations:
MethodTypeDescription
getEvent()StringEvents like join, leave, timeout, state-change, interval.
getUuid()StringUUID for the event.
getTimestamp()LongTimestamp for the event.
getOccupancy()IntCurrent occupancy.
getState()JsonElementState of the UUID.
getSubscription()StringThe channel group or wildcard subscription match (if exists).
getChannel()StringThe channel for which the message belongs.
getTimetoken()LongTimetoken of the message.
getUserMetadata()ObjectUser metadata.
  1. PNConfiguration pnConfiguration = new PNConfiguration();
    // subscribeKey from admin panel
    pnConfiguration.setSubscribeKey("my_subkey"); // required
    // publishKey from admin panel (only required if publishing)
    pnConfiguration.setPublishKey("my_pubkey");
    pnConfiguration.setLogVerbosity(PNLogVerbosity.BODY);
    PubNub pubnub = new PubNub(pnConfiguration);
    
    pubnub.subscribe()
        .channels(Arrays.asList("my_channel")) // subscribe to channels information
        .execute();
  2. It is possible to subscribe to more than one channel over a single TCP socket by taking advantage of Multiplexing feature. See the Multiplexing section for more info on this feature as well as the examples below using a list or an array to specify channel name.
    pubnub.subscribe()
        .channels(Arrays.asList("my_channel1","my_channel2" )) // subscribe to channels information
        .execute();
  3. For any given channel there is an associated Presence channel. You can subscribe directly to the channel by appending -pnpres to the channel name. For example the channel named my_channel would have the presence channel named my_channel-pnpres.
    pubnub.subscribe()
        .channels(Arrays.asList("my_channel")) // subscribe to channels
        .withPresence() // also subscribe to related presence information
        .execute();
    {
    	"action": "join",
    	"timestamp": 1345546797,
    	"uuid": "175c2c67-b2a9-470d-8f4b-1db94f90e39e",
    	"occupancy": 2
    }
    
    {
        "action" : "leave",
        "timestamp" : 1345549797,
        "uuid" : "175c2c67-b2a9-470d-8f4b-1db94f90e39e",
        "occupancy" : 1
    }
    {
    	"action": "timeout",
    	"timestamp": 1345549797,
    	"uuid": "76c2c571-9a2b-d074-b4f8-e93e09f49bd",
    	"occupancy": 0
    }
    
    {
    	"action": "state-change",
    	"uuid": "76c2c571-9a2b-d074-b4f8-e93e09f49bd",
    	"timestamp": 1345549797,
    	"data": {
    		"isTyping": true
    	}
    }
    
    {
    	"action":"interval",
    	"timestamp":1474396578,
    	"occupancy":2
    }
    

    When a channel is in interval mode with presence_deltas pnconfig flag enabled, the interval message may also include the following fields which contain an array of changed UUIDs since the last interval message.

    • joined
    • left
    • timedout

    For example, this interval message indicates there were 2 new UUIDs that joined and 1 timed out UUID since the last interval:

    {
        "action" : "interval",
        "occupancy" : <# users in channel>,
        "timestamp" : <unix timestamp>,
        "joined" : ["uuid2", "uuid3"],
        "timedout" : ["uuid1"]
    }
    

    If the full interval message is greater than 30KB (since the max publish payload is ∼32KB), none of the extra fields will be present. Instead there will be a here_now_refresh boolean field set to true. This indicates to the user that they should do a hereNow request to get the complete list of users present in the channel.

    {
        "action" : "interval",
        "occupancy" : <# users in channel>,
        "timestamp" : <unix timestamp>,
        "here_now_refresh" : true
    }
    
  4. Wildcard subscribes allow the client to subscribe to multiple channels using wildcard. E.g., if you subscribe to a.* you will get all messages for a.b, a.c, a.x. The wildcarded * portion refers to any portion of the channel string name after the dot (.).
    pubnub.subscribe()
    	.channels(Arrays.asList("foo.*")) // subscribe to channels information
    	.execute();
  5. You can set state for a uuid during a subscribe by using the state parameter. Simply specify the desired key/value pairs as a JSON object.
    PNConfiguration pnConfiguration = new PNConfiguration();
    pnConfiguration.setSubscribeKey("demo");
    pnConfiguration.setPublishKey("demo");
    
    
    class complexData {
    	String fieldA;
    	int fieldB;
    }
    
    PubNub pubnub= new PubNub(pnConfiguration);
    
    pubnub.addListener(new SubscribeCallback() {
    	@Override
    	public void status(PubNub pubnub, PNStatus status) {
    		if (status.getCategory() == PNStatusCategory.PNConnectedCategory){
    			complexData data = new complexData();
    			data.fieldA = "Awesome";
    			data.fieldB = 10;
    			pubnub.setPresenceState()
    				.channels(Arrays.asList("awesomeChannel"))
    				.channelGroups(Arrays.asList("awesomeChannelGroup"))
    				.state(data).async(new PNCallback<PNSetStateResult>() {
    					@Override
    					public void onResponse(PNSetStateResult result, PNStatus status) {
    						// handle set state response
    					}
    				});
    		}
    	}
    
    	@Override
    	public void message(PubNub pubnub, PNMessageResult message) {
    
    	}
    
    	@Override
    	public void presence(PubNub pubnub, PNPresenceEventResult presence) {
    
    	}
    });
    
    pubnub.subscribe().channels(Arrays.asList("awesomeChannel"));
  6. pubnub.subscribe()
        .channels(Arrays.asList("ch1", "ch2")) // subscribe to channels
        .channelGroups(Arrays.asList("cg1", "cg2")) // subscribe to channel groups
        .withTimetoken(1337L) // optional, pass a timetoken
        .withPresence() // also subscribe to related presence information
        .execute();
  7. pubnub.subscribe()
        .channelGroups(Arrays.asList("cg1", "cg2")) // subscribe to channel groups
        .withTimetoken(1337L) // optional, pass a timetoken
        .withPresence() // also subscribe to related presence information
        .execute();
When subscribed to a single channel, this function causes the client to issue a leave from the channel and close any open socket to the PubNub Network. For multiplexed channels, the specified channel(s) will be removed and the socket remains open until there are no more channels remaining in the list.
To Unsubscribe from a channel you can use the following method(s) in the Java V4 SDK
  1. ParameterTypeRequiredDescription
    channelsArrayOptionalUnsubscribe to channels, Either channel or channelGroup is required
    channelGroupsArrayOptionalUnsubscribe to channel groups, Either channel or channelGroup is required
    execute()CommandYesCommand that will execute unsubscribe.
Unsubscribe from a channel:
pubnub.unsubscribe()
    .channels(Arrays.asList("my_channel"))
    .execute();
The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method.
The output below demonstrates the response to a successful call:
{
	"action" : "leave"
}
  1. pubnub.unsubscribe()
        .channels(Arrays.asList("ch1", "ch2", "ch3"))
        .channelGroups(Arrays.asList("cg1", "cg2", "cg3"))
        .execute();
    {
    	"action" : "leave"
    }
    
  2. pubnub.unsubscribe()
        .channelGroups(Arrays.asList("cg1", "cg2", "cg3"))
        .execute();
    {
    	"action": "leave"
    }
    
Unsubscribe from all channels and all channel groups
  • public final void unsubscribeAll()
pubnub.unsubscribeAll();
None

You can be notified of connectivity status, message and presence notifications via the listeners.

Listeners should be added before calling the method.

pubnub.addListener(new SubscribeCallback() {
    @Override
    public void status(PubNub pubnub, PNStatus status) {
        if (status.getOperation() != null) {
            switch (status.getOperation()) {
                // let's combine unsubscribe and subscribe handling for ease of use
                case PNSubscribeOperation:
                case PNUnsubscribeOperation:
                    // note: subscribe statuses never have traditional
                    // errors, they just have categories to represent the
                    // different issues or successes that occur as part of subscribe
                    switch (status.getCategory()) {
                        case PNConnectedCategory:
                            // this is expected for a subscribe, this means there is no error or issue whatsoever
                        case PNReconnectedCategory:
                            // this usually occurs if subscribe temporarily fails but reconnects. This means
                            // there was an error but there is no longer any issue
                        case PNDisconnectedCategory:
                            // this is the expected category for an unsubscribe. This means there
                            // was no error in unsubscribing from everything
                        case PNUnexpectedDisconnectCategory:
                            // this is usually an issue with the internet connection, this is an error, handle appropriately
                        case PNAccessDeniedCategory:
                            // this means that PAM does allow this client to subscribe to this
                            // channel and channel group configuration. This is another explicit error
                        default:
                            // More errors can be directly specified by creating explicit cases for other
                            // error categories of `PNStatusCategory` such as `PNTimeoutCategory` or `PNMalformedFilterExpressionCategory` or `PNDecryptionErrorCategory`
                    }

                case PNHeartbeatOperation:
                    // heartbeat operations can in fact have errors, so it is important to check first for an error.
                    // For more information on how to configure heartbeat notifications through the status
                    // PNObjectEventListener callback, consult <link to the PNCONFIGURATION heartbeart config>
                    if (status.isError()) {
                        // There was an error with the heartbeat operation, handle here
                    } else {
                        // heartbeat operation was successful
                    }
                default: {
                    // Encountered unknown status type
                }
            }
        } else {
            // After a reconnection see status.getCategory()
        }
    }

    @Override
    public void message(PubNub pubnub, PNMessageResult message) {
      
    }

    @Override
    public void presence(PubNub pubnub, PNPresenceEventResult presence) {

    }
});
SubscribeCallback subscribeCallback = new SubscribeCallback() {
    @Override
    public void status(PubNub pubnub, PNStatus status) {

    }

    @Override
    public void message(PubNub pubnub, PNMessageResult message) {

    }

    @Override
    public void presence(PubNub pubnub, PNPresenceEventResult presence) {

    }
};

pubnub.addListener(subscribeCallback);

// some time later
pubnub.removeListener(subscribeCallback);
SubscribeCallback subscribeCallback = new SubscribeCallback() {
	@Override
	public void status(PubNub pubnub, PNStatus status) {
		if (status.getCategory() == PNStatusCategory.PNUnexpectedDisconnectCategory) {
			// internet got lost, do some magic and call reconnect when ready
			pubnub.reconnect();
		} else if (status.getCategory() == PNStatusCategory.PNTimeoutCategory) {
			// do some magic and call reconnect when ready
			pubnub.reconnect();
		} else {
			log.error(status);
		}
	}

	@Override
	public void message(PubNub pubnub, PNMessageResult message) {

	}

	@Override
	public void presence(PubNub pubnub, PNPresenceEventResult presence) {

	}
};

pubnub.addListener(subscribeCallback);
CategoriesDescription
PNNetworkIssuesCategoryA subscribe event experienced an exception when running.
PNReconnectedCategorySDK was able to reconnect to pubnub.
PNConnectedCategorySDK subscribed with a new mix of channels (fired every time the channel / channel group mix changed).
You can obtain information about the current state of a channel including a list of unique user-ids currently subscribed to the channel and the total occupancy count of the channel by calling the hereNow() function in your application.
To call Here Now you can use the following method(s) in the Java V4 SDK:
  1. ParameterTypeRequiredDefaultsDescription
    channelsArrayOptionalThe channels to get the here now details.
    channelGroupsArraysOptionalThe channelGroups to get the here now details.
    includeStateBooleanOptionalfalseIf true, the response will include the presence states of the users for channels/channelGroups
    includeUUIDsBooleanOptionaltrueIf true, the response will include the UUIDs of the connected clients.
    asyncPNCallbackYesPNCallback of type PNHereNowResult
pubnub.hereNow()
	// tailor the next two lines to example
	.channels(Arrays.asList("coolChannel", "coolChannel2"))
	.includeUUIDs(true)
	.async(new PNCallback<PNHereNowResult>() {
		@Override
		public void onResponse(PNHereNowResult result, PNStatus status) {
			if (status.isError()) {
				// handle error
				return;
			}
			
			for (PNHereNowChannelData channelData : result.getChannels().values()) {
				System.out.println("---");
				System.out.println("channel:" + channelData.getChannelName());
				System.out.println("occupancy: " + channelData.getOccupancy());
				System.out.println("occupants:");
				for (PNHereNowOccupantData occupant : channelData.getOccupants()) {
					System.out.println("uuid: " + occupant.getUuid() + " state: " + occupant.getState());
				}
			}
		}
	});
The hereNow() operation returns a PNHereNowResult which contains the following operations:
MethodTypeDescription
getTotalChannels()IntTotal Channels.
getTotalOccupancy()IntTotal Occupancy.
getChannels()Map<String, PNHereNowChannelData>A map with values of PNHereNowChannelData for each channel. See PNHereNowChannelData for more details.
MethodTypeDescription
getChannelName()StringChannel name.
getOccupancy()IntOccupancy of the channel.
getOccupants()List<PNHereNowOccupantData>A list of PNHereNowOccupantData, see PNHereNowOccupantData for more details.
MethodTypeDescription
getUuid()StringUUIDs of the user.
getState()ObjectState of the user.
  1. pubnub.hereNow()
    	.channels(Arrays.asList("my_channel")) // who is present on those channels?
    	.includeState(true) // include state with request (false by default)
    	.includeUUIDs(true) // if false, only shows occupancy count
    	.async(new PNCallback<PNHereNowResult>() {
    		@Override
    		public void onResponse(PNHereNowResult result, PNStatus status) {
    		
    		}
    	});
    {
    	"status" : 200,
    	"message" : "OK",
    	"service" : "Presence",
    	"uuids" : [
    		{
    			"uuid" : "myUUID0"
    		},
    		{
    			"state" : {
    				"abcd" : {
    					"age" : 15
    				}
    			},
    			"uuid" : "myUUID1"
    		},
    		{
    			"uuid" : "b9eb408c-bcec-4d34-b4c4-fabec057ad0d"
    		},
    		{
    			"state" : {
    				"abcd" : {
    					"age" : 15
    				}
    			},
    			"uuid" : "myUUID2"
    		},
    		{
    			"state" : {
    				"abcd" : {
    					"age" : 24
    				}
    			},
    			"uuid" : "myUUID9"
    		}
    	],
    	"occupancy" : 5
    }
    
  2. You can return only the occupancy information for a single channel by specifying the channel and setting uuids to false:
    pubnub.hereNow()
    	.channels(Arrays.asList("my_channel")) // who is present on those channels?
    	.includeState(false) // include state with request (false by default)
    	.includeUUIDs(false) // if false, only shows occupancy count
    	.async(new PNCallback<PNHereNowResult>() {
    		@Override
    		public void onResponse(PNHereNowResult result, PNStatus status) {
    		
    		}
    	});
    {
    	"channels": {
    		"my_channel": {
    			"occupancy": 3
    		}
    	},
    	"total_channels": 1,
    	"total_occupancy": 3
    }
    
  3. You can return the list of uuids and occupancy for all channels by omitting the channel:
    pubnub.hereNow()
    	.includeState(false) // include state with request (false by default)
    	.includeUUIDs(true) // if false, only shows occupancy count
    	.async(new PNCallback<PNHereNowResult>() {
    		@Override
    		public void onResponse(PNHereNowResult result, PNStatus status) {
    		
    		}
    	});
    {
        "total_channels" : 2,
        "total_occupancy" : 3,
        "channels" : {
            "lobby" : {
                "occupancy" : 1,
                "uuids" : [
                    "dara01"
                ]
            },
            "game01" : {
                "occupancy" : 2,
                "uuids" : [
                    "jason01",
                    "jason02"
                ]
            }
        }
    }
    
  4. You can return only the occupancy information (Global Here Now) by omitting the channel name
    pubnub.hereNow()
        .includeState(true) // include state with request (false by default)
        .includeUUIDs(true) // if false, only shows occupancy count
        .async(new PNCallback<HereNowData>() {
            @Override
            public void onResponse(HereNowData result, PNStatus status) {
    
            }
        });
    {
    	"channels": {
    		"my_channel": {
    			"occupancy": 3
    		}
    	},
    	"total_channels": 1,
    	"total_occupancy": 3
    }
    
  5. pubnub.hereNow()
    	.channelGroups(Arrays.asList("cg1", "cg2", "cg3")) // who is present on channel groups?
    	.includeState(true) // include state with request (false by default)
    	.includeUUIDs(true) // if false, only shows occupancy count
    	.async(new PNCallback<PNHereNowResult>() {
    		@Override
    		public void onResponse(PNHereNowResult result, PNStatus status) {
    		
    		}
    	});
    {
    	occupancy : 4,
    	uuids : ['123123234t234f34fq3dq', '143r34f34t34fq34q34q3', '23f34d3f4rq34r34rq23q', 'w34tcw45t45tcw435tww3']
    }
    
You can obtain information about the current list of a channels to which a uuid is subscribed to by calling the whereNow() function in your application.
 
If the app is killed/crashes and restarted (or the page containing the PubNub instance is refreshed on the browser) within the heartbeat window no timeout event is generated.
To call whereNow() you can use the following method(s) in the Java V4 SDK:
  1. ParameterTypeRequiredDescription
    uuidStringOptionalUuid of the user we want to spy on.
    asyncCommandYesExecute as async.
You simply need to define the uuid and the callback function to be used to send the data to as in the example below.
pubnub.whereNow()
    .async(new PNCallback<PNWhereNowResult>() {
        @Override
        public void onResponse(PNWhereNowResult result, PNStatus status) {
            // returns a pojo with channels // channel groups which I am part of.  
        }
    });
The whereNow() operation returns a PNWhereNowResult which contains the following operations:
MethodTypeDescription
getChannels()List<String>The list of channels where the UUID is present.
pubnub.whereNow()
	.uuid("some-other-uuid") // uuid of the user we want to spy on.
	.async(new PNCallback<PNWhereNowResult>() {
		@Override
		public void onResponse(PNWhereNowResult result, PNStatus status) {
			// returns a pojo with channels // channel groups which "some-other-uuid" part of.
		}
	});
The state API is used to set/get key/value pairs specific to a subscriber uuid.
State information is supplied as a JSON object of key/value pairs.

 
Presence state must be expressed as a Map. When calling setState, be sure to supply an initialized Map or POJO which can be serialized to a Map.
  1. ParameterTypeRequiredDescription
    channelsArrayOptionalChannels to set state.
    channelGroupsArrayOptionalChannelGroups to set state.
    stateHashMapOptionalState to set.
    uuidStringOptionalSet state for specific UUID.
    asyncPNCallbackYesPNCallback of type PNSetStateResult.
  1. ParameterTypeRequiredDescription
    channelsArraysOptionalChannel name to fetch the state.
    channelGroupsArraysOptionalChannelGroups name to fetch the state.
    uuidStringOptionalUUID
    asyncPNCallbackYesPNCallback of type PNGetStateResult.
Map<String, Object> myState = new HashMap<>();
myState.put("age", 20);

pubnub.setPresenceState()
	.channels(Arrays.asList("ch1", "ch2", "ch3")) // apply on those channels
	.state(myState) // the new state
	.async(new PNCallback<PNSetStateResult>() {
		@Override
		public void onResponse(PNSetStateResult result, PNStatus status) {
			// on new state for those channels
		}
	});
pubnub.getPresenceState()
	.channels(Arrays.asList("ch1", "ch2", "ch3")) // channels to fetch state for
	.channelGroups(Arrays.asList("cg1", "cg2", "cg3")) // channel groups to fetch state for
	.uuid("suchUUID") // uuid of user to fetch, or for own uuid
	.async(new PNCallback<PNGetStateResult>() {
		@Override
		public void onResponse(PNGetStateResult result, PNStatus status) {
			// handle response
		}
	});
The setPresenceState() operation returns a PNSetStateResult which contains the following operations:
MethodTypeDescription
getState() Map<String, Object>Map of UUIDs and the user states.
The getPresenceState() operation returns a PNGetStateResult which contains the following operations:
MethodTypeDescription
getStateByUUID() Map<String, Object>Map of UUIDs and the user states.
  1. Map<String, Object> myState = new HashMap<>();
    myState.put("age", 20);
    
    pubnub.setPresenceState()
    	.channelGroups(Arrays.asList("cg1", "cg2", "cg3")) // apply on those channel groups
    	.channels(Arrays.asList("ch1", "ch2", "ch3")) // apply on those channels
    	.state(myState) // the new state
    	.async(new PNCallback<PNSetStateResult>() {
    		@Override
    		public void onResponse(PNSetStateResult result, PNStatus status) {
    			// on new state for those channels
    		}
    	});
    The above code would return the following response to the client:
    {
    	first   : "Robert",
    	last    : "Plant",
    	age     : 59,
    	region  : "UK"
    }
    
This function establishes access permissions for PubNub Access Manager (PAM) by setting the read or write attribute to true. A grant with read or write set to false (or not included) will revoke any previous grants with read or write set to true.
Permissions can be applied to any one of two levels:
  1. Channel level privileges are based on a combination of subscribeKey and channel name.
  2. User level privileges are based on the combination of subscribeKey, channel and auth_key.
When a user attempts to access a PubNub resource, PAM will evaluate any existing rules using the following order of precedence before access to a channel is granted to the user:
  1. User Level - As a final step PAM evaluates the attributes at the User level. If an attribute is set to true for subscribeKey, channel and auth_key, access is granted for that attribute.
 
If an argument of the grant is not provided, an expected default will be assumed.
  • read and write arguments default to false
  • no auth_key results in channel-level grant
  • no channel results in application-level grant
No Permissions - If no permissions were granted at any of the three levels, the user will be denied access to the PubNub resource and receive a 403 error message. This is the default behavior for a PAM enabled application.
 
Note that privileges specifically granted to an application's subscribeKey always take precedence over privileges granted to channel or auth_key. Therefore an application that requires authentication at the userlevel should not grant access at either the Application or Channel levels.
  • History: To access historical messages you must grant full read access at either the subscribeKey or channel level. When a user has the appropriate permissions they can access any data stored. If they do not have access a 403 will be returned by PAM.
  • Presence: To grant access to Presence for a particular channel name you must also allow read and write access to the presence channel name which is specified by adding the -pnpres suffix to the name. Also note that a leave will fail in the case where a user's grant expires while connected. An HTTP 403 will be returned.
  • APNS: Standard permissions are required for publishing.
The duration of permission set with grant() are controlled by setting a time-to-live(ttl). If a ttl is not specified it is automatically set to 1440 minutes by default. Once the ttl associated with an entry in PAM has expired, the read and write attributes are immediately set to false for that entry in the PAM table.
 
PAM grant or revoke requests must be less than ~32KB at a time, or the client will return an error. For requests greater than 32KB, break them into smaller batched requests.
 
When the message size exceeds 32KB the server returns the HTTP Error code 500, instead of the correct error code 414.
To Grant Permissions on a Channel you can use the following method(s) in the Java V4 SDK
  1. ParameterTypeRequiredDefaultsDescription
    authKeysArraysOptionalAuth keys
    channelsArraysOptionalThe channels to grant access.
    channelGroupsArraysOptionalThe channelGroups to grant access.
    writeBooleanOptionalfalseWrite permission
    readBooleanOptionalfalseRead permission
    manageBooleanOptionalfalseManage permission
    ttlLongOptionalNot setTime to live for permission to be valid
    asyncPNCallbackYesPNCallback of type PNAccessManagerGrantResult
pubnub.grant()
    .channels(Arrays.asList("ch1", "ch2", "ch3")) //channels to allow grant on
    .channelGroups(Arrays.asList("cg1", "cg2", "cg3")) // groups to allow grant on
    .authKeys(Arrays.asList("key1", "key2", "key3")) // the keys we are provisioning
    .write(true) // allow those keys to write (false by default)
    .manage(true) // allow those keys to manage channel groups (false by default)
    .read(true) // allow keys to read the subscribe feed (false by default)
    .ttl(12337) // how long those keys will remain valid (0 for eternity)
    .async(new PNCallback<PNAccessManagerGrantResult>() {
        @Override
        public void onResponse(PNAccessManagerGrantResult result, PNStatus status) {
            // PNAccessManagerGrantResult is a parsed and abstracted response from server
        }
    });
The grant() operation returns a PNAccessManagerGrantResult which contains the following operations:
MethodTypeDescription
getLevel()StringSubkey or channel level.
getTtl()IntTtl of grant.
getSubscribeKey()StringThe subscribeKey.
getChannels()Map<String, Map<String, PNAccessManagerKeyData>>Access rights per channel. See PNAccessManagerKeyData for more details.
getChannelGroups()Map<String, Map<String, PNAccessManagerKeyData>>Access rights per channel group. See PNAccessManagerKeyData for more details.
MethodTypeDescription
isReadEnabled()Booleantrue if the user has read rights.
isWriteEnabled()Booleantrue if the user has write rights.
isManageEnabled()Booleantrue if the user has manage rights.
  1. pubnub.grant()
        .channels(Arrays.asList("my_channel"))	
        .write(true)
        .read(false)
        .authKeys(Arrays.asList("my_ro_authkey"))
        .ttl(5)
        .async(new PNCallback<PNAccessManagerGrantResult>() {
            @Override
            public void onResponse(PNAccessManagerGrantResult result, PNStatus status) {
                // PNAccessManagerGrantResult is a parsed and abstracted response from server
            }
        });
    The above code would return the following response to the client:
    {
    	"status" : 200,
    	"message" : "Success",
    	"payload" : {
    		"ttl" : 5,
    		"auths" : {
    			"my_ro_authkey" : {
    				"r" : 1,
    				"w" : 0
    			}
    		},
    		"subscribe_key" : "my_subkey",
    		"level" : "user",
    		"channel" : "my_channel"
    	},
    	"service" : "Access Manager"
    }
    
  2. pubnub.grant()
        .channels(Arrays.asList("my_channel-pnpres"))	
        .write(true)
        .read(true)
        .async(new PNCallback<PNAccessManagerGrantResult>() {
            @Override
            public void onResponse(PNAccessManagerGrantResult result, PNStatus status) {
                // PNAccessManagerGrantResult is a parsed and abstracted response from server
            }
        });
    
  3. pubnub.grant()
    	.channelGroups(Arrays.asList("cg1", "cg2", "cg3")) // groups to allow grant on
    	.authKeys(Arrays.asList("key1", "key2", "key3")) // the keys we are provisioning
    	.write(true) // allow those keys to write (false by default)
    	.manage(true) // allow those keys to manage channel groups (false by default)
    	.read(true) // allow keys to read the subscribe feed (false by default)
    	.ttl(12337) // how long those keys will remain valid (0 for eternity)
    	.async(new PNCallback<PNAccessManagerGrantResult>() {
    		@Override
    		public void onResponse(PNAccessManagerGrantResult result, PNStatus status) {
    			// PNAccessManagerGrantResult is a parsed and abstracted response from server
    		}
    	});
    The above code would return the following response to the client:
    {
        "status":200,
        "message":"Success",
        "payload":{
            "ttl":5,
            "auths":{
              "my_rw_authkey":{"r":1,"w":1}
            },
            "subscribe_key":"my_subkey",
            "level":"user",
            "channel":"my_channel"
        },
        "service":"Access Manager"
    }
    
This function adds a channel to a channel group.
Adding Channels is accomplished by using the following method(s) in the Java V4 SDK:
  1. ParameterTypeRequiredDescription
    channelGroupStringYesThe channelGroup to add the channels to.
    channelsArrayYesThe channel to add to the channel group.
    asyncPNCallbackYesPNCallback of type PNChannelGroupsAddChannelResult
pubnub.addChannelsToChannelGroup()
    .channelGroup("cg1")
    .channels(Arrays.asList("ch1", "ch2", "ch3"))
    .async(new PNCallback<PNChannelGroupsAddChannelResult>() {
        @Override
        public void onResponse(PNChannelGroupsAddChannelResult result, PNStatus status) {

        }
    });
{
    "service" : "channel-registry",
    "status"  : 200,
    "error"   : false,
    "message" : "OK"
}
This function lists all the channels of the channel group.
Listing Channels is accomplished by using the following method(s) in the Java V4 SDK:
  1. ParameterTypeRequiredDescription
    channelGroupStringYesChannel group to fetch the channels.
    asyncPNCallbackYesPNCallback of type PNChannelGroupsAllChannelsResult.
pubnub.listChannelsForChannelGroup()
    .channelGroup("cg1")
    .async(new PNCallback<PNChannelGroupsAllChannelsResult>() {
        @Override
        public void onResponse(PNChannelGroupsAllChannelsResult result, PNStatus status) {

        }
    });
The listChannelsForChannelGroup() operation returns a PNChannelGroupsAllChannelsResult which contains the following operations:
MethodTypeDescription
getChannels()List<String>List of channels of a channel group.
This function removes the channels from the channel group.
Removing Channels is accomplished by using the following method(s) in the Java V4 SDK:
  1. ParameterTypeRequiredDescription
    channelsArrayYesThe channels to remove from the channel group.
    channelGroup StringYesSpecifies channelGroup to remove the channels from.
    asyncPNCallbackOptionalPNCallback of type PNChannelGroupsRemoveChannelResult.
pubnub.removeChannelsFromChannelGroup()
    .channelGroup("family")
    .channels(Arrays.asList("son"))
    .async(new PNCallback<PNChannelGroupsRemoveChannelResult>() {
        @Override
        public void onResponse(PNChannelGroupsRemoveChannelResult result, PNStatus status) {
 
        }
    });
{
	"status" : 200,
	"message" : "OK",
	"service" : "channel-registry",
	"error" : False
}
This function removes the channel group.
Deleting Channel Group is accomplished by using the following method(s) in the Java V4 SDK:
  1. ParameterTypeRequiredDescription
    channelGroup StringYesSpecifies channelGroup to remove.
    asyncPNCallbackOptionalPNCallback of type PNChannelGroupsDeleteGroupResult.
pubnub.deleteChannelGroup()
	.channelGroup("family")
	.async(new PNCallback<PNChannelGroupsDeleteGroupResult>() {
		@Override
		public void onResponse(PNChannelGroupsDeleteGroupResult result, PNStatus status) {

		}
	});
{
	"status" : 200,
	"message" : "OK",
	"service" : "channel-registry",
	"error" : False
}
This function fetches historical messages of a channel.
PubNub Storage/Playback Service provides real-time access to an unlimited history for all messages published to PubNub. Stored messages are replicated across multiple availability zones in several geographical data center locations. Stored messages can be encrypted with AES-256 message encryption ensuring that they are not readable while stored on PubNub's network.
It is possible to control how messages are returned and in what order, for example you can:
  • Search for messages starting on the newest end of the timeline (default behavior - reverse = false)
  • Search for messages from the oldest end of the timeline by setting reverse to true.
  • Page through results by providing a start OR end time token.
  • Retrieve a slice of the time line by providing both a start AND end time token.
  • Limit the number of messages to a specific quantity using the count parameter.
 
Start & End parameter usage clarity:
If only the start parameter is specified (without end), you will receive messages that are older than and up to that start timetoken value.
If only the end parameter is specified (without start) you will receive messages that match that end timetoken value and newer.
Specifying values for both start and end parameters will return messages between those timetoken values (inclusive on the end value).
Keep in mind that you will still receive a maximum of 100 messages even if there are more messages that meet the timetoken values. Iterative calls to history adjusting the start timetoken is necessary to page through the full set of results if more than 100 messages meet the timetoken values.
To run History you can use the following method(s) in the Java V4 SDK
  1. ParameterTypeRequiredDefaultsDescription
    channelStringYesSpecifies channelto return history messages from.
    reverseBooleanOptionalfalseSetting to true will traverse the time line in reverse starting with the oldest message first.
    includeTimetokenBooleanOptionalfalseWhether event dates time tokens should be included in response or not.
    startLongOptionalTime token delimiting the start of time slice (exclusive) to pull messages from.
    endLongOptionalTime token delimiting the end of time slice (inclusive) to pull messages from.
    countIntOptional100Specifies the number of historical messages to return.
    asyncPNCallbackYesPNCallback of type PNHistoryResult.
Retrieve the last 100 messages on a channel:
pubnub.history()
	.channel("history_channel") // where to fetch history from
	.count(100) // how many items to fetch
	.async(new PNCallback<PNHistoryResult>() {
		@Override
		public void onResponse(PNHistoryResult result, PNStatus status) {
 
		}
	});
The history() operation returns a PNHistoryResult which contains the following operations:
MethodTypeDescription
getMessages()List<PNHistoryItemResult>List of messages of type PNHistoryItemResult. See PNHistoryItemResult for more details.
getStartTimetoken()LongStart timetoken.
getEndTimetoken()LongEnd timetoken.
MethodTypeDescription
getTimetoken()LongTimetoken of the message.
getEntry()JsonElementMessage.
  1. pubnub.history()
        .channel("my_channel") // where to fetch history from
        .count(3) // how many items to fetch
        .reverse(true) // should go in reverse?
        .async(new PNCallback<PNHistoryResult>() {
            @Override
            public void onResponse(PNHistoryResult result, PNStatus status) {
    
            }
        });
     [
    	["Pub1","Pub2","Pub3"],
    	13406746729185766,
    	13406746780720711
    ]
    
  2. pubnub.history()
    	.channel("my_channel") // where to fetch history from
    	.start(13847168620721752L) // first timestamp
    	.reverse(true) // should go in reverse?
    	.async(new PNCallback<PNHistoryResult>() {
    		@Override
    		public void onResponse(PNHistoryResult result, PNStatus status) {
    		
    		}
    	});
     [
    	["Pub3","Pub4","Pub5"],
    	13406746780720711,
    	13406746845892666
    ]
    
  3. pubnub.history()
        .channel("my_channel") // where to fetch history from
        .count(100) // how many items to fetch
        .start(-1) // first timestamp 
        .end(13847168819178600L) // last timestamp
        .reverse(true) // should go in reverse?
        .async(new PNCallback<PNHistoryResult>() {
            @Override
            public void onResponse(PNHistoryResult result, PNStatus status) {
    
            }
        });
    [
    	["Pub3","Pub4","Pub5"],
    	13406746780720711,
    	13406746845892666
    ]
    
  4.  
    Usage!
    You can call the method by passing 0 or a valid time token as the argument.
    package com.pubnub.api;
    
    import com.pubnub.api.callbacks.PNCallback;
    import com.pubnub.api.models.consumer.PNStatus;
    import com.pubnub.api.models.consumer.history.PNHistoryResult;
    import org.json.JSONArray;
    import org.json.JSONException;
    
    import java.util.concurrent.CountDownLatch;
    import java.util.concurrent.TimeUnit;
    
    public class PubnubRecursiveHistoryFetcher {
    	private PubNub pubnub;
        
    	private abstract class CallbackSkeleton {
    	
    		public abstract void handleResponse(PNHistoryResult result);
    
        }
    
    	PubnubRecursiveHistoryFetcher() {
    		// NOTICE: for demo/demo pub/sub keys Storage & Playback is disabled,
    		// so use your pub/sub keys instead
    		PNConfiguration pnConfiguration = new PNConfiguration();
    		pnConfiguration.setSubscribeKey("demo");
    		pubnub = new PubNub(pnConfiguration);
    	}
    
    	public static void main(String[] args) {
    		PubnubRecursiveHistoryFetcher fetcher = new PubnubRecursiveHistoryFetcher();
    	}
    
    	public void getAllMessages(CallbackSkeleton callback) {
    		getAllMessages(null, callback);
    	}
    
    	public void getAllMessages(Long startTimestamp, final CallbackSkeleton callback) {
    		final CountDownLatch latch = new CountDownLatch(1);
    		
    		if (startTimestamp == null) {
    			startTimestamp = -1L;
    		}
    
    		pubnub.history()
    			.channel("history_channel") // where to fetch history from
    			.count(100) //  how many items to fetch
    			.start(startTimestamp) // first timestamp
    			.async(new PNCallback<PNHistoryResult>() {
    				@Override
    				public void onResponse(PNHistoryResult historyResult, PNStatus status) {
    					if (!status.isError() && historyResult.getMessages().size() != 0) {
    						System.out.println(historyResult.getMessages().size());
    						System.out.println("start: " + historyResult.getStartTimeToken());
    						System.out.println("end: " + historyResult.getEndTimeToken());
    						callback.handleResponse(historyResult);
    						getAllMessages(historyResult.getEndTimeToken(), callback);
    					}
    				}
    			});
    
    	}
    }
  5. pubnub.history()
    	.channel("history_channel") // where to fetch history from
    	.count(100) // how many items to fetch
    	.includeTimetoken(true) // include timetoken with each entry
    	.async(new PNCallback<PNHistoryResult>() {
    		@Override
    		public void onResponse(PNHistoryResult result, PNStatus status) {
     
    		}
    	});
Enable push notifications on provided set of channels.
To run Adding Device to Channel you can use the following method(s) in the Java V4 SDK
  1. ParameterTypeRequiredDefaultsDescription
    pushTypePNPushTypeYesNot setAccepted values: PNPushType.GCM, PNPushType.APNS, PNPushType.MPNS.
    channelsArraysYesAdd push notifications on the specified channels.
    deviceIdStringYesDevice id.
    asyncPNCallbackYesPNCallback of type PNPushAddChannelResult.
pubnub.addPushNotificationsOnChannels()
	.pushType(PNPushType.GCM)
	.channels(Arrays.asList("ch1", "ch2", "ch3"))
	.deviceId("googleDevice")
	async(new PNCallback<PNPushAddChannelResult>() {
		@Override
		public void onResponse(PNPushAddChannelResult result, PNStatus status) {
			// handle response.
		}
	});
The addPushNotificationsOnChannels() does not return actionable data, be sure to check the status object on the outcome of the operation by checking the status.isError().
Request for all channels on which push notification has been enabled using specified pushToken.
To run Listing Channels For Device you can use the following method(s) in the Java V4 SDK
  1. ParameterTypeRequiredDefaultsDescription
    deviceIdStringYesDevice id.
    pushTypePNPushTypeYesNot setAccepted values: PNPushType.GCM, PNPushType.APNS, PNPushType.MPNS.
    asyncPNCallbackYesPNCallback of type PNPushListProvisionsResult.
pubnub.auditPushChannelProvisions()
	.deviceId("googleDevice")
	.pushType(PNPushType.GCM)
	.async(new PNCallback<PNPushListProvisionsResult>() {
		@Override
		public void onResponse(PNPushListProvisionsResult result, PNStatus status) {
		
		}
	});
The auditPushChannelProvisions() operation returns a PNPushListProvisionsResult which contains the following operations:
MethodTypeDescription
getChannels() List<String>List of channels subscribed for push notifications.
Disable push notifications on provided set of channels. If nil will be passed as channels then client will remove push notifications from all channels which associated with pushToken.
To run Removing Device From Channel you can use the following method(s) in the Java V4 SDK
  1. ParameterTypeRequiredDefaultsDescription
    deviceIdStringYesDevice id.
    channelsArraysYesRemove push notifications on the specified channels.
    pushTypePNPushTypeYesNot setAccepted values: PNPushType.GCM, PNPushType.APNS, PNPushType.MPNS.
    asyncPNCallbackYesPNCallback of type PNPushRemoveChannelResult.
pubnub.removePushNotificationsFromChannels()
	.deviceId("googleDevice")
	.channels(Arrays.asList("ch1", "ch2", "ch3"))
	.pushType(PNPushType.GCM)
	.async(new PNCallback<PNPushRemoveChannelResult>() {
		@Override
		public void onResponse(PNPushRemoveChannelResult result, PNStatus status) {
		
		}
	});
The removePushNotificationsFromChannels() does not return actionable data, be sure to check the status object on the outcome of the operation by checking the status.isError().
This function will return a 17 digit precision Unix epoch.
 
Timetoken
The timetoken is constructed using the following algorithm:
timetoken = (Unix epoch time in seconds) * 10000000
Example of creating a timetoken for a specific time & date
08/19/2013 @ 9:20pm in UTC = 1376961606
timetoken = 1376961606 * 10000000
timetoken = 13769616060000000
To fetch Time you can use the following method(s) in Java V4 SDK
  1. ParameterTypeRequiredDescription
    asyncPNCallbackYesPNCallback of type PNTimeResult
pubnub.time().async(new PNCallback<PNTimeResult>() {
	@Override
	public void onResponse(PNTimeResult result, PNStatus status) {
		// handle time result.
	}
});
The time() operation returns a PNTimeResult which contains the following operations:
MethodTypeDescription
getTimetoken()LongReturns a long representation of current time token.
Returns all the subscribed channels in a List of type String..
To Get Subscribed Channels you can use the following method(s) in the Java V4 SDK:
  1. public final List<String> getSubscribedChannels()
List<String> channels = pubnub.getSubscribedChannels();
List<String>
["channel1", "channel2"]
Returns all the subscribed channel groups in a List of type String..
To Get Subscribe Channel Groups you can use the following method(s) in the Java V4 SDK
  1. public final List<String> getSubscribedChannelGroups()
List<String> groups = pubnub.getSubscribedChannelGroups();
List<String>
["channelGroup1", "channelGroup2"]
Destroy frees up the threads and allows for clean exit.
  1. destroy()
pubnub.destroy();
None
This function allow to encrypt the data.
To encrypt the data you can use the following method(s) in Java V4 SDK.
  1. ParameterTypeRequiredDescription
    dataStringYesThe data to encrypt.
    customCipherKeyStringOptionalIf it's not provided, the cipher key from config will be used.
This function allow to decrypt the data.
To decrypt the data you can use the following method(s) in Java V4 SDK.
  1. ParameterTypeRequiredDescription
    dataStringYesThe data to decrypt.
    customCipherKeyStringOptionalIf it's not provided, the cipher key from config will be used.
Check out PubNub's other Java-based SDKs, such as Java V4, Android V4