PubNub Java SDK

repository·master·Indexed 20 days ago

https://github.com/pubnub/java

A real-time communication layer for Java and Android applications enabling low-latency data exchange via publish/subscribe, presence, signals, and files. This SDK supports asynchronous messaging, event listeners via SubscribeCallback, and file upload functionality. Note: This repository is no longer being updated; development has moved to the PubNub Kotlin SDK.

Tokens
2.6K
Snippets
8
Records
13
Agent score
71%

What's inside pubnub-java

  1. Handle PubNub status and connection categories

    master

    The status(PubNub pubnub, PNStatus status) callback is used to monitor the connection state.

    For PNSubscribeOperation and PNUnsubscribeOperation, check the status.getCategory() to determine the specific state:

    • PNConnectedCategory: Successfully connected.
    • PNReconnectedCategory: Temporary failure followed by reconnection.
    • PNDisconnectedCategory: Successfully unsubscribed.
    • PNUnexpectedDisconnectCategory: Error (e.g., internet connection issue).
    • PNAccessDeniedCategory: Error (e.g., PAM permission issue).

    For PNHeartbeatOperation, use status.isError() to check if the heartbeat failed.

  2. Run integration tests against a real PubNub application

    master

    The Java SDK includes integration tests that run against a live PubNub application. To run them, you must first create a dedicated application in the PubNub Admin Portal.

    Setup

    1. Create a dedicated PubNub application.
    2. Configure the subKey (Subscribe Key) in a test.properties file located in the project's root directory. You can use test.properties.example as a template.
    3. Alternatively, you can override properties by setting environment variables.

    Execution

    Use the Gradle integrationTest task to launch the tests. Note that these tests are not part of the standard CI pipeline and must be triggered manually.

    # Option 1: Using test.properties
    ./gradlew integrationTest
    
    # Option 2: Overriding via environment variables
    export subKey=<SUBSCRIBE_KEY>
    ./gradlew build integrationTest
  3. Add PubNub SDK dependencies to an IDE project

    master

    To manually add the PubNub libraries to your project in an IDE (such as IntelliJ IDEA), follow these steps:

    1. Navigate to File -> Project Structure -> Modules.
    2. Select the Main/Test module.
    3. Go to the Dependencies tab.
    4. Click the "+" (add) button.
    5. Select Library -> Java.
    6. Select and add all required libraries from the list.
    7. Click Apply to save changes.
  4. Build a shadowJar (Fat Jar)

    master

    To create a shadowJar (a Fat Jar containing all dependencies), you can use either of the following sequences of commands:

    Option 1 (Single command):

    gradle clean build shadowJar

    Option 2 (Step-by-step):

    gradle clean
    gradle clean test
    gradle build shadowJar
  5. Install the PubNub Java SDK

    master

    Integrate the PubNub Java SDK into your project using Maven or Gradle. Note that this repository is no longer being updated; development has moved to the PubNub Kotlin SDK.

    ### For Maven
    ```xml
    <dependency>
      <groupId>com.pubnub</groupId>
      <artifactId>pubnub-gson</artifactId>
      <version>6.4.5</version>
    </dependency>

    For Gradle

    implementation 'com.pubnub:pubnub-gson:6.4.5'
  6. Configure the PubNub client

    master

    To initialize a PubNub instance, create a PNConfiguration object. You must provide a UserId and set your SubscribeKey and PublishKey, which can be obtained from the PubNub Admin Portal.

    PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUserId"));
    pnConfiguration.setSubscribeKey("mySubscribeKey");
    pnConfiguration.setPublishKey("myPublishKey");
    
    PubNub pubnub = new PubNub(pnConfiguration);
  7. Handle file upload errors and status

    master

    When performing an asynchronous file upload, the PNCallback<Void> returns a PNStatus object. You should inspect this object to determine if the upload succeeded or failed.

    Status Mapping for Failures:

    • Access Denied: PNStatusCategory.PNAccessDeniedCategory (HTTP 401 or 403).
    • Bad Request: PNStatusCategory.PNBadRequestCategory (HTTP 400 or general failure).
    • Timeout: PNStatusCategory.PNTimeoutCategory (Socket timeout).
    • Connection Issues: PNStatusCategory.PNUnexpectedDisconnectCategory (Unknown host, Socket exception, or SSL exception).
    • Cancelled: PNStatusCategory.PNCancelledCategory (If the call was explicitly cancelled).

    If status.error() is true, inspect status.errorData() for the PNErrorData containing the error message and cause.

  8. Upload a file to PubNub

    master

    To upload a file, use the file upload functionality which utilizes FileUploadRequestDetails to configure the multipart request. The upload process supports encryption via a CryptoModule if provided.

    Note: The UploadFile class is an internal implementation of a RemoteAction. End-users should interact with the high-level PubNub client API that invokes this action.

    Key behaviors:

    • Encryption: If a CryptoModule is passed, the file content is encrypted before being sent.
    • Content-Type: The Content-Type of the file is determined by the Content-Type field within the formFields list. If not provided, it defaults to application/octet-stream.
    • Error Handling: Errors during upload are categorized using PNStatusCategory. Common categories include PNAccessDeniedCategory (401/403), PNBadRequestCategory (400), and PNTimeoutCategory (Socket timeouts).
    • Operation Type: This action is identified as PNOperationType.PNFileAction.
  9. Add event listeners with SubscribeCallback

    master

    To handle real-time events like messages, presence, and status changes, implement the SubscribeCallback abstract class and pass it to pubnub.addListener().

    Note: Since SubscribeCallback is an abstract class, you must implement all its methods even if they are not used in your specific implementation.

    pubnub.addListener(new SubscribeCallback() {
        @Override
        public void status(PubNub pubnub, PNStatus status) {
            // Handle status updates (e.g., connection, disconnection, errors)
        }
    
        @Override
        public void message(PubNub pubnub, PNMessageResult message) {
            // Handle incoming messages
        }
    
        @Override
        public void presence(@NotNull PubNub pubnub, @NotNull PNPresenceEventResult presence) {
            // Handle presence events (join, leave, timeout, etc.)
        }
    
        @Override
        public void signal(PubNub pubnub, PNSignalResult pnSignalResult) {
            // Handle signals
        }
    
        @Override
        public void messageAction(PubNub pubnub, PNMessageActionResult pnActionResult) {
            // Handle message actions
        }
    
        @Override
        public void file(PubNub pubnub, PNFileEventResult pnFileEventResult) {
            // Handle file events
        }
    });
  10. Publish a message to a channel

    master

    Use the publish() method to send data to a specific channel. The operation is asynchronous and provides a callback to handle success or failure. If a failure occurs, check the publishStatus category to diagnose the issue.

    pubnub.publish().channel(channelName)
      .message(messageJsonObject)
      .async((result, publishStatus) -> {
        if (!publishStatus.isError()) {
            // Message successfully published to specified channel.
        } else {
            // Handle message publish error
        }
    });
  11. Troubleshoot GenerateUploadUrl errors

    master

    When attempting to generate an upload URL, the following errors may occur during validation or response processing:

    • PNERROBJ_SUBSCRIBE_KEY_MISSING: The PubNub configuration is missing a subscribeKey.
    • PNERROBJ_CHANNEL_MISSING: The channel parameter provided is null or empty.
    • PNERROBJ_INTERNAL_ERROR:
      • Occurs if the server response is empty or null.
      • Occurs if the response does not contain the required key form parameter in the formFields list.