### Complete Pub/Sub Example Source: https://github.com/pubnub/java/blob/master/_autodocs/api-reference/publish-subscribe.md A comprehensive example demonstrating PubNub configuration, listener setup, subscribing to channels, publishing messages, sending signals, and unsubscribing. ```java // Configuration PNConfiguration config = new PNConfiguration(new UserId("user-123")); config.setSubscribeKey("demo"); config.setPublishKey("demo"); PubNub pubNub = new PubNub(config); // Add listener for all events pubNub.addListener(new SubscribeCallback.BaseSubscribeCallback() { @Override public void status(PubNub pubnub, PNStatus status) { if (status.getCategory() == PNStatusCategory.PNConnectedCategory) { System.out.println("Connected! Ready to send/receive messages"); } } @Override public void message(PubNub pubnub, PNMessageResult message) { System.out.println("Channel: " + message.getChannel()); System.out.println("Message: " + message.getMessage()); } @Override public void presence(PubNub pubnub, PNPresenceEventResult presence) { System.out.println("Presence: " + presence.getEvent() + " by " + presence.getUuid()); } @Override public void signal(PubNub pubnub, PNSignalResult signal) { System.out.println("Signal on " + signal.getChannel() + ": " + signal.getMessage()); } // Implement other abstract methods... }); // Subscribe to channels pubNub.subscribe() .channels(Arrays.asList("chat", "notifications")) .withPresence() .execute(); // Publish a message pubNub.publish() .channel("chat") .message(new JSONObject() .put("user", "Alice") .put("text", "Hello everyone!")) .shouldStore(true) .async((result, status) -> { if (!status.isError()) { System.out.println("Message published with timetoken: " + result.getTimetoken()); } }); // Send a signal pubNub.signal() .channel("typing") .message(true) .async((result, status) -> { if (!status.isError()) { System.out.println("Typing indicator sent"); } }); // Unsubscribe pubNub.unsubscribe() .channels(Arrays.asList("chat")) .execute(); ``` -------------------------------- ### Complete Publish/Subscribe Example Source: https://github.com/pubnub/java/blob/master/_autodocs/api-reference/publish-subscribe.md A comprehensive example demonstrating the setup and usage of the PubNub SDK for subscribing, publishing, and sending signals. ```APIDOC ## Complete Publish/Subscribe Example ```java // Configuration PNConfiguration config = new PNConfiguration(new UserId("user-123")); config.setSubscribeKey("demo"); config.setPublishKey("demo"); PubNub pubNub = new PubNub(config); // Add listener for all events pubNub.addListener(new SubscribeCallback.BaseSubscribeCallback() { @Override public void status(PubNub pubnub, PNStatus status) { if (status.getCategory() == PNStatusCategory.PNConnectedCategory) { System.out.println("Connected! Ready to send/receive messages"); } } @Override public void message(PubNub pubnub, PNMessageResult message) { System.out.println("Channel: " + message.getChannel()); System.out.println("Message: " + message.getMessage()); } @Override public void presence(PubNub pubnub, PNPresenceEventResult presence) { System.out.println("Presence: " + presence.getEvent() + " by " + presence.getUuid()); } @Override public void signal(PubNub pubnub, PNSignalResult signal) { System.out.println("Signal on " + signal.getChannel() + ": " + signal.getMessage()); } // Implement other abstract methods... }); // Subscribe to channels pubNub.subscribe() .channels(Arrays.asList("chat", "notifications")) .withPresence() .execute(); // Publish a message pubNub.publish() .channel("chat") .message(new JSONObject() .put("user", "Alice") .put("text", "Hello everyone!")) .shouldStore(true) .async((result, status) -> { if (!status.isError()) { System.out.println("Message published with timetoken: " + result.getTimetoken()); } }); // Send a signal pubNub.signal() .channel("typing") .message(true) .async((result, status) -> { if (!status.isError()) { System.out.println("Typing indicator sent"); } }); // Unsubscribe pubNub.unsubscribe() .channels(Arrays.asList("chat")) .execute(); ``` ``` -------------------------------- ### Complete State and Presence Example Source: https://github.com/pubnub/java/blob/master/_autodocs/api-reference/presence-state.md A comprehensive example demonstrating PubNub configuration, listener setup for presence events, subscribing with presence, setting presence state, querying 'here now' and 'where now', and unsubscribing. ```java // Configuration PNConfiguration config = new PNConfiguration(new UserId("user-123")); config.setSubscribeKey("demo"); config.setPublishKey("demo"); config.setPresenceTimeout(300); PubNub pubNub = new PubNub(config); // Add listener for all events pubNub.addListener(new SubscribeCallback.BaseSubscribeCallback() { @Override public void status(PubNub pubnub, PNStatus status) { if (status.getCategory() == PNStatusCategory.PNConnectedCategory) { System.out.println("Connected - presence active"); } } @Override public void presence(PubNub pubnub, PNPresenceEventResult presence) { switch (presence.getEvent()) { case "join": System.out.println(presence.getUuid() + " joined (occupancy: " + presence.getOccupancy() + ")"); break; case "leave": System.out.println(presence.getUuid() + " left"); break; case "timeout": System.out.println(presence.getUuid() + " timed out"); break; case "state-change": System.out.println(presence.getUuid() + " state: " + presence.getState()); break; } } @Override public void message(PubNub pubnub, PNMessageResult message) {} @Override public void signal(PubNub pubnub, PNSignalResult signal) {} @Override public void uuid(PubNub pubnub, PNUUIDMetadataResult uuid) {} @Override public void channel(PubNub pubnub, PNChannelMetadataResult channel) {} @Override public void membership(PubNub pubnub, PNMembershipResult membership) {} @Override public void messageAction(PubNub pubnub, PNMessageActionResult action) {} @Override public void file(PubNub pubnub, PNFileEventResult file) {} }); // Subscribe with presence pubNub.subscribe() .channels(Arrays.asList("room-1")) .withPresence() .execute(); // Set state pubNub.setPresenceState() .channel("room-1") .state(new JSONObject() .put("status", "online") .put("device", "mobile")) .async((result, status) -> { if (!status.isError()) { System.out.println("Presence state updated"); } }); // Query who's in the room pubNub.hereNow() .channels(Arrays.asList("room-1")) .includeUUIDs(true) .includeState(true) .async((result, status) -> { if (!status.isError()) { PNHereNowChannelData channel = result.getChannels().get(0); System.out.println("Room occupancy: " + channel.getOccupancy()); for (PNHereNowOccupantData occupant : channel.getOccupants()) { System.out.println(" - " + occupant.getUuid() + " (" + occupant.getState() + ")"); } } }); // Check what channels you're in pubNub.whereNow() .async((result, status) -> { if (!status.isError()) { System.out.println("Subscribed to: " + result.getChannels()); } }); // Leave gracefully pubNub.unsubscribe() .channels(Arrays.asList("room-1")) .execute(); ``` -------------------------------- ### Complete Listener Example Source: https://github.com/pubnub/java/blob/master/_autodocs/api-reference/callbacks.md An example demonstrating how to implement a comprehensive listener for various PubNub events, including status, message, presence, and more. ```APIDOC ## Complete Listener Example ```java pubnub.addListener(new SubscribeCallback.BaseSubscribeCallback() { @Override public void status(PubNub pubnub, PNStatus status) { switch (status.getCategory()) { case PNConnectedCategory: System.out.println("Connected and ready to receive messages"); break; case PNReconnectedCategory: System.out.println("Reconnected after network interruption"); break; case PNDisconnectedCategory: System.out.println("Disconnected from PubNub"); break; case PNUnexpectedDisconnectCategory: System.out.println("Unexpected disconnect - will auto-reconnect"); break; case PNAccessDeniedCategory: System.out.println("Access denied by PAM"); break; default: if (status.isError()) { System.out.println("Error: " + status.getCategory()); } } } @Override public void message(PubNub pubnub, PNMessageResult message) { System.out.println("Channel: " + message.getChannel()); System.out.println("Message: " + message.getMessage()); if (message.getUserMetadata() != null) { System.out.println("Metadata: " + message.getUserMetadata()); } if (message.getCustomMessageBody() != null) { System.out.println("Custom fields: " + message.getCustomMessageBody()); } } @Override public void presence(PubNub pubnub, PNPresenceEventResult presence) { System.out.println("Presence event: " + presence.getEvent()); System.out.println("UUID: " + presence.getUuid()); System.out.println("Channel: " + presence.getChannel()); System.out.println("Occupancy: " + presence.getOccupancy()); } @Override public void signal(PubNub pubnub, PNSignalResult signal) { System.out.println("Signal on " + signal.getChannel() + ": " + signal.getMessage()); } @Override public void uuid(PubNub pubnub, PNUUIDMetadataResult uuid) { System.out.println("UUID metadata changed: " + uuid.getUuid()); } @Override public void channel(PubNub pubnub, PNChannelMetadataResult channel) { System.out.println("Channel metadata changed: " + channel.getChannel()); } @Override public void membership(PubNub pubnub, PNMembershipResult membership) { System.out.println("Membership changed: " + membership.getUuid() + " <-> " + membership.getChannel()); } @Override public void messageAction(PubNub pubnub, PNMessageActionResult action) { System.out.println("Message action: " + action.getType() + " = " + action.getValue()); } @Override public void file(PubNub pubnub, PNFileEventResult file) { System.out.println("File uploaded: " + file.getFile().getName() + " (ID: " + file.getFile().getId() + ")"); } }); ``` ``` -------------------------------- ### Complete State & Presence Example Source: https://github.com/pubnub/java/blob/master/_autodocs/api-reference/presence-state.md A comprehensive example demonstrating PubNub configuration, subscription with presence, setting presence state, querying presence information, and unsubscribing. ```APIDOC ## Complete State & Presence Example ```java // Configuration PNConfiguration config = new PNConfiguration(new UserId("user-123")); config.setSubscribeKey("demo"); config.setPublishKey("demo"); config.setPresenceTimeout(300); PubNub pubNub = new PubNub(config); // Add listener for all events pubNub.addListener(new SubscribeCallback.BaseSubscribeCallback() { @Override public void status(PubNub pubnub, PNStatus status) { if (status.getCategory() == PNStatusCategory.PNConnectedCategory) { System.out.println("Connected - presence active"); } } @Override public void presence(PubNub pubnub, PNPresenceEventResult presence) { switch (presence.getEvent()) { case "join": System.out.println(presence.getUuid() + " joined (occupancy: " + presence.getOccupancy() + ")"); break; case "leave": System.out.println(presence.getUuid() + " left"); break; case "timeout": System.out.println(presence.getUuid() + " timed out"); break; case "state-change": System.out.println(presence.getUuid() + " state: " + presence.getState()); break; } } @Override public void message(PubNub pubnub, PNMessageResult message) {} @Override public void signal(PubNub pubnub, PNSignalResult signal) {} @Override public void uuid(PubNub pubnub, PNUUIDMetadataResult uuid) {} @Override public void channel(PubNub pubnub, PNChannelMetadataResult channel) {} @Override public void membership(PubNub pubnub, PNMembershipResult membership) {} @Override public void messageAction(PubNub pubnub, PNMessageActionResult action) {} @Override public void file(PubNub pubnub, PNFileEventResult file) {} }); // Subscribe with presence pubNub.subscribe() .channels(Arrays.asList("room-1")) .withPresence() .execute(); // Set state pubNub.setPresenceState() .channel("room-1") .state(new JSONObject() .put("status", "online") .put("device", "mobile")) .async((result, status) -> { if (!status.isError()) { System.out.println("Presence state updated"); } }); // Query who's in the room pubNub.hereNow() .channels(Arrays.asList("room-1")) .includeUUIDs(true) .includeState(true) .async((result, status) -> { if (!status.isError()) { PNHereNowChannelData channel = result.getChannels().get(0); System.out.println("Room occupancy: " + channel.getOccupancy()); for (PNHereNowOccupantData occupant : channel.getOccupants()) { System.out.println(" - " + occupant.getUuid() + " (" + occupant.getState() + ")"); } } }); // Check what channels you're in pubNub.whereNow() .async((result, status) -> { if (!status.isError()) { System.out.println("Subscribed to: " + result.getChannels()); } }); // Leave gracefully pubNub.unsubscribe() .channels(Arrays.asList("room-1")) .execute(); ``` ``` -------------------------------- ### Basic PNConfiguration Setup Source: https://github.com/pubnub/java/blob/master/_autodocs/api-reference/pnconfiguration.md Initialize PNConfiguration with a UserId and set demo keys. Ensure secure connection is enabled. ```java PNConfiguration config = new PNConfiguration(new UserId("user-123")); config.setSubscribeKey("demo"); config.setPublishKey("demo"); config.setSecure(true); ``` -------------------------------- ### Pagination Example Source: https://github.com/pubnub/java/blob/master/_autodocs/api-reference/message-history.md Demonstrates how to paginate through message history using the fetchMessages API. ```APIDOC ## Pagination Example ```java String page = null; boolean hasMore = true; while (hasMore) { FetchMessages.Builder fetch = pubnub.fetchMessages() .channels(Arrays.asList("history")) .maximumPerChannel(100); if (page != null) { fetch.page(new PNPage().setPageHash(page)); } PNFetchMessagesResult result = fetch.sync(); // Process messages result.getChannels().forEach((channel, messages) -> { messages.forEach(msg -> { System.out.println("Message: " + msg.getMessage()); }); }); // Check for more pages PNPage nextPage = result.getMore().get("history"); if (nextPage != null && nextPage.getPageHash() != null) { page = nextPage.getPageHash(); } else { hasMore = false; } } ``` ``` -------------------------------- ### Complete Subscribe Listener Example Source: https://github.com/pubnub/java/blob/master/_autodocs/api-reference/callbacks.md An example of implementing a comprehensive listener for various PubNub events including status changes, messages, presence, signals, and metadata updates. This listener should be added to the PubNub client instance. ```java pubnub.addListener(new SubscribeCallback.BaseSubscribeCallback() { @Override public void status(PubNub pubnub, PNStatus status) { switch (status.getCategory()) { case PNConnectedCategory: System.out.println("Connected and ready to receive messages"); break; case PNReconnectedCategory: System.out.println("Reconnected after network interruption"); break; case PNDisconnectedCategory: System.out.println("Disconnected from PubNub"); break; case PNUnexpectedDisconnectCategory: System.out.println("Unexpected disconnect - will auto-reconnect"); break; case PNAccessDeniedCategory: System.out.println("Access denied by PAM"); break; default: if (status.isError()) { System.out.println("Error: " + status.getCategory()); } } } @Override public void message(PubNub pubnub, PNMessageResult message) { System.out.println("Channel: " + message.getChannel()); System.out.println("Message: " + message.getMessage()); if (message.getUserMetadata() != null) { System.out.println("Metadata: " + message.getUserMetadata()); } if (message.getCustomMessageBody() != null) { System.out.println("Custom fields: " + message.getCustomMessageBody()); } } @Override public void presence(PubNub pubnub, PNPresenceEventResult presence) { System.out.println("Presence event: " + presence.getEvent()); System.out.println("UUID: " + presence.getUuid()); System.out.println("Channel: " + presence.getChannel()); System.out.println("Occupancy: " + presence.getOccupancy()); } @Override public void signal(PubNub pubnub, PNSignalResult signal) { System.out.println("Signal on " + signal.getChannel() + ": " + signal.getMessage()); } @Override public void uuid(PubNub pubnub, PNUUIDMetadataResult uuid) { System.out.println("UUID metadata changed: " + uuid.getUuid()); } @Override public void channel(PubNub pubnub, PNChannelMetadataResult channel) { System.out.println("Channel metadata changed: " + channel.getChannel()); } @Override public void membership(PubNub pubnub, PNMembershipResult membership) { System.out.println("Membership changed: " + membership.getUuid() + " <-> " + membership.getChannel()); } @Override public void messageAction(PubNub pubnub, PNMessageActionResult action) { System.out.println("Message action: " + action.getType() + " = " + action.getValue()); } @Override public void file(PubNub pubnub, PNFileEventResult file) { System.out.println("File uploaded: " + file.getFile().getName() + " (ID: " + file.getFile().getId() + ")"); } }); ``` -------------------------------- ### Compile Project with Gradle Source: https://github.com/pubnub/java/blob/master/DEVELOPER.md Use this command to clean and compile the project. Ensure Gradle is installed and configured. ```bash gradle clean compile ``` -------------------------------- ### History Endpoint: start Source: https://github.com/pubnub/java/blob/master/_autodocs/api-reference/message-history.md Sets the start timetoken for message retrieval. ```java public History start(Long start) ``` -------------------------------- ### Receiving Presence Events Source: https://github.com/pubnub/java/blob/master/_autodocs/api-reference/presence-state.md Example of how to set up a listener to receive and process presence events, including enabling presence during subscription. ```APIDOC ## Receiving Presence Events ### Description This code demonstrates how to implement a `SubscribeCallback` to handle presence events and how to enable presence tracking when subscribing to channels. ### Usage 1. Implement the `presence` method in your `SubscribeCallback`. 2. Enable presence using `.withPresence()` when calling `.subscribe()`. ### Code Example ```java // Add a listener to handle presence events pubnub.addListener(new SubscribeCallback.BaseSubscribeCallback() { @Override public void presence(PubNub pubnub, PNPresenceEventResult presence) { System.out.println("Channel: " + presence.getChannel()); System.out.println("Event: " + presence.getEvent()); System.out.println("UUID: " + presence.getUuid()); System.out.println("Occupancy: " + presence.getOccupancy()); if (presence.getEvent().equals("state-change")) { System.out.println("New State: " + presence.getState()); } } }); // Enable presence with subscription pubnub.subscribe() .channels(Arrays.asList("room-1")) .withPresence() .execute(); ``` ``` -------------------------------- ### Activate Subscription and Listen for Events Source: https://github.com/pubnub/java/blob/master/_autodocs/api-reference/publish-subscribe.md Activate the subscription and set up a listener to handle incoming messages and presence events. This example shows how to process both types of events. ```java pubnub.subscribe() .channels(Arrays.asList("live-feed")) .withPresence() .execute(); // Listen for messages pubnub.addListener(new SubscribeCallback.BaseSubscribeCallback() { @Override public void message(PubNub pubnub, PNMessageResult message) { System.out.println("Message: " + message.getMessage()); } @Override public void presence(PubNub pubnub, PNPresenceEventResult presence) { System.out.println("Presence: " + presence.getEvent()); } }); ``` -------------------------------- ### Enable Automatic Subscriber Thread Start Source: https://github.com/pubnub/java/blob/master/_autodocs/configuration.md Configure the SDK to automatically start the subscription thread upon initialization. Set to false for manual control via listeners. ```java config.setStartSubscriberThread(true); ``` -------------------------------- ### Create Get Channel Metadata Endpoint Source: https://github.com/pubnub/java/blob/master/_autodocs/api-reference/pubnub.md Use this to create an endpoint for getting channel metadata. Returns a builder for fluent configuration. ```java public GetChannelMetadata.Builder getChannelMetadata() ``` -------------------------------- ### Get User Presence State Asynchronously Source: https://github.com/pubnub/java/blob/master/_autodocs/api-reference/presence-state.md Retrieves the current state for the default user on a specified channel. This example executes the retrieval asynchronously. ```java pubnub.getPresenceState() .channel("room-1") .async((result, status) -> { if (!status.isError()) { System.out.println("State: " + result.getStateByUuid()); } }); ``` -------------------------------- ### Handle Pagination Source: https://github.com/pubnub/java/blob/master/_autodocs/api-reference/message-history.md Provides an example of how to handle pagination for large result sets by checking for and fetching subsequent pages using cursors. ```java // Handle pagination via more cursors PNPage nextPage = result.getMore().get(channel); if (nextPage != null) { // Fetch next page } ``` -------------------------------- ### Unsubscribe Example Source: https://github.com/pubnub/java/blob/master/_autodocs/api-reference/publish-subscribe.md Demonstrates how to unsubscribe from a single channel or multiple channels and channel groups using the PubNub Java SDK. ```java // Unsubscribe from specific channel pubnub.unsubscribe() .channels(Arrays.asList("news")) .execute(); // Unsubscribe from all pubnub.unsubscribe() .channels(Arrays.asList("news", "updates")) .channelGroups(Arrays.asList("notifications")) .execute(); ``` -------------------------------- ### Subscribe to Channels and Channel Groups Source: https://github.com/pubnub/java/blob/master/_autodocs/api-reference/publish-subscribe.md Combine channel subscriptions with channel group subscriptions. This example subscribes to the 'main' channel and the 'notifications' channel group. ```java pubnub.subscribe() .channels(Arrays.asList("main")) .channelGroups(Arrays.asList("notifications")) .execute(); ``` -------------------------------- ### Subscribe to Multiple Channels Source: https://github.com/pubnub/java/blob/master/_autodocs/api-reference/publish-subscribe.md Use the SubscribeBuilder to subscribe to a list of channels. This example subscribes to 'news' and 'updates'. ```java pubnub.subscribe() .channels(Arrays.asList("news", "updates")) .execute(); ``` -------------------------------- ### Encryption Module Setup Source: https://github.com/pubnub/java/blob/master/_autodocs/README.md Demonstrates how to create and configure a legacy CryptoModule for end-to-end message encryption. The SDK automatically encrypts messages before sending and decrypts them upon receipt. ```APIDOC ## Encryption Module Setup ### Description End-to-end message encryption via CryptoModule. ### Code Example ```java CryptoModule crypto = CryptoModule.createLegacyCryptoModule( "my-cipher-key", // 16 or 32 chars true // useRandomInitializationVector ); config.setCryptoModule(crypto); // All messages automatically encrypted/decrypted pubnub.publish() .channel("private") .message("Secret") .async(callback); // Message encrypted before sending ``` ``` -------------------------------- ### Create Get UUID Metadata Endpoint Source: https://github.com/pubnub/java/blob/master/_autodocs/api-reference/pubnub.md Use this to create an endpoint for getting UUID metadata for a specific user. Returns a builder for fluent configuration. ```java public GetUUIDMetadata.Builder getUUIDMetadata() ``` -------------------------------- ### Timetoken Conversion Source: https://github.com/pubnub/java/blob/master/_autodocs/api-reference/message-history.md Demonstrates how to get the current timetoken, calculate a past timetoken, and convert a timetoken back to milliseconds. ```java // Get current timetoken long currentTimetoken = System.currentTimeMillis() * 10000; // Get timetoken for 1 hour ago long oneHourAgo = (System.currentTimeMillis() - 3600000) * 10000; // Convert timetoken to milliseconds long milliseconds = timetoken / 10000; ``` -------------------------------- ### Count Messages Since Specific Timetokens Example Source: https://github.com/pubnub/java/blob/master/_autodocs/api-reference/message-history.md Demonstrates how to count messages in multiple channels since specific points in time using timetokens provided per channel. ```java // Count messages since a point in time Map timetokens = new HashMap<>(); timetokens.put("news", 15683974046308224L); timetokens.put("updates", 15683974046308224L); pubnub.messageCounts() .channels(Arrays.asList("news", "updates")) .channelsTimetokenByChannel(timetokens) .async((result, status) -> { if (!status.isError()) { Map counts = result.getChannels(); counts.forEach((channel, count) -> { System.out.println(channel + ": " + count + " messages"); }); } }); ``` -------------------------------- ### Create Get All Channels Metadata Endpoint Source: https://github.com/pubnub/java/blob/master/_autodocs/api-reference/pubnub.md Use this to create an endpoint for retrieving metadata for all channels. Returns a GetAllChannelsMetadata endpoint. ```java public GetAllChannelsMetadata getAllChannelsMetadata() ``` -------------------------------- ### Here Now - Get Users in Channel Source: https://github.com/pubnub/java/blob/master/_autodocs/api-reference/presence-state.md Retrieve a list of users currently in specified channels, optionally including their UUIDs and state. This is useful for real-time user presence tracking. ```java pubnub.hereNow() .channels(Arrays.asList("room-1", "room-2")) .includeUUIDs(true) .includeState(true) .async((result, status) -> { if (!status.isError()) { for (PNHereNowChannelData channel : result.getChannels()) { System.out.println("Channel: " + channel.getChannelName()); System.out.println("Occupancy: " + channel.getOccupancy()); for (PNHereNowOccupantData occupant : channel.getOccupants()) { System.out.println(" User: " + occupant.getUuid()); System.out.println(" State: " + occupant.getState()); } } } }); ``` -------------------------------- ### Create Get All UUID Metadata Endpoint Source: https://github.com/pubnub/java/blob/master/_autodocs/api-reference/pubnub.md Use this to create an endpoint for retrieving UUID metadata for all users. Returns a GetAllUUIDMetadata endpoint. ```java public GetAllUUIDMetadata getAllUUIDMetadata() ``` -------------------------------- ### Get Users on a Channel (Java) Source: https://github.com/pubnub/java/blob/master/_autodocs/api-reference/pubnub.md Retrieves information about users currently on a channel, including occupancy and UUIDs. Use this to monitor channel activity. ```java pubnub.hereNow() .channels(Arrays.asList("my-channel")) .includeState(true) .includeUUIDs(true) .async(new PNCallback() { @Override public void onResponse(PNHereNowResult result, PNStatus status) { if (!status.isError()) { result.getChannels().forEach(channel -> { System.out.println("Occupancy: " + channel.getOccupancy()); channel.getOccupants().forEach(occupant -> System.out.println("User: " + occupant.getUuid()) ); }); } } }); ``` -------------------------------- ### PNBoundedPage Source: https://github.com/pubnub/java/blob/master/_autodocs/types.md Represents pagination with defined start and end cursors, useful for fetching data within a specific range. ```APIDOC ## PNBoundedPage ### Description Pagination with start and end cursors. ### Fields - **start** (String) - Start cursor - **end** (String) - End cursor ``` -------------------------------- ### Fetch Messages with Start Timetoken Source: https://github.com/pubnub/java/blob/master/_autodocs/api-reference/message-history.md Fetches messages published after a specific timetoken. Use this for paginating or retrieving messages from a certain point in time. ```java long lastTimetoken = 15683974046308224L; pubnub.fetchMessages() .channels(Arrays.asList("history")) .start(lastTimetoken) // Messages after this timetoken .async(callback); ``` -------------------------------- ### Fetch Messages with Timetoken Range Source: https://github.com/pubnub/java/blob/master/_autodocs/api-reference/message-history.md Shows how to efficiently fetch messages within a specific timetoken range by providing start and end points. ```java pubnub.fetchMessages() .channels(channels) .start(earlierTimetoken) .end(laterTimetoken) .async(callback); ``` -------------------------------- ### Implement Exponential Backoff for Rate Limiting Source: https://github.com/pubnub/java/blob/master/_autodocs/errors.md Implement exponential backoff to handle rate limiting errors (HTTP 429). This example retries the operation with increasing delays. ```java // Implement exponential backoff private void retryWithBackoff(Runnable operation, int attempt) { try { operation.run(); } catch (PubNubException e) { if (e.getStatusCode() == 429 && attempt < 5) { long delay = (long) Math.pow(2, attempt) * 1000; // 2^n seconds new Timer().schedule(new TimerTask() { @Override public void run() { retryWithBackoff(operation, attempt + 1); } }, delay); } else { throw e; } } } ``` -------------------------------- ### Here Now - Get Occupancy Count Source: https://github.com/pubnub/java/blob/master/_autodocs/api-reference/presence-state.md Retrieve only the occupancy count for specified channels without user details. Use this when you only need to know how many users are in a channel. ```java pubnub.hereNow() .channels(Arrays.asList("room-1", "room-2")) .includeUUIDs(false) .includeState(false) .async((result, status) -> { if (!status.isError()) { for (PNHereNowChannelData channel : result.getChannels()) { System.out.println("Channel: " + channel.getChannelName()); System.out.println("Occupancy: " + channel.getOccupancy()); } } }); ``` -------------------------------- ### Publish Operation with PNCallback Source: https://github.com/pubnub/java/blob/master/_autodocs/api-reference/callbacks.md Example of using PNCallback to handle the response of a publish operation. It checks for errors and logs the result or error details. The status object can be used to retry operations. ```java pubnub.publish() .channel("my-channel") .message("Hello") .async(new PNCallback() { @Override public void onResponse(PNPublishResult result, PNStatus status) { if (!status.isError()) { System.out.println("Published: " + result.getTimetoken()); } else { System.out.println("Error: " + status.getCategory()); status.retry(); // Retry the operation } } }); ``` -------------------------------- ### Implement Retry Logic for Publishing in Java Source: https://github.com/pubnub/java/blob/master/_autodocs/errors.md Implement retry logic for operations like publishing to ensure message delivery. This example shows a recursive approach with a delay based on the attempt number. ```java public void publishWithRetry(String channel, Object message, int maxRetries) { publishWithRetry(channel, message, 0, maxRetries); } private void publishWithRetry(String channel, Object message, int attempt, int maxRetries) { pubnub.publish() .channel(channel) .message(message) .async(new PNCallback() { @Override public void onResponse(PNPublishResult result, PNStatus status) { if (!status.isError()) { System.out.println("Published: " + result.getTimetoken()); } else if (attempt < maxRetries) { System.out.println("Retry attempt " + (attempt + 1)); new Timer().schedule(new TimerTask() { @Override public void run() { publishWithRetry(channel, message, attempt + 1, maxRetries); } }, 1000 * (attempt + 1)); } else { System.out.println("Failed after " + maxRetries + " retries"); } } }); } ``` -------------------------------- ### Where Now - Get Channels for Current User Source: https://github.com/pubnub/java/blob/master/_autodocs/api-reference/presence-state.md Retrieve a list of channels the current user is subscribed to. This is useful for understanding a user's current subscriptions. ```java pubnub.whereNow() .async((result, status) -> { if (!status.isError()) { System.out.println("Subscribed channels: " + result.getChannels()); } }); ``` -------------------------------- ### Delete Messages from Past Hour Example Source: https://github.com/pubnub/java/blob/master/_autodocs/api-reference/message-history.md Demonstrates how to delete messages from the past hour using the deleteMessages endpoint with start and end timetokens. ```java // Delete messages from past hour long now = System.currentTimeMillis() * 10000; long oneHourAgo = now - (60 * 60 * 1000 * 10000); pubnub.deleteMessages() .channel("old-messages") .start(oneHourAgo) .end(now) .async((result, status) -> { if (!status.isError()) { System.out.println("Messages deleted"); } }); ``` -------------------------------- ### Get Another User's Presence State Synchronously Source: https://github.com/pubnub/java/blob/master/_autodocs/api-reference/presence-state.md Retrieves the current state for a specific user (identified by UUID) on a channel. This example executes the retrieval synchronously. ```java // Get another user's state pubnub.getPresenceState() .channel("room-1") .uuid("alice-123") .sync(); ``` -------------------------------- ### Initialize PNConfiguration with Environment Variables Source: https://github.com/pubnub/java/blob/master/_autodocs/configuration.md Configure PNConfiguration programmatically by retrieving subscribe and publish keys from environment variables. Ensure a UserId is provided during initialization. ```java String subscribeKey = System.getenv("PUBNUB_SUBSCRIBE_KEY"); String publishKey = System.getenv("PUBNUB_PUBLISH_KEY"); PNConfiguration config = new PNConfiguration(new UserId("user-id")); config.setSubscribeKey(subscribeKey); config.setPublishKey(publishKey); PubNub pubNub = new PubNub(config); ``` -------------------------------- ### Specify Start Timetoken for Deletion Source: https://github.com/pubnub/java/blob/master/_autodocs/api-reference/message-history.md Set the start timetoken to define the beginning of the time range for message deletion (exclusive). ```java public DeleteMessages start(Long start) ``` -------------------------------- ### Set User Presence State Synchronously Source: https://github.com/pubnub/java/blob/master/_autodocs/api-reference/presence-state.md Use this to set custom state data for the current user on a channel. The state can be any JSON-serializable object. This example executes the operation synchronously and includes error handling. ```java try { PNSetStateResult result = pubnub.setPresenceState() .channel("room-1") .state(new JSONObject().put("status", "idle")) .sync(); System.out.println("State updated"); } catch (PubNubException e) { System.out.println("Error: " + e.getMessage()); } ``` -------------------------------- ### Initialize PubNub with Minimal Configuration Source: https://github.com/pubnub/java/blob/master/_autodocs/README.md Use this snippet to create a basic PNConfiguration object with a user ID, subscribe key, and publish key, then initialize the PubNub client. ```java PNConfiguration config = new PNConfiguration(new UserId("my-user-id")); config.setSubscribeKey("your-subscribe-key"); config.setPublishKey("your-publish-key"); PubNub pubNub = new PubNub(config); ``` -------------------------------- ### Deploy to Nexus with Gradle Source: https://github.com/pubnub/java/blob/master/DEVELOPER.md Deploys the project, including Javadoc, to Nexus. Requires Javadoc documentation to be enabled and the package to be configured on Sonatype. ```bash gradle clean build javadoc upload ``` -------------------------------- ### Development Configuration Source: https://github.com/pubnub/java/blob/master/_autodocs/configuration.md Use this configuration for development environments. It sets up basic keys and enables secure connections. ```java PNConfiguration config = new PNConfiguration(new UserId("dev-user")); config.setSubscribeKey("demo"); config.setPublishKey("demo"); config.setSecure(true); config.setLogVerbosity(PNLogVerbosity.BODY); config.setReconnectionPolicy(PNReconnectionPolicy.LINEAR); ``` -------------------------------- ### authKey Source: https://github.com/pubnub/java/blob/master/_autodocs/api-reference/pnconfiguration.md Sets or gets the authentication key for PAM operations. ```APIDOC ## authKey ### Description Authentication key for PAM operations. ### Method Signature ```java public String getAuthKey() public PNConfiguration setAuthKey(String authKey) ``` ### Parameters #### setAuthKey - **authKey** (String) - Optional - The authentication key for PAM operations. ``` -------------------------------- ### Configure Subscribe and Publish Keys Source: https://github.com/pubnub/java/blob/master/_autodocs/errors.md Ensure both subscribe and publish keys are set in the PNConfiguration to avoid missing configuration errors. ```java PNConfiguration config = new PNConfiguration(new UserId("user123")); config.setSubscribeKey("your-subscribe-key"); // Required config.setPublishKey("your-publish-key"); // Required for publishing ``` -------------------------------- ### Run Integration Tests with Gradle Source: https://github.com/pubnub/java/blob/master/src/integrationTest/README.md Execute integration tests using Gradle. Ensure your subscribe key is configured in `test.properties` or set as an environment variable. ```bash > export subKey= > ./gradlew build integrationTest ``` -------------------------------- ### publishKey Source: https://github.com/pubnub/java/blob/master/_autodocs/api-reference/pnconfiguration.md Sets or gets the PubNub publish key, which is required for publishing messages. ```APIDOC ## publishKey ### Description PubNub publish key (required for publishing messages). ### Method Signature ```java public String getPublishKey() public PNConfiguration setPublishKey(String publishKey) ``` ### Parameters #### setPublishKey - **publishKey** (String) - Required - The PubNub publish key. ``` -------------------------------- ### Initialize PNConfiguration with UserId Source: https://github.com/pubnub/java/blob/master/_autodocs/api-reference/pnconfiguration.md Use this constructor to initialize PNConfiguration with default values and a unique user ID. Ensure to set your subscribe and publish keys after initialization. ```java PNConfiguration config = new PNConfiguration(new UserId("user123")); config.setSubscribeKey("your-subscribe-key"); config.setPublishKey("your-publish-key"); ``` -------------------------------- ### subscribeKey Source: https://github.com/pubnub/java/blob/master/_autodocs/api-reference/pnconfiguration.md Sets or gets the PubNub subscribe key, which is required for subscription operations. ```APIDOC ## subscribeKey ### Description PubNub subscribe key (required for subscription operations). ### Method Signature ```java public String getSubscribeKey() public PNConfiguration setSubscribeKey(String subscribeKey) ``` ### Parameters #### setSubscribeKey - **subscribeKey** (String) - Required - The PubNub subscribe key. ``` -------------------------------- ### secretKey Source: https://github.com/pubnub/java/blob/master/_autodocs/api-reference/pnconfiguration.md Sets or gets the PubNub secret key, which is required for PAM v2 operations. ```APIDOC ## secretKey ### Description PubNub secret key (required for PAM v2 operations). ### Method Signature ```java public String getSecretKey() public PNConfiguration setSecretKey(String secretKey) ``` ### Parameters #### setSecretKey - **secretKey** (String) - Optional - The PubNub secret key. ``` -------------------------------- ### Initialize PubNub Instance Source: https://github.com/pubnub/java/blob/master/_autodocs/api-reference/pubnub.md Create a new PubNub instance using the PNConfiguration object. Ensure your subscribe and publish keys are set. ```java PNConfiguration config = new PNConfiguration(new UserId("user123")); config.setSubscribeKey("your-subscribe-key"); config.setPublishKey("your-publish-key"); PubNub pubnub = new PubNub(config); ``` -------------------------------- ### Message Count Source: https://github.com/pubnub/java/blob/master/_autodocs/api-reference/message-history.md Get the count of messages in specified channels for a given time range. ```APIDOC ## Message Count ### Description Get count of messages in channels for a timerange. ### Method Signature ```java public MessageCounts messageCounts() ``` ### Parameters #### channels ```java public MessageCounts channels(List channels) ``` Channels to count messages in. #### channelsTimetoken ```java public MessageCounts channelsTimetoken(Long channelsTimetoken) ``` Single timetoken for all channels (inclusive). #### channelsTimetokenByChannel ```java public MessageCounts channelsTimetokenByChannel(Map channelsTimetokenByChannel) ``` Specific timetoken per channel. ### Example ```java // Count messages since a point in time Map timetokens = new HashMap<>(); timetokens.put("news", 15683974046308224L); timetokens.put("updates", 15683974046308224L); pubnub.messageCounts() .channels(Arrays.asList("news", "updates")) .channelsTimetokenByChannel(timetokens) .async((result, status) -> { if (!status.isError()) { Map counts = result.getChannels(); counts.forEach((channel, count) -> { System.out.println(channel + ": " + count + " messages"); }); } }); ``` ``` -------------------------------- ### startSubscriberThread Source: https://github.com/pubnub/java/blob/master/_autodocs/api-reference/pnconfiguration.md Controls whether the subscriber thread starts automatically on PubNub initialization. Defaults to true. ```APIDOC ## startSubscriberThread ### Description Start subscriber thread automatically on PubNub initialization. ### Type boolean ### Default true ``` -------------------------------- ### Get File URL Endpoint Source: https://github.com/pubnub/java/blob/master/_autodocs/api-reference/pubnub.md Creates an endpoint to generate a downloadable URL for a specific file. ```java public GetFileUrl.Builder getFileUrl() ``` -------------------------------- ### Presence Builder Initialization Source: https://github.com/pubnub/java/blob/master/_autodocs/api-reference/presence-state.md Initializes the Presence Builder for fine-grained control over presence. ```APIDOC ## Presence Builder (Explicit Presence Control) The presence builder allows fine-grained control over which channels to maintain presence on. ```java public PresenceBuilder presence() ``` ``` -------------------------------- ### userId / uuid Source: https://github.com/pubnub/java/blob/master/_autodocs/api-reference/pnconfiguration.md Sets or gets the unique identifier for this client/user, required for subscription and presence operations. ```APIDOC ## userId / uuid ### Description Unique identifier for this client/user. Required for subscription and presence operations. ### Method Signature ```java public UserId getUserId() public void setUserId(@NotNull UserId userId) @Deprecated public void setUuid(@NotNull String uuid) ``` ### Parameters #### setUserId - **userId** (UserId) - Required - The unique identifier for the user. #### setUuid (Deprecated) - **uuid** (String) - Required - The unique identifier for the user (deprecated). ### Example ```java config.setUserId(new UserId("alice-user-1")); UserId currentUser = config.getUserId(); ``` ``` -------------------------------- ### PubNub Constructor Source: https://github.com/pubnub/java/blob/master/_autodocs/api-reference/pubnub.md Creates a new PubNub instance with the specified configuration. This is the primary way to initialize the SDK. ```APIDOC ## PubNub Constructor ### Description Creates a new PubNub instance with the specified configuration. ### Method Signature ```java public PubNub(@NotNull PNConfiguration initialConfig) ``` ### Parameters #### Path Parameters * **initialConfig** (PNConfiguration) - Required - Configuration object containing SDK settings ### Request Example ```java PNConfiguration config = new PNConfiguration(new UserId("user123")); config.setSubscribeKey("your-subscribe-key"); config.setPublishKey("your-publish-key"); PubNub pubnub = new PubNub(config); ``` ``` -------------------------------- ### Get Server Time Source: https://github.com/pubnub/java/blob/master/_autodocs/api-reference/message-history.md Retrieves the current timetoken from the PubNub server. This is useful for synchronizing operations. ```java pubnub.time() .async((result, status) -> { if (!status.isError()) { long timetoken = result.getTimetoken(); System.out.println("Server time: " + timetoken); } }); ``` -------------------------------- ### PNConfiguration Constructor Source: https://github.com/pubnub/java/blob/master/_autodocs/api-reference/pnconfiguration.md Initializes PNConfiguration with default values and a user ID. This is the recommended way to create a configuration object for a PubNub client instance. ```APIDOC ## PNConfiguration(UserId userId) ### Description Initializes PNConfiguration with default values and a user ID. ### Method ```java public PNConfiguration(@NotNull UserId userId) throws PubNubException ``` ### Parameters #### Path Parameters - **userId** (UserId) - Required - User identifier for this SDK instance ### Throws - **PubNubException** - if userId is null or empty ### Request Example ```java PNConfiguration config = new PNConfiguration(new UserId("user123")); config.setSubscribeKey("your-subscribe-key"); config.setPublishKey("your-publish-key"); ``` ``` -------------------------------- ### Get Message Actions Endpoint Source: https://github.com/pubnub/java/blob/master/_autodocs/api-reference/pubnub.md Creates an endpoint to retrieve message actions associated with a specific channel. ```java public GetMessageActions getMessageActions() ``` -------------------------------- ### Production PNConfiguration with Security Source: https://github.com/pubnub/java/blob/master/_autodocs/api-reference/pnconfiguration.md Configure PNConfiguration for production with your own keys, security enabled, and custom timeouts. Supports exponential reconnection policy and unlimited retries. ```java PNConfiguration config = new PNConfiguration(new UserId("user-id")); config.setSubscribeKey("your-subscribe-key"); config.setPublishKey("your-publish-key"); config.setSecretKey("your-secret-key"); config.setSecure(true); config.setConnectTimeout(10); config.setNonSubscribeRequestTimeout(15); config.setSubscribeTimeout(320); config.setPresenceTimeout(300); config.setReconnectionPolicy(PNReconnectionPolicy.EXPONENTIAL); config.setMaximumReconnectionRetries(-1); ``` -------------------------------- ### Configure PubNub with Keys and User ID Source: https://github.com/pubnub/java/blob/master/README.md Instantiate the PubNub client with your unique user ID, subscribe key, and publish key. This configuration is necessary before making any PubNub operations. ```java PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUserId")); pnConfiguration.setSubscribeKey("mySubscribeKey"); pnConfiguration.setPublishKey("myPublishKey"); PubNub pubnub = new PubNub(pnConfiguration); ``` -------------------------------- ### Publish with Required Parameters Source: https://github.com/pubnub/java/blob/master/_autodocs/errors.md Ensure all required parameters, such as channel and message, are provided when publishing. Optional parameters like 'shouldStore' can also be set. ```java // Ensure required parameters are provided pubnub.publish() .channel("my-channel") // Required .message(new JSONObject() // Required .put("text", "Hello")) .shouldStore(true) // Optional .async(callback); ``` -------------------------------- ### Get Server Timetoken Source: https://github.com/pubnub/java/blob/master/_autodocs/api-reference/pubnub.md Use this endpoint to retrieve the server timetoken. It requires an asynchronous callback to handle the response. ```java pubnub.time() .async(new PNCallback() { @Override public void onResponse(PNTimeResult result, PNStatus status) { if (!status.isError()) { System.out.println("Timetoken: " + result.getTimetoken()); } } }); ``` -------------------------------- ### Set Connect Timeout in Java Source: https://github.com/pubnub/java/blob/master/_autodocs/configuration.md Configure the maximum time in seconds to establish a connection. Default is 5 seconds. ```java config.setConnectTimeout(5) ```