JavaPubNub Java SDK 4.3.0

 

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.

<dependency>
  <groupId>com.pubnub</groupId>
  <artifactId>pubnub-gson</artifactId>
  <version>4.3.0</version>
</dependency>
compile group: 'com.pubnub', name: 'pubnub-gson', version: '4.3.0'
To use Pubnub, simply copy the Pubnub-4.3.0.jar file into your project's libs directory.
-dontwarn com.pubnub.**
 
# Gson uses generic type information stored in a class file when working with fields. Proguard
# removes such information by default, so configure it to keep all of it.
-keepattributes Signature
 
# For using GSON @Expose annotation
-keepattributes *Annotation*
 
# Gson specific classes
-keep class sun.misc.Unsafe { *; }
-keep class com.google.gson.stream.** { *; }
 
# Application classes that will be serialized/deserialized over Gson
-keep class com.google.gson.examples.android.model.** { *; }
 
# Prevent proguard from stripping interface information from TypeAdapterFactory,
# JsonSerializer, JsonDeserializer instances (so they can be used in @JsonAdapter)
-keep class * implements com.google.gson.TypeAdapterFactory
-keep class * implements com.google.gson.JsonSerializer
-keep class * implements com.google.gson.JsonDeserializer
 
# Platform calls Class.forName on types which do not exist on Android to determine platform.
-dontnote retrofit2.Platform
# Platform used when running on RoboVM on iOS. Will not be used at runtime.
-dontnote retrofit2.Platform$IOS$MainThreadExecutor
# Platform used when running on Java 8 VMs. Will not be used at runtime.
-dontwarn retrofit2.Platform$Java8
# Retain generic type information for use by reflection by converters and adapters.
-keepattributes Signature
# Retain declared checked exceptions for use by a Proxy instance.
-keepattributes Exceptions



Add PubNub to your project using one of the procedures defined under How to Get It.
public static void main(String[] args) {
    PNConfiguration pnConfiguration = new PNConfiguration();
    pnConfiguration.setSubscribeKey("demo");
    pnConfiguration.setPublishKey("demo");
    
    PubNub pubnub = new PubNub(pnConfiguration);

    pubnub.addListener(new SubscribeCallback() {
        @Override
        public void status(PubNub pubnub, PNStatus status) {


            if (status.getCategory() == PNStatusCategory.PNUnexpectedDisconnectCategory) {
                // This event happens when radio / connectivity is lost
            }

            else if (status.getCategory() == PNStatusCategory.PNConnectedCategory) {

                // Connect event. You can do stuff like publish, and know you'll get it.
                // Or just use the connected event to confirm you are subscribed for
                // UI / internal notifications, etc
            
                if (status.getCategory() == PNStatusCategory.PNConnectedCategory){
                    pubnub.publish().channel("awesomeChannel").message("hello!!").async(new PNCallback<PNPublishResult>() {
                        @Override
                        public void onResponse(PNPublishResult result, PNStatus status) {
                            // Check whether request successfully completed or not.
                            if (!status.isError()) {

                                // Message successfully published to specified channel.
                            }
                            // Request processing failed.
                            else {

                                // Handle message publish error. Check 'category' property to find out possible issue
                                // because of which request did fail.
                                //
                                // Request can be resent using: [status retry];
                            }
                        }
                    });
                }
            }
            else if (status.getCategory() == PNStatusCategory.PNReconnectedCategory) {

                // Happens as part of our regular operation. This event happens when
                // radio / connectivity is lost, then regained.
            }
            else if (status.getCategory() == PNStatusCategory.PNDecryptionErrorCategory) {

                // Handle messsage decryption error. Probably client configured to
                // encrypt messages and on live data feed it received plain text.
            }
        }

        @Override
        public void message(PubNub pubnub, PNMessageResult message) {
            // Handle new message stored in message.message
            if (message.getChannel() != null) {
                // Message has been received on channel group stored in
                // message.getChannel()
            }
            else {
                // Message has been received on channel stored in
                // message.getSubscription()
            }

            /*
                log the following items with your favorite logger
                    - message.getMessage()
                    - message.getSubscription()
                    - message.getTimetoken()
            */
        }

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

        }
    });

    pubnub.subscribe().channels(Arrays.asList("awesomeChannel")).execute();
}
In addition to the Hello World sample code, we also provide some copy and paste snippets of common API functions:
Instantiate a new Pubnub instance. Only the subscribeKey is mandatory. Also include publishKey if you intend to publish from this instance, and the secretKey if you wish to perform PAM administrative operations from this Java V4 instance.
 
For security reasons you should only include the secret-key on a highly secured server. The secret-key is only required for granting rights using our Access Manager.
PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.setSubscribeKey("SubscribeKey");
pnConfiguration.setPublishKey("PublishKey");
pnConfiguration.setSecure(false);
  
PubNub pubnub = new PubNub(pnConfiguration);
pubnub.addListener(new SubscribeCallback() {
    @Override

    public void status(PubNub pubnub, PNStatus status) {
		// the status object returned is always related to subscribe but could contain
		// information about subscribe, heartbeat, or errors
		// use the operationType to switch on different options
		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
			}
		}
	}

	@Override
	public void message(PubNub pubnub, PNMessageResult message) {
		// handle incoming messages
	}

	@Override
	public void presence(PubNub pubnub, PNPresenceEventResult presence) {
		// handle incoming presence data
	}
});
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
PNNetworkIssuesCategory
A subscribe event experienced an exception when running.
PNReconnectedCategory
SDK was able to reconnect to pubnub.
PNConnectedCategory
SDK subscribed with a new mix of channels (fired every time the channel / channel group mix changed).
Call time() to verify the client connectivity to the origin:
pubnub.time().async(new PNCallback<PNTimeResult>() {
	@Override
	public void onResponse(PNTimeResult result, PNStatus status) {
		// handle time result.
	}
});
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.
Publish a message to a channel:
pubnub.publish()
    .message(Arrays.asList("hello", "there"))
    .channel("suchChannel")
    .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
        }
    });
Get occupancy of who's here now on the channel by UUID:
Requires that the Presence add-on is enabled for your key. How do I enable add-on features for my keys? - see http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys
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());
				}
			}
		}
	});
Subscribe to realtime Presence events, such as join, leave, and timeout, by UUID. Setting the presence attribute to a callback will subscribe to presents events on my_channel:
Requires that the Presence add-on is enabled for your key. How do I enable add-on features for my keys? - see http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys
pubnub.subscribe()
    .channels(Arrays.asList("my_channel")) // subscribe to channels
    .withPresence() // also subscribe to related presence information
    .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.
Retrieve published messages from archival storage:
Requires that the Storage and Playback add-on is enabled for your key. How do I enable add-on features for my keys? - see http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys
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) {
 
		}
	});
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.

For more details, please see the Destroy section.

pubnub.destroy();
Check out PubNub's other Java-based SDKs, such as Java V4, Android V4