Configuration API for PubNub Java SDK

Breaking changes since v9.0.0

PubNub Java SDK version 9.0.0 unifies the codebases for Java and Kotlin SDKs, introduces a new way of instantiating the PubNub client, and changes asynchronous API callbacks and emitted status events. These changes can impact applications built with previous versions of the Java SDK.

For more details about what has changed, refer to Java/Kotlin SDK migration guide.

Java complete API reference for building real-time applications on PubNub, including basic usage and sample code.

Configuration

PNConfiguration instance is storage for user-provided information which describe further PubNub client behavior. Configuration instance contains additional set of properties which allow performing precise PubNub client configuration.

Method(s)

To create configuration instance you can use the following function in the Java SDK:

PNConfiguration.builder(userId, subscribeKey).build()
PropertiesTypeRequiredDefaultDescription
subscribeKeyStringYessubscribeKey from the Admin Portal.
publishKeyStringOptionalpublishKey from the Admin Portal (only required if publishing).
secretKeyStringOptionalsecretKey (only required for access operations, keep away from Android).
logVerbosityPNLogVerbosityOptionalPNLogVerbosity.NONESet PNLogVerbosity.BODY to enable debugging. To disable debugging use the option PNLogVerbosity.NONE
authKeyStringOptionalNot setIf Access Manager is utilized, client will use this authKey in all restricted requests.
cacheBustingBooleanOptionalIf operating behind a misbehaving proxy, allow the client to shuffle the subdomains.
secureBooleanOptionaltrueWhen true TLS is enabled.
connectTimeoutIntOptional5How long before the client gives up trying to connect with the server.
The value is in seconds.
subscribeTimeoutIntOptional310The subscribe request timeout.
The value is in seconds.
nonSubscribeRequestTimeoutIntOptional10For non subscribe operations (publish, herenow, etc), this property relates to a read timeout that is applied from the moment the connection between a client and the server has been successfully established. It defines a maximum time of inactivity between two data packets when waiting for the server’s response.
The value is in seconds.
filterExpressionStringOptionalNot setFeature to subscribe with a custom filter expression.
heartbeatNotificationOptionsPNHeartbeatNotificationOptionsOptionalPNHeartbeatNotificationOptions.FAILURESHeartbeat notification options. By default, the SDK alerts on failed heartbeats (equivalent to PNHeartbeatNotificationOptions.FAILURES).
Other options including all heartbeats (PNHeartbeatNotificationOptions.ALL) and no heartbeats (PNHeartbeatNotificationOptions.NONE) are supported.
originStringOptionalCustom origin if needed.
retryConfigurationRetryConfigurationOptionalRetryConfiguration.NoneCustom reconnection configuration parameters. You can specify one or more endpoint groups for which the retry policy won't be applied.

RetryConfiguration is the type of policy to be used.

Available values:
  • RetryConfiguration.None.INSTANCE
  • RetryConfiguration.Linear(delayInSec, maxRetryNumber, excludedOperations)
  • RetryConfiguration.Exponential(minDelayInSec, maxDelayInSec, maxRetryNumber, excludedOperations

excludedOperations takes a list of RetryableEndpointGroup enums, for example, RetryableEndpointGroup.SUBSCRIBE.

For more information, refer to Reconnection Policy.
presenceTimeoutIntOptional300Sets the custom presence server timeout.
The value is in seconds, and the minimum value is 20 seconds.
proxyProxyOptionalInstructs the SDK to use a proxy configuration when communicating with PubNub servers. For more details see this https://docs.oracle.com/javase/7/docs/api/java/net/Proxy.html
proxySelectorProxySelectorOptionalSets Java ProxySelector. For more details, refer to https://docs.oracle.com/javase/7/docs/api/java/net/ProxySelector.html
proxyAuthenticatorAuthenticatorOptionalSets Java Authenticator. For more details refer to https://docs.oracle.com/javase/7/docs/api/java/net/Authenticator.html
googleAppEngineNetworkingBooleanOptionalEnable Google App Engine networking.
suppressLeaveEventsBooleanOptionalfalseWhen true the SDK doesn't send out the leave requests.
maintainPresenceStateBooleanOptionaltrueWhether the state set using pubnub.setPresenceState() should be maintained for the current userId. This option works only when enableEventEngine is set to true.
cryptoModuleCryptoModule.createAesCbcCryptoModule(cipherKey, useRandomInitializationVector)

CryptoModule.createLegacyCryptoModule(cipherKey, useRandomInitializationVector)
OptionalNoneThe cryptography module used for encryption and decryption of messages and files. Takes the cipherKey and useRandomInitializationVector parameters as arguments. For more information, refer to the cryptoModule section.
includesInstanceIdentifierBooleanOptionalfalseWhether to include a PubNubCore.instanceId with every request.
includeRequestIdentifierBooleanOptionaltrueWhether to include a PubNubCore.requestId with every request.
maximumConnectionsInt?OptionalSets max requests per host (okhttp3.Dispatcher.setMaxRequestsPerHost).
certificatePinnerCertificatePinnerOptionalSets certificate pinner for HTTPS connections.
httpLoggingInterceptorHttpLoggingInterceptorOptionalSets a custom interceptor for logging network traffic.
sslSocketFactorySSLSocketFactoryOptionalSets the SSL socket factory for creating SSL sockets.
x509ExtendedTrustManagerX509ExtendedTrustManagerOptionalSets the SSL trust manager for managing SSL certificates.
connectionSpecConnectionSpecOptionalSets the specifications for making connections (ConnectionSpec).
hostnameVerifierHostnameVerifierOptionalManages the verification of the hostnames.
fileMessagePublishRetryLimitIntOptional5Specifies how many times publishing file messages should automatically retry before failing.
dedupOnSubscribeBooleanOptionalEnables deduplication on subscribe.
maximumMessagesCacheSizeIntOptionalSets the maximum size of messages cache.
pnsdkSuffixesMap<String,String>OptionalAdds custom suffixes to the SDK version info.
managePresenceListManuallyBooleanOptionalEnables explicit presence control when set to true, affecting heartbeat and presence behavior.

cryptoModule

cryptoModule provides encrypt/decrypt functionality for messages and files. From the 6.3.6 release on, you can configure how the actual encryption/decryption algorithms work.

Each PubNub SDK is bundled with two ways of encryption: the legacy encryption with 128-bit cipher key entropy and the recommended 256-bit AES-CBC encryption. For more general information on how encryption works, refer to the Message Encryption and File Encryption sections.

If you do not explicitly set the cryptoModule in your app and have the setCipherKey and useRandomInitializationVector params set in PubNub config, the client defaults to using the legacy encryption.

Legacy encryption with 128-bit cipher key entropy

You don't have to change your encryption configuration if you want to keep using the legacy encryption. If you want to use the recommended 256-bit AES-CBC encryption, you must explicitly set that in PubNub config.

cryptoModule configuration

To configure the cryptoModule to encrypt all messages/files, you can use the following methods in the Java SDK:

// encrypts using 256-bit AES-CBC cipher (recommended)
// decrypts data encrypted with the legacy and the 256-bit AES-CBC ciphers
pnConfiguration.cryptoModule = CryptoModule.createAesCbcCryptoModule("enigma", true):

// encrypts with 128-bit cipher key entropy (legacy)
// decrypts data encrypted with the legacy and the 256-bit AES-CBC ciphers
pnConfiguration.cryptoModule = CryptoModule.createLegacyCryptoModule("enigma", true);

Your client can decrypt content encrypted using either of the modules. This way, you can interact with historical messages or messages sent from older clients while encoding new messages using the more secure 256-bit AES-CBC cipher.

Older SDK versions

Apps built using the SDK versions lower than 6.3.6 will not be able to decrypt data encrypted using the 256-bit AES-CBC cipher. Make sure to update your clients or encrypt data using the legacy algorithm.

Basic Usage

Required UserId

Always set the userId to uniquely identify the user or device that connects to PubNub. This userId should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the userId, you won't be able to connect to PubNub.

PNConfiguration.Builder configBuilder = PNConfiguration.builder(new UserId("yourUserId"), "yourSubscribeKey");
// publishKey from Admin Portal (only required if publishing)
configBuilder.publishKey("PublishKey");
// the cryptography module used for encryption and decryption
configBuilder.cryptoModule = CryptoModule.createAesCbcCryptoModule("enigma", true):
// Enable Debugging
configBuilder.logVerbosity(PNLogVerbosity.BODY);
// if Access Manager is utilized, client will use this authKey in all restricted
// requests
configBuilder.authKey("authKey");
// use SSL.
configBuilder.secure(true);
// PSV2 feature to subscribe with a custom filter expression
configBuilder.filterExpression("such=wow");
PNConfiguration pnConfiguration = configBuilder.build();

Value override

You can provide updated values for certain configuration options for a single request to any supported API with PnConfigurationOverride.from().

PNConfiguration.Builder configBuilder = PNConfiguration.builder(new UserId("yourUserId"), "yourSubscribeKey");
configBuilder.publishKey("PublishKey");
configBuilder.cryptoModule = CryptoModule.createAesCbcCryptoModule("enigma", true):
PNConfiguration config = configBuilder.build();

// publish
PNConfiguration overrideConfig = PNConfigurationOverride.from(config)
.publishKey("overridePublishKey")
.build();

pubnub.publish().channel("myChannel").message("myMessage")
.overrideConfiguration(overrideConfig).sync();

The configuration options you can override include:

  • subscribeKey
  • publishKey
  • secretKey
  • retryConfiguration
  • userId
  • includeInstanceIdentifier
  • includeRequestIdentifier
  • authKey
  • cryptoModule
  • connectTimeout
  • nonSubscribeReadTimeout

Initialization

Add PubNub to your project using one of the procedures defined under Getting Started.

Description

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.

Method(s)

To initialize PubNub you can use the following method(s) in the Java SDK:

PNConfiguration.Builder configBuilder = PNConfiguration.builder(new UserId("yourUserId"), "yourSubscribeKey");
PubNub.create(configBuilder.build());
ParameterTypeRequiredDescription
pnConfigurationPNConfigurationYesGoto Configuration for more details.

Basic Usage

Initialize the PubNub client API

Required UserId

Always set the userId to uniquely identify the user or device that connects to PubNub. This userId should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the userId, you won't be able to connect to PubNub.

PNConfiguration.Builder configBuilder = PNConfiguration.builder(new UserId("yourUserId"), "yourSubscribeKey");
// publishKey from Admin Portal (only required if publishing)
configBuilder.publishKey("PublishKey");
PubNub pubNub = PubNub.create(configBuilder.build());

Returns

It returns the PubNub instance for invoking PubNub APIs like publish(), subscribe(), history(), hereNow(), etc.

Other Examples

Initialize a non-secure client

Required UserId

Always set the userId to uniquely identify the user or device that connects to PubNub. This userId should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the userId, you won't be able to connect to PubNub.

PNConfiguration.Builder configBuilder = PNConfiguration.builder(new UserId("yourUserId"), "yourSubscribeKey");
configBuilder.secure(false);
PubNub pubNub = PubNub.create(configBuilder.build());

Initialization for a Read-Only client

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:

Required UserId

Always set the userId to uniquely identify the user or device that connects to PubNub. This userId should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the userId, you won't be able to connect to PubNub.

PNConfiguration.Builder configBuilder = PNConfiguration.builder(new UserId("yourUserId"), "yourSubscribeKey");
PubNub pubNub = PubNub.create(configBuilder.build());

Initializing with SSL Enabled

This examples demonstrates how to enable PubNub Transport Layer Encryption with SSL. Just initialize the client with setSecure 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.

Required UserId

Always set the userId to uniquely identify the user or device that connects to PubNub. This userId should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the userId, you won't be able to connect to PubNub.

PNConfiguration.Builder configBuilder = PNConfiguration.builder(new UserId("yourUserId"), "yourSubscribeKey");
configBuilder.secure(true);
PubNub pubNub = PubNub.create(configBuilder.build());

Initializing with Access Manager

Requires Access Manager add-on

This method requires that the Access Manager add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.

Secure your secretKey

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.

When you init with secretKey, you get root permissions for the Access Manager. With this feature you don't have to grant access to your servers to access channel data. The servers get all access on all channels.

For applications that will administer Access Manager permissions, the API is initialized with the secretKey as in the following example:

Required UserId

Always set the userId to uniquely identify the user or device that connects to PubNub. This userId should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the userId, you won't be able to connect to PubNub.

PNConfiguration.Builder configBuilder = PNConfiguration.builder(new UserId("yourUserId"), "yourSubscribeKey");
configBuilder.secure(true);
configBuilder.secretKey("secretKey");
PubNub pubNub = PubNub.create(configBuilder.build());

Now that the pubnub object is instantiated the client will be able to access the Access Manager functions. The pubnub object will use the secretKey to sign all Access Manager messages to the PubNub Network.

How to Set Proxy

Required UserId

Always set the userId to uniquely identify the user or device that connects to PubNub. This userId should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the userId, you won't be able to connect to PubNub.

PNConfiguration.Builder configBuilder = PNConfiguration.builder(new UserId("yourUserId"), "yourSubscribeKey");
configBuilder.publishKey("myPublishKey");
configBuilder.secure(true);
configBuilder.secretKey("secretKey");
configBuilder.proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("http://mydomain.com", 8080)));
PubNub pubNub = PubNub.create(configBuilder.build());

Event Listeners

PubNub SDKs provide several sources for real-time updates:

  • The PubNub client can receive updates from all subscriptions: all channels, channel groups, channel metadata, and users metadata.
  • The Subscription object can receive updates only for the particular object for which it was created: channel, channel group, channel metadata, or user.
  • The SubscriptionsSet object can receive updates for all objects for which a list of subscription objects was created.

To facilitate working with those real-time update sources, PubNub SDKs use local representations of server entities that allow you to subscribe and add handlers on a per-entity basis. For more information, refer to Publish & Subscribe.

UserId

These functions are used to set/get a user ID on the fly.

Method(s)

To set/get userId you can use the following method(s) in Java SDK:

pnConfiguration.setUserId(UserId);
ParameterTypeRequiredDefaultDescription
UserIdStringYesuserId to be used as a device identifier. If you don't set the userId, you won't be able to connect to PubNub.
pnConfiguration.getUserId();

This method doesn't take any arguments.

Basic Usage

Set User ID

Required UserId

Always set the userId to uniquely identify the user or device that connects to PubNub. This userId should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the userId, you won't be able to connect to PubNub.

PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.setUserId(new UserId("myUniqueUserId"));

Get User ID

PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.getUserId();

Authentication Key

Setter and getter for users auth key.

Method(s)

  1. setAuthKey()

    pnConfiguration.setAuthKey(String);
    ParameterTypeRequiredDescription
    Auth KeyStringYesIf Access Manager is utilized, client will use this authKey in all restricted requests.
  2. getAuthKey()

    pnConfiguration.getAuthKey();

This method doesn't take any arguments.

Basic Usage

Set Auth Key

PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.setAuthKey("authKey");

Get Auth Key

pnConfiguration.getAuthKey();

Returns

None.

Filter Expression

Requires Stream Controller add-on

This method requires that the Stream Controller add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.

Stream filtering allows a subscriber to apply a filter to only receive messages that satisfy the conditions of the filter. The message filter is set by the subscribing client(s) but it is applied on the server side thus preventing unwanted messages (those that do not meet the conditions of the filter) from reaching the subscriber.

To set or get message filters, you can use the following method. To learn more about filtering, refer to the Publish Messages documentation.

Method(s)

  1. setFilterExpression()

    pnConfiguration.setFilterExpression(String);
    ParameterTypeRequiredDescription
    filterExpressionStringYesPSV2 feature to subscribe with a custom filter expression
  2. getFilterExpression()

    pnConfiguration.getFilterExpression();

This method doesn't take any arguments.

Basic Usage

Set Filter Expression

Required UserId

Always set the userId to uniquely identify the user or device that connects to PubNub. This userId should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the userId, you won't be able to connect to PubNub.

PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.setFilterExpression("such=wow");

Get Filter Expression

pnConfiguration.getFilterExpression();
Last updated on