Configuration API for Java SDK
Breaking changes in 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 (< 9.0.0) 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.
Reuse the client instance
Create one PubNub client and reuse it for the lifetime of the user or session. Don't call PubNub.create() for every publish or operation. When a client is no longer needed, call destroy() to release its connections and background resources.
For more information, refer to Reuse the client instance.
Immutable configuration
Once a configuration object has been passed to the PubNub constructor, you can't change its properties.
If you require changing values dynamically consider using value overrides.
Method(s)
To create configuration instance you can use the following function in the Java SDK:
1import com.pubnub.api.java.v2.PNConfiguration;
2
3PNConfiguration.builder(UserId userId, String subscribeKey).build()
subscribeKeyrequired#subscribeKeyfrom the Admin Portal.publishKey#publishKeyfrom the Admin Portal (only required if publishing).secretKey#secretKey(only required for access operations, keep away from Android).logContentConfig#- Controls how much content to add to each log record. Refer to Log content configuration for more details.
cacheBusting#- If operating behind a misbehaving proxy, allow the client to shuffle the subdomains.
secure#- When
trueTLSis enabled. connectTimeout#- Maximum time to establish a connection, in seconds.
subscribeTimeout#- Subscribe request timeout, in seconds.
nonSubscribeRequestTimeout#- Non-subscribe request timeout, in seconds.
filterExpression#- Subscribe with a custom filter expression.
heartbeatNotificationOptions#Heartbeatnotification options. By default, the SDK alerts on failed heartbeats (equivalent toPNHeartbeatNotificationOptions.FAILURES).
Other options including all heartbeats (PNHeartbeatNotificationOptions.ALL) and no heartbeats (PNHeartbeatNotificationOptions.NONE) are supported.origin#- Custom
originif needed.
To request a custom domain, contact support and follow the request process. retryConfiguration#- Reconnection policy. Choose
None,Linear(delayInSec, maxRetryNumber, excludedOperations), orExponential(minDelayInSec, maxDelayInSec, maxRetryNumber, excludedOperations). You can exclude endpoint groups (for example,SUBSCRIBE). See SDK connection lifecycle. presenceTimeout#- How long the server considers the client alive for presence. The client sends periodic heartbeats to stay active. If no heartbeat arrives within the timeout, the client is marked inactive and a "timeout" event is emitted on the presence channel. Minimum
20seconds. heartbeatInterval#- How often the client sends heartbeats. To shorten presence timeout, set roughly to
(presenceTimeout / 2) - 1. Minimum3. Default0(disabled). proxy#- Instructs the SDK to use a
proxyconfiguration when communicating with PubNub servers. For more details see this https://docs.oracle.com/javase/7/docs/api/java/net/Proxy.html proxySelector#- Sets Java ProxySelector. For more details, refer to https://docs.oracle.com/javase/7/docs/api/java/net/ProxySelector.html
proxyAuthenticator#- Sets Java Authenticator. For more details refer to https://docs.oracle.com/javase/7/docs/api/java/net/Authenticator.html
googleAppEngineNetworking#- Enable Google App Engine networking.
suppressLeaveEvents#- When
truethe SDK doesn't send out theleaverequests. maintainPresenceState#- Whether the custom presence state information set using
pubnub.setPresenceState()should be sent every time the SDK sends a subscribe call. cryptoModule#- The cryptography module used for encryption and decryption of messages and files. Takes the
cipherKeyanduseRandomInitializationVectorparameters as arguments. For more information, refer to the cryptoModule section. includesInstanceIdentifier#- Whether to include a
PubNubCore.instanceIdwith every request. includeRequestIdentifier#- Whether to include a
PubNubCore.requestIdwith every request. maximumConnections#- Maximum number of concurrent asynchronous requests per host (
.async()calls only). This is a concurrency cap on in-flight async requests, not the size of the HTTP connection pool (seeconnectionPoolMaxIdleConnections). If you fan out.sync()calls and see requests backing up under load, raise concurrency in your own thread pool or switch those calls to.async(). connectionPoolMaxIdleConnections#- Maximum number of idle connections to keep in the HTTP connection pool. When set to
0, connection pooling is disabled and connections are closed immediately after use. Refer to OkHttp's ConnectionPool documentation for more details. connectionPoolKeepAliveDuration#- How long to keep idle connections alive in the HTTP connection pool before evicting them, in seconds. Refer to OkHttp's ConnectionPool documentation for more details.
certificatePinner#- Sets certificate pinner for HTTPS connections.
sslSocketFactory#- Sets the SSL socket factory for creating SSL sockets.
x509ExtendedTrustManager#- Sets the SSL trust manager for managing SSL certificates.
connectionSpec#- Sets the specifications for making connections (ConnectionSpec).
hostnameVerifier#- Manages the verification of the hostnames.
dedupOnSubscribe#- Enables deduplication on subscribe.
maximumMessagesCacheSize#- Sets the maximum size of messages cache.
pnsdkSuffixes#- Adds custom suffixes to the SDK version info.
managePresenceListManually#- Enables explicit presence control when set to true, affecting heartbeat and presence behavior.
Deprecated#authKey- This parameter is deprecated. Refer to Manage Access to understand the permission authorization flow and to Java Access Manager API for an overview of the API.
If Access Manager v2 is utilized, the client will use thisauthKeyin all restricted requests.
cryptoModule
cryptoModule encrypts and decrypts messages and files. From 6.3.6, you can configure the algorithms it uses. By default, encryption is disabled.
Each SDK includes two options: legacy 128‑bit encryption and recommended 256‑bit AES‑CBC. For background, see Message Encryption and File Encryption.
For configuration details, utilities, and examples, see 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.
Sample code
Required User ID
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.
1
Value override
You can provide updated values for certain configuration options for a single request to any supported API with PnConfigurationOverride.from().
1
The configuration options you can override include:
subscribeKeypublishKeysecretKeyretryConfigurationuserIdincludeInstanceIdentifierincludeRequestIdentifiercryptoModuleconnectTimeoutnonSubscribeReadTimeout
Initialization
Add PubNub to your project using one of the procedures under Getting Started.
Description
Initialize the PubNub Client API before using any APIs. This sets account-level credentials such as publishKey and subscribeKey.
Method(s)
Initialize PubNub with:
1
pnConfigurationrequired#- Goto Configuration for more details.
Sample code
Initialize the PubNub client API
Required User ID
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.
1
Returns
Returns the PubNub instance to call APIs such as publish(), subscribe(), history(), and hereNow().
Other examples
Initialize a non-secure client
Required User ID
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.
1
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 User ID
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.
1
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 User ID
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.
1
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. See Enable the features your app calls.
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 User ID
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.
1
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 User ID
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.
1
HTTP/2
The Java SDK's HTTP transport is built on OkHttp, which negotiates HTTP/2 automatically over TLS using ALPN and falls back to HTTP/1.1 when the origin doesn't support it.
HTTP/2 requires a compatible origin
HTTP/2 is only negotiated over TLS. Keep secure set to true (the default), since setting it to false produces http:// URLs, and OkHttp doesn't support HTTP/2 over cleartext (h2c).
The default origin, ps.pndsn.com, serves HTTP/1.1 only. To actually get HTTP/2, set origin to an HTTP/2-capable endpoint provisioned for your keyset. For background on HTTP/2 support across PubNub origins, refer to Data transport & protocols.
To confirm which protocol was negotiated for a request, check the debug-level network response logs. For more information, refer to Logging.
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
Subscriptionobject can receive updates only for the particular object for which it was created: channel, channel group, channel metadata, or user. - The
SubscriptionsSetobject can receive updates for all objects for which a list of subscription objects was created.
To work with these sources, the SDK provides local representations of server resources called SDK entities, so you can subscribe and add handlers per SDK entity. For details, see 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:
1import com.pubnub.api.java.v2.PNConfiguration;
2
3pnConfiguration.setUserId(String userId);
userIdrequired#userIdto be used as a device identifier. If you don't set theuserId, you won't be able to connect to PubNub.
1import com.pubnub.api.java.v2.PNConfiguration;
2
3pnConfiguration.getUserId();
This method doesn't take any arguments.
Sample code
Set user ID
Required User ID
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.
1
Get user ID
1
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. See Enable the features your app calls.
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)
-
setFilterExpression()1import com.pubnub.api.java.v2.PNConfiguration;
2
3pnConfiguration.setFilterExpression(String filterExpression);requiredfilterExpressionrequired#- PSV2 feature to
subscribewith a custom filter expression
-
getFilterExpression()1import com.pubnub.api.java.v2.PNConfiguration;
2
3pnConfiguration.getFilterExpression();
This method doesn't take any arguments.
Sample code
Set filter expression
Required User ID
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.
1
Get filter expression
1