Configuration API for PubNub Java SDK

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:

new PNConfiguration();
PropertiesTypeRequiredDefaultDescription
setSubscribeKeyStringYessubscribeKey from the Admin Portal.
setPublishKeyStringOptionalpublishKey from the Admin Portal (only required if publishing).
setSecretKeyStringOptionalsecretKey (only required for access operations, keep away from Android).
setUserIdUserIdYesuserId to use. The UserId object takes String as an argument. You should set a unique identifier for the user or the device that connects to PubNub.

It's a UTF-8 encoded string of up to 64 alphanumeric characters.

If you don't set the userId, you won't be able to connect to PubNub.
setLogVerbosityPNLogVerbosityOptionalPNLogVerbosity.NONESet PNLogVerbosity.BODY to enable debugging. To disable debugging use the option PNLogVerbosity.NONE
setAuthKeyStringOptionalNot setIf Access Manager is utilized, client will use this authKey in all restricted requests.
setCacheBustingBooleanOptionalIf operating behind a misbehaving proxy, allow the client to shuffle the subdomains.
setSecureBooleanOptionaltrueWhen true TLS is enabled.
setConnectTimeoutIntOptional5How long before the client gives up trying to connect with a subscribe call.
The value is in seconds.
setSubscribeTimeoutIntOptional310The subscribe request timeout.
The value is in seconds.
setNonSubscribeRequestTimeoutIntOptional10For non subscribe operations (publish, herenow, etc), how long to wait to connect to PubNub before giving up with a connection timeout error.
The value is in seconds.
setFilterExpressionStringOptionalNot setFeature to subscribe with a custom filter expression.
setHeartbeatNotificationOptionsPNHeartbeatNotificationOptionsOptionalPNHeartbeatNotificationOptions.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.
setOriginStringOptionalCustom origin if needed.
setReconnectionPolicyPNReconnectionPolicyOptionalPNReconnectionPolicy.NONESet to PNReconnectionPolicy.LINEAR for automatic reconnects. Use PNReconnectionPolicy.NONE to disable automatic reconnects.
Use PNReconnectionPolicy.EXPONENTIAL to set exponential retry interval.
setPresenceTimeoutIntOptional300Sets the custom presence server timeout.
The value is in seconds, and the minimum value is 20 seconds.
setPresenceTimeoutWithCustomIntervalInt, IntOptional300, 0Parameters are presence timeout (same as setPresenceTimeout) and custom heartbeat interval at which to ping the server.
setProxyProxyOptionalInstructs 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
setMaximumReconnectionRetriesIntOptional-1The config sets how many times to retry to reconnect before giving up.
setProxySelectorProxySelectorOptionalSets Java ProxySelector. For more details, refer to https://docs.oracle.com/javase/7/docs/api/java/net/ProxySelector.html
setProxyAuthenticatorAuthenticatorOptionalSets Java Authenticator. For more details refer to https://docs.oracle.com/javase/7/docs/api/java/net/Authenticator.html
setGoogleAppEngineNetworkingBooleanOptionalEnable Google App Engine networking.
setSuppressLeaveEventsBooleanOptionalfalseWhen true the SDK doesn't send out the leave requests.
requestMessageCountThresholdIntOptional100PNRequestMessageCountExceededCategory is thrown when the number of messages into the payload is above requestMessageCountThreshold.
setDisableTokenManagerBooleanOptionalfalseDisables the TMS (Token Manager System) in a way that it won't authorize requests even if there are applicable tokens.
setCryptoModuleCryptoModule.createAesCbcCryptoModule(cipherKey, useRandomInitializationVector)

CryptoModule.createLegacyCryptoModulecipherKey, 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.
setCipherKeyStringOptionalIf cipher is passed, all communications to and from PubNub will be encrypted.
useRandomInitializationVectorBooleanOptionaltrueWhen true the initialization vector (IV) is random for all requests (not just for file upload). When false the IV is hard-coded for all requests except for file upload.
setUuidStringYesThis parameter is deprecated, use userId instead.

UUID to use. You should set a unique UUID to identify the user or the device that connects to PubNub.
If you don't set the UUID, you won't be able to connect to PubNub.
Disabling random initialization vector

Disable random initialization vector (IV) only for backward compatibility (<5.0.0) with existing applications. Never disable random IV on new applications.

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 pnConfiguration = new PNConfiguration();
// subscribeKey from Admin Portal
pnConfiguration.setSubscribeKey("SubscribeKey"); // required
// publishKey from Admin Portal (only required if publishing)
pnConfiguration.setPublishKey("PublishKey");
// the cryptography module used for encryption and decryption
pnConfiguration.cryptoModule = CryptoModule.createAesCbcCryptoModule("enigma", true):
// secretKey (only required for access operations, keep away from Android)
pnConfiguration.setSecretKey("SecretKey");
// UserId to be used as a device identifier
pnConfiguration.setUserId(new UserId("myUniqueUserId"));
// Enable Debugging
pnConfiguration.setLogVerbosity(PNLogVerbosity.BODY);
// if Access Manager is utilized, client will use this authKey in all restricted
// requests
show all 26 lines

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:

new PubNub(pnConfiguration);
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 pnConfiguration = new PNConfiguration();
pnConfiguration.setSubscribeKey("my_subkey");
pnConfiguration.setPublishKey("my_pubkey");
pnConfiguration.setSecure(true);
pnConfiguration.setUserId(new UserId("myUniqueUserId"));
PubNub pubnub = new PubNub(pnConfiguration);

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 pnConfiguration = new PNConfiguration();
pnConfiguration.setSubscribeKey("SubscribeKey");
pnConfiguration.setPublishKey("PublishKey");
pnConfiguration.setSecure(false);
pnConfiguration.setUserId(new UserId("myUniqueUserId"));
PubNub pubnub = new PubNub(pnConfiguration);

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 pnConfiguration = new PNConfiguration();
pnConfiguration.setSubscribeKey("my_subkey");
PubNub pubnub = new PubNub(pnConfiguration);

Use a custom User ID

Set a custom userId to identify your users.

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.setSubscribeKey("mySubscribeKey");
pnConfiguration.setPublishKey("myPublishKey");
pnConfiguration.setUserId(new UserId("myUniqueUserId"));
PubNub pubnub = new PubNub(pnConfiguration);

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 pnConfiguration = new PNConfiguration();
pnConfiguration.setSubscribeKey("my_subkey");
pnConfiguration.setPublishKey("my_pubkey");
pnConfiguration.setSecure(true);
pnConfiguration.setUserId(new UserId("myUniqueUserId"));
PubNub pubnub = new PubNub(pnConfiguration);

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 pnConfiguration = new PNConfiguration();
pnConfiguration.setSubscribeKey("my_subkey");
pnConfiguration.setPublishKey("my_pubkey");
pnConfiguration.setSecretKey("my_secretkey");
pnConfiguration.setUserId(new UserId("myUniqueUserId"));
pnConfiguration.setSecure(true);

PubNub pubnub = new PubNub(pnConfiguration);

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 pnConfiguration = new PNConfiguration();
pnConfiguration.setSubscribeKey("mySubscribeKey");
pnConfiguration.setPublishKey("myPublishKey");
pnConfiguration.setSecretKey("mySecretKey");
pnConfiguration.setUserId(new UserId("myUniqueUserId"));
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("http://mydomain.com", 8080));
pnConfiguration.setProxy(proxy);
PubNub pubNub = new PubNub(pnConfiguration);

Event Listeners

You can be notified of connectivity status, message and presence notifications via the listeners.

Listeners should be added before calling the method.

Add Listeners

pubnub.addListener(new SubscribeCallback() {
// PubNub status
@Override
public void status(PubNub pubnub, PNStatus status) {
switch (status.getOperation()) {
// combine unsubscribe and subscribe handling for ease of use
case PNSubscribeOperation:
case PNUnsubscribeOperation:
// Note: subscribe statuses never have traditional errors,
// just categories to represent different issues or successes
// that occur as part of subscribe
switch (status.getCategory()) {
case PNConnectedCategory:
// No error or issue whatsoever.
case PNReconnectedCategory:
show all 129 lines

Remove Listeners

SubscribeCallback subscribeCallback = new SubscribeCallback() {
@Override
public void status(PubNub pubnub, PNStatus status) {

}

@Override
public void message(PubNub pubnub, PNMessageResult message) {

}

@Override
public void presence(PubNub pubnub, PNPresenceEventResult presence) {

}
show all 52 lines

Handling Disconnects

SubscribeCallback subscribeCallback = new SubscribeCallback() {
@Override
public void status(PubNub pubnub, PNStatus status) {
if (status.getCategory() == PNStatusCategory.PNUnexpectedDisconnectCategory) {
// internet got lost, do some magic and call reconnect when ready
pubnub.reconnect();
} else if (status.getCategory() == PNStatusCategory.PNTimeoutCategory) {
// do some magic and call reconnect when ready
pubnub.reconnect();
} else {
log.error(status);
}
}

@Override
show all 26 lines

Listener status events

CategoryDescription
PNNetworkUpCategoryThe SDK detected that the network is online.
PNNetworkDownCategoryThe SDK announces this when a connection isn't available, or when the SDK isn't able to reach the PubNub Data Stream Network.
PNNetworkIssuesCategoryA subscribe event experienced an exception when running. The SDK isn't able to reach the PubNub Data Stream Network. This may be due to many reasons, such as: the machine or device isn't connected to the internet; the internet connection has been lost; your internet service provider is having trouble; or, perhaps the SDK is behind a proxy.
PNReconnectedCategoryThe SDK was able to reconnect to PubNub.
PNConnectedCategorySDK subscribed with a new mix of channels. This is fired every time the channel or channel group mix changes.
PNAccessDeniedCategoryAccess Manager permission failure.
PNMalformedResponseCategoryJSON parsing crashed.
PNBadRequestCategoryThe server responded with a bad response error because the request is malformed.
PNDecryptionErrorCategoryIf using decryption strategies and the decryption fails.
PNTimeoutCategoryFailure to establish a connection to PubNub due to a timeout.
PNRequestMessageCountExceedCategoryThe SDK announces this error if requestMessageCountThreshold is set, and the number of messages received from PubNub (in-memory cache messages) exceeds the threshold.
PNUnknownCategoryReturned when the subscriber gets a non-200 HTTP response code from the server.

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