JavaJava V4 Presence API Reference for Realtime Apps

Go to Publish & Subscribe


Requires Presence add-on XRequires that the Presence add-on is enabled for your key. See this page on enabling add-on features on your keys:

http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
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. Requires Presence add-on XRequires that the Presence add-on is enabled for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
    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) {
    		
    		}
    	});
    if (!status.isError()) {
    	for (PNHereNowChannelData channelData : result.getChannels().values()) {
    	        channelData.getOccupancy(); // 3
    	        channelData.getChannelName(); // my_channel
    	        channelData.getOccupants(); // members of a channel
    	        for (PNHereNowOccupantData occupant : channelData.getOccupants()) {
    	            occupant.getUuid(); // some_uuid;
    	            occupant.getState(); // channel member state, if applicable
    	        }
        }
    } else {
        // an error occurred
    	status.getErrorData().getInformation();
    	status.getErrorData().getThrowable().printStackTrace();
    }
  2. Requires Presence add-on XRequires that the Presence add-on is enabled for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
    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) {
    		
    		}
    	});
    if (!status.isError()) {
        for (PNHereNowChannelData channelData: result.getChannels().values()) {
            channelData.getOccupancy(); // 3
            channelData.getChannelName(); // my_channel
        }
    } else {
        // an error occurred
        status.getErrorData().getInformation();
        status.getErrorData().getThrowable().printStackTrace();
    }
  3. Requires Presence add-on XRequires that the Presence add-on is enabled with Global Here Now checked for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
    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) {
    		
    		}
    	});
    if (!status.isError()) {
        result.getTotalChannels(); // 4
        result.getTotalOccupancy(); // 12
        for (PNHereNowChannelData channelData: result.getChannels().values()) {
            channelData.getOccupancy(); // 3
            channelData.getChannelName(); // my_channel
            channelData.getOccupants(); // members of a channel
            for (PNHereNowOccupantData occupant: channelData.getOccupants()) {
                occupant.getUuid(); // some_uuid;
            }
        }
    } else {
        // an error occurred
        status.getErrorData().getInformation();
        status.getErrorData().getThrowable().printStackTrace();
    }
  4. Requires Presence add-on XRequires that the Presence add-on is enabled with Global Here Now checked for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
    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<PNHereNowResult>() {
            @Override
            public void onResponse(PNHereNowResult result, PNStatus status) {
    
            }
        });
    if (!status.isError()) {
        result.getTotalChannels(); // 4
        result.getTotalOccupancy(); // 12
        for (PNHereNowChannelData channelData: result.getChannels().values()) {
            channelData.getOccupancy(); // 3
            channelData.getOccupants(); // members of a channel
            for (PNHereNowOccupantData occupant: channelData.getOccupants()) {
                occupant.getUuid(); // some_uuid;
            }
        }
    } else {
        // an error occurred
        status.getErrorData().getInformation();
        status.getErrorData().getThrowable().printStackTrace();
    }
  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) {
    		
    		}
    	});
    if (!status.isError()) {
        result.getTotalOccupancy(); // 12
    } else {
        // an error occurred
        status.getErrorData().getInformation();
        status.getErrorData().getThrowable().printStackTrace();
    }
Requires Presence add-on XRequires that the Presence add-on is enabled for your key. See this page on enabling add-on features on your keys:

http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
You can obtain information about the current list of 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.
		}
	});
Requires Presence add-on XRequires that the Presence add-on is enabled for your key. See this page on enabling add-on features on your keys:

http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
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 JsonObject. When calling setState, be sure to supply an initialized JsonObject or POJO which can be serialized to a JsonObject.
  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.
JsonObject state = new JsonObject();
state.addProperty("is_typing", isTyping);

pubnub.setPresenceState()
    .channels(Arrays.asList(channel))
    .state(state)
    .async(new PNCallback<PNSetStateResult>() {
        @Override
        public void onResponse(final PNSetStateResult result, PNStatus status) {
        }
    });
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. JsonObject state = new JsonObject();
    state.addProperty("is_typing", isTyping);
     
    pubnub.setPresenceState()
        .channelGroups(Arrays.asList("cg1", "cg2", "cg3")) // apply on those channel groups
        .channels(Arrays.asList("ch1", "ch2", "ch3")) // apply on those channels
        .state(state) // the new state
        .async(new PNCallback<PNSetStateResult>() {
            @Override
            public void onResponse(final PNSetStateResult result, PNStatus status) {
                // on new state for those channels
            }
        });
    The above code would return the following response to the client:
     if (presence.getEvent().equals("state-change")) {
         boolean is_typing = presence.getState()
                                .getAsJsonObject()
                                .get("is_typing")
                                .getAsBoolean();
     }

Go to Access Manager