Configuration API for PubNub Java SDK
Java V4 complete API reference for building real-time applications on PubNub, including basic usage and sample code.
Configuration
Description
PNConfiguration
instance is storage for user-provided information which describe further PubNub client behavior. Configuration instance contain additional set of properties which allow to perform precise PubNub client configuration.
Method(s)
To create configuration
instance you can use the following function in the Java V4 SDK:
new PNConfiguration();
Properties | Type | Required | Defaults | Description |
---|---|---|---|---|
setSubscribeKey | String | Yes | subscribeKey from the Admin Portal. | |
setPublishKey | String | Optional | publishKey from the Admin Portal (only required if publishing). | |
setSecretKey | String | Optional | secretKey (only required for access operations, keep away from Android). | |
setCipherKey | String | Optional | If cipher is passed, all communications to and from PubNub will be encrypted. | |
setUuid | String | Yes | 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. | |
setLogVerbosity | PNLogVerbosity | Optional | PNLogVerbosity.NONE | Set PNLogVerbosity.BODY to enable debugging. To disable debugging use the option PNLogVerbosity.NONE |
setAuthKey | String | Optional | Not set | If Access Manager is utilized, client will use this authKey in all restricted requests. |
setCacheBusting | Boolean | Optional | If operating behind a misbehaving proxy, allow the client to shuffle the subdomains. | |
setSecure | Boolean | Optional | true | When true TLS is enabled. |
setConnectTimeout | Int | Optional | 5 | How long before the client gives up trying to connect with a subscribe call. The value is in seconds. |
setSubscribeTimeout | Int | Optional | 310 | The subscribe request timeout. The value is in seconds. |
setNonSubscribeRequestTimeout | Int | Optional | 10 | For 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. |
setFilterExpression | String | Optional | Not set | Feature to subscribe with a custom filter expression. |
setHeartbeatNotificationOptions | PNHeartbeatNotificationOptions | Optional | PNHeartbeatNotificationOptions.FAILURES | Heartbeat 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. |
setOrigin | String | Optional | Custom origin if needed. | |
setReconnectionPolicy | PNReconnectionPolicy | Optional | PNReconnectionPolicy.NONE | Set to PNReconnectionPolicy.LINEAR for automatic reconnects. Use PNReconnectionPolicy.NONE to disable automatic reconnects. Use PNReconnectionPolicy.EXPONENTIAL to set exponential retry interval. |
setPresenceTimeout | Int | Optional | 300 | Sets the custom presence server timeout. The value is in seconds, and the minimum value is 20 seconds. |
setPresenceTimeoutWithCustomInterval | Int, Int | Optional | 300 , 0 | Parameters are presence timeout (same as setPresenceTimeout) and custom heartbeat interval at which to ping the server. |
setProxy | Proxy | Optional | Instructs 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 | |
setMaximumReconnectionRetries | Int | Optional | -1 | The config sets how many times to retry to reconnect before giving up. |
setProxySelector | ProxySelector | Optional | Sets Java ProxySelector. For more details, refer to https://docs.oracle.com/javase/7/docs/api/java/net/ProxySelector.html | |
setProxyAuthenticator | Authenticator | Optional | Sets Java Authenticator. For more details refer to https://docs.oracle.com/javase/7/docs/api/java/net/Authenticator.html | |
setGoogleAppEngineNetworking | Boolean | Optional | Enable Google App Engine networking. | |
setSuppressLeaveEvents | Boolean | Optional | false | When true the SDK doesn't send out the leave requests. |
requestMessageCountThreshold | Int | Optional | 100 | PNRequestMessageCountExceededCategory is thrown when the number of messages into the payload is above requestMessageCountThreshold . |
setDisableTokenManager | Boolean | Optional | false | Disables the TMS (Token Manager System) in a way that it won't authorize requests even if there are applicable tokens. |
useRandomInitializationVector | Boolean | Optional | true | When 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. |
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.
Basic Usage
Note
Always set the UUID
to uniquely identify the user or device that connects to PubNub. This UUID
should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UUID
, 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");
// secretKey (only required for access operations, keep away from Android)
pnConfiguration.setSecretKey("SecretKey");
// if cipherKey is passed, all communicatons to/from pubnub will be encrypted
pnConfiguration.setCipherKey("cipherKey");
// UUID to be used as a device identifier
pnConfiguration.setUuid("myUniqueUUID");
// Enable Debugging
pnConfiguration.setLogVerbosity(PNLogVerbosity.BODY);
// if Access Manager is utilized, client will use this authKey in all restricted
// requests
pnConfiguration.setAuthKey("authKey");
// use SSL.
pnConfiguration.setSecure(true);
// PSV2 feature to subscribe with a custom filter expression
pnConfiguration.setFilterExpression("such=wow");
// heartbeat notifications, by default, the SDK will alert on failed heartbeats.
// other options such as all heartbeats or no heartbeats are supported.
pnConfiguration.setHeartbeatNotificationOptions(PNHeartbeatNotificationOptions.All);
pnConfiguration.setPresenceTimeout(120);
// the number of messages into the payload
pnConfiguration.setRequestMessageCountThreshold(100);
Initialization
Add PubNub to your project using one of the procedures defined under How to Get It
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 V4 SDK:
new PubNub(pnConfiguration);
Parameter Type Required Description pnConfiguration
PNConfiguration Yes Goto Configuration for more details.
Basic Usage
Initialize the PubNub client API:
Note
Always set the UUID
to uniquely identify the user or device that connects to PubNub. This UUID
should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UUID
, 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.setUuid("myUniqueUUID");
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:
Note
Always set the
UUID
to uniquely identify the user or device that connects to PubNub. ThisUUID
should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set theUUID
, you won't be able to connect to PubNub.PNConfiguration pnConfiguration = new PNConfiguration(); pnConfiguration.setSubscribeKey("SubscribeKey"); pnConfiguration.setPublishKey("PublishKey"); pnConfiguration.setSecure(false); pnConfiguration.setUuid("myUniqueUUID"); 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:Note
Always set the
UUID
to uniquely identify the user or device that connects to PubNub. ThisUUID
should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set theUUID
, you won't be able to connect to PubNub.PNConfiguration pnConfiguration = new PNConfiguration(); pnConfiguration.setSubscribeKey("my_subkey"); PubNub pubnub = new PubNub(pnConfiguration);
-
Set a custom
UUID
to identify your users.Note
Always set the
UUID
to uniquely identify the user or device that connects to PubNub. ThisUUID
should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set theUUID
, you won't be able to connect to PubNub.PNConfiguration pnConfiguration = new PNConfiguration(); pnConfiguration.setSubscribeKey("mySubscribeKey"); pnConfiguration.setPublishKey("myPublishKey"); pnConfiguration.setUuid("myUniqueUUID"); 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 withsetSecure
set totrue
. 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.Note
Always set the
UUID
to uniquely identify the user or device that connects to PubNub. ThisUUID
should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set theUUID
, 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.setUuid("myUniqueUUID"); PubNub pubnub = new PubNub(pnConfiguration);
- Initializing with Access Manager: Requires Access Manager add-onRequires that the Access Manager add-on is enabled for your key. See this page on enabling add-on features on your keys:
https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-Note
Anyone with the
secretKey
can grant and revoke permissions to your app. Never let yoursecretKey
be discovered, and to only exchange it / deliver it securely. Only use thesecretKey
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 PAM permissions, the API is initialized with the
secretKey
as in the following example:Note
Always set the
UUID
to uniquely identify the user or device that connects to PubNub. ThisUUID
should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set theUUID
, 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.setUuid("myUniqueUUID"); pnConfiguration.setSecure(true); PubNub pubnub = new PubNub(pnConfiguration);
Now that the pubnub object is instantiated the client will be able to access the PAM functions. The pubnub object will use the
secretKey
to sign all PAM messages to the PubNub Network. -
Note
Always set the
UUID
to uniquely identify the user or device that connects to PubNub. ThisUUID
should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set theUUID
, you won't be able to connect to PubNub.PNConfiguration pnConfiguration = new PNConfiguration(); pnConfiguration.setSubscribeKey("mySubscribeKey"); pnConfiguration.setPublishKey("myPublishKey"); pnConfiguration.setSecretKey("mySecretKey"); pnConfiguration.setUuid("myUniqueUUID"); Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("http://mydomain.com", 8080)); pnConfiguration.setProxy(proxy); PubNub pubNub = new PubNub(pnConfiguration);
Event Listeners
Description
You can be notified of connectivity status, message and presence notifications via the listeners.
Listeners should be added before calling the method.
Adding 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:
// Subscribe temporarily failed but reconnected.
// There is no longer any issue.
case PNDisconnectedCategory:
// No error in unsubscribing from everything.
case PNUnexpectedDisconnectCategory:
// Usually an issue with the internet connection.
// This is an error: handle appropriately.
case PNAccessDeniedCategory:
// PAM does not allow this client to subscribe to this
// channel and channel group configuration. This is
// another explicit error.
default:
// You can directly specify more errors by creating
// explicit cases for other error categories of
// `PNStatusCategory` such as `PNTimeoutCategory` or
// `PNMalformedFilterExpressionCategory` or
// `PNDecryptionErrorCategory`.
}
case PNHeartbeatOperation:
// Heartbeat operations can in fact have errors, so it's important to check first for an error.
// For more information on how to configure heartbeat notifications through the status
// PNObjectEventListener callback, refer to
// /docs/sdks/java/android/api-reference/configuration#configuration_basic_usage
if (status.isError()) {
// There was an error with the heartbeat operation, handle here
} else {
// heartbeat operation was successful
}
default: {
// Encountered unknown status type
}
}
}
// Messages
@Override
public void message(PubNub pubnub, PNMessageResult message) {
String messagePublisher = message.getPublisher();
System.out.println("Message publisher: " + messagePublisher);
System.out.println("Message Payload: " + message.getMessage());
System.out.println("Message Subscription: " + message.getSubscription());
System.out.println("Message Channel: " + message.getChannel());
System.out.println("Message timetoken: " + message.getTimetoken());
}
// Presence
@Override
public void presence(@NotNull PubNub pubnub, @NotNull PNPresenceEventResult presence) {
System.out.println("Presence Event: " + presence.getEvent());
// Can be join, leave, state-change or timeout
System.out.println("Presence Channel: " + presence.getChannel());
// The channel to which the message was published
System.out.println("Presence Occupancy: " + presence.getOccupancy());
// Number of users subscribed to the channel
System.out.println("Presence State: " + presence.getState());
// User state
System.out.println("Presence UUID: " + presence.getUuid());
// UUID to which this event is related
presence.getJoin();
// List of users that have joined the channel (if event is 'interval')
presence.getLeave();
// List of users that have left the channel (if event is 'interval')
presence.getTimeout();
// List of users that have timed-out off the channel (if event is 'interval')
presence.getHereNowRefresh();
// Indicates to the client that it should call 'hereNow()' to get the
// complete list of users present in the channel.
}
// Signals
@Override
public void signal(PubNub pubnub, PNSignalResult pnSignalResult) {
System.out.println("Signal publisher: " + signal.getPublisher());
System.out.println("Signal payload: " + signal.getMessage());
System.out.println("Signal subscription: " + signal.getSubscription());
System.out.println("Signal channel: " + signal.getChannel());
System.out.println("Signal timetoken: " + signal.getTimetoken());
}
// Message actions
@Override
public void messageAction(PubNub pubnub, PNMessageActionResult pnActionResult) {
PNMessageAction pnMessageAction = pnActionResult.getAction();
System.out.println("Message action type: " + pnMessageAction.getType());
System.out.println("Message action value: " + pnMessageAction.getValue());
System.out.println("Message action uuid: " + pnMessageAction.getUuid());
System.out.println("Message action actionTimetoken: " + pnMessageAction.getActionTimetoken());
System.out.println("Message action messageTimetoken: " + pnMessageAction.getMessageTimetoken());]
System.out.println("Message action subscription: " + pnActionResult.getSubscription());
System.out.println("Message action channel: " + pnActionResult.getChannel());
System.out.println("Message action timetoken: " + pnActionResult.getTimetoken());
}
// files
@Override
public void file(PubNub pubnub, PNFileEventResult pnFileEventResult) {
System.out.println("File channel: " + pnFileEventResult.getChannel());
System.out.println("File publisher: " + pnFileEventResult.getPublisher());
System.out.println("File message: " + pnFileEventResult.getMessage());
System.out.println("File timetoken: " + pnFileEventResult.getTimetoken());
System.out.println("File file.id: " + pnFileEventResult.downloadFile().getId());
System.out.println("File file.name: " + pnFileEventResult.downloadFile().getName());
System.out.println("File file.url: " + pnFileEventResult.downloadFile().getUrl());
}
});
Removing 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) {
}
@Override
public void signal(PubNub pubnub, PNSignalResult pnSignalResult) {
}
@Override
public void messageAction(PubNub pubnub, PNMessageActionResult pnActionResult) {
}
@Override
public void user(PubNub pubnub, PNUserResult pnUserResult) {
}
@Override
public void space(PubNub pubnub, PNSpaceResult pnSpaceResult) {
}
@Override
public void membership(PubNub pubnub, PNMembershipResult pnMembershipResult) {
}
@Override
public void file(PubNub pubnub, PNFileEventResult pnFileEventResult) {
}
};
pubnub.addListener(subscribeCallback);
// some time later
pubnub.removeListener(subscribeCallback);
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
public void message(PubNub pubnub, PNMessageResult message) {
}
@Override
public void presence(PubNub pubnub, PNPresenceEventResult presence) {
}
};
pubnub.addListener(subscribeCallback);
Listener status events
Category | Description |
---|---|
PNNetworkUpCategory | The SDK detected that the network is online. |
PNNetworkDownCategory | The SDK announces this when a connection isn't available, or when the SDK isn't able to reach the PubNub Data Stream Network. |
PNNetworkIssuesCategory | A 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. |
PNReconnectedCategory | The SDK was able to reconnect to PubNub. |
PNConnectedCategory | SDK subscribed with a new mix of channels. This is fired every time the channel or channel group mix changes. |
PNAccessDeniedCategory | PAM permission failure. |
PNMalformedResponseCategory | JSON parsing crashed. |
PNBadRequestCategory | The server responded with a bad response error because the request is malformed. |
PNDecryptionErrorCategory | If using decryption strategies and the decryption fails. |
PNTimeoutCategory | Failure to establish a connection to PubNub due to a timeout. |
PNRequestMessageCountExceedCategory | The SDK announces this error if requestMessageCountThreshold is set, and the number of messages received from PubNub (in-memory cache messages) exceeds the threshold. |
PNUnknownCategory | Returned when the subscriber gets a non-200 HTTP response code from the server. |
UUID
Description
These functions are used to set/get a user ID on the fly.
Method(s)
To set/get UUID
you can use the following method(s) in Java V4 SDK:
pnConfiguration.setUuid(String);
Parameter Type Required Defaults Description uuid
String Yes UUID
to be used as a device identifier. If you don't set theUUID
, you won't be able to connect to PubNub.
pnConfiguration.getUuid();
This method doesn't take any arguments.
Basic Usage
Note
Always set the UUID
to uniquely identify the user or device that connects to PubNub. This UUID
should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UUID
, you won't be able to connect to PubNub.
PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.setUuid("myUniqueUUID");
PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.getUuid();
Authentication Key
Description
Setter and getter for users auth key.
Method(s)
pnConfiguration.setAuthKey(String);
Parameter Type Required Description Auth Key
String Yes If Access Manager is utilized, client will use this authKey
in all restricted requests.pnConfiguration.getAuthKey();
This method doesn't take any arguments.
Basic Usage
PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.setAuthKey("authKey");
pnConfiguration.getAuthKey();
Returns
None.
Filter Expression
Requires Stream Controller add-onRequires that the Stream Controller add-on is enabled for your key. See this page on enabling add-on features on your keys:
https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-
Description
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/get filters you can use the following method. To learn more about filtering, refer to the Publish Messages documentation.
Method(s)
pnConfiguration.setFilterExpression(String);
Parameter Type Required Description filterExpression
String Yes PSV2 feature to subscribe
with a custom filter expressionpnConfiguration.getFilterExpression();
This method doesn't take any arguments.
Basic Usage
Note
Always set the UUID
to uniquely identify the user or device that connects to PubNub. This UUID
should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UUID
, you won't be able to connect to PubNub.
Note
Always set the UUID
to uniquely identify the user or device that connects to PubNub. This UUID
should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UUID
, you won't be able to connect to PubNub.
PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.setFilterExpression("such=wow");
pnConfiguration.getFilterExpression();