Camel Components

PubNub

Since Camel 2.19

Both producer and consumer are supported

Camel PubNub component can be used to communicate with the PubNub data stream network for connected devices. This component uses pubnub java library.

Use cases include:

  • Chat rooms: Sending and receiving messages

  • Locations and Connected cars: dispatching taxi cabs

  • Smart sensors: Receiving data from a sensor for data visualizations

  • Health: Monitoring heart rate from a patient’s wearable device

  • Multiplayer games

  • Interactive media: audience-participating voting system

Maven users will need to add the following dependency to their pom.xml for this component:

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-pubnub</artifactId>
    <version>x.x.x</version>
    <!-- use the same version as your Camel core version -->
</dependency>

URI format

pubnub:channel[?options]

Where channel is the PubNub channel to publish or subscribe to.

Configuring Options

Camel components are configured on two separate levels:

  • component level

  • endpoint level

Configuring Component Options

At the component level, you set general and shared configurations that are, then, inherited by the endpoints. It is the highest configuration level.

For example, a component may have security settings, credentials for authentication, urls for network connection and so forth.

Some components only have a few options, and others may have many. Because components typically have pre-configured defaults that are commonly used, then you may often only need to configure a few options on a component; or none at all.

You can configure components using:

  • the Component DSL.

  • in a configuration file (application.properties, *.yaml files, etc).

  • directly in the Java code.

Configuring Endpoint Options

You usually spend more time setting up endpoints because they have many options. These options help you customize what you want the endpoint to do. The options are also categorized into whether the endpoint is used as a consumer (from), as a producer (to), or both.

Configuring endpoints is most often done directly in the endpoint URI as path and query parameters. You can also use the Endpoint DSL and DataFormat DSL as a type safe way of configuring endpoints and data formats in Java.

A good practice when configuring options is to use Property Placeholders.

Property placeholders provide a few benefits:

  • They help prevent using hardcoded urls, port numbers, sensitive information, and other settings.

  • They allow externalizing the configuration from the code.

  • They help the code to become more flexible and reusable.

The following two sections list all the options, firstly for the component followed by the endpoint.

Component Options

The PubNub component supports the following options which are listed below.

Name Description Default Type

configuration (common)

The shared configuration that the endpoints of this component start from.

PubNubConfiguration

uuid (common)

Required The user ID (UUID) of the PubNub client that the endpoint creates. No user ID is generated when it is not set. GETSTATE and SETSTATE also use it as the user whose presence state they get or set, unless the CamelPubNubUUID header is set.

String

bridgeErrorHandler (consumer)

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. Important: This is only possible if the 3rd party component allows Camel to be alerted if an exception was thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not possible. In other situations we may improve the Camel component to hook into the 3rd party component and make this possible for future releases. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored.

false

boolean

withPresence (consumer)

Whether to also subscribe to the presence events of the channel.

false

boolean

lazyStartProducer (producer)

Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing.

false

boolean

operation (producer)

The operation to perform. PUBLISH (used when not set) publishes the message body to the channel. FIRE sends the message body only to the PubNub Functions event handlers of the channel: subscribers do not receive it, and it is not stored in the history. HERENOW gets the occupancy of the channel with the user IDs and presence state of its subscribers. GETSTATE gets the presence state of a user on the channel. SETSTATE sets the message body (a JSON object) as the presence state of a user on the channel. GETHISTORY gets up to the 100 most recent messages stored for the channel. The CamelPubNubOperation header overrides this option.

Enum values:

  • HERENOW

  • GETSTATE

  • SETSTATE

  • GETHISTORY

  • PUBLISH

  • FIRE

String

autowiredEnabled (advanced)

Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching type, which then gets configured on the component. This can be used for automatic configuring JDBC data sources, JMS connection factories, AWS Clients, etc.

true

boolean

authKey (security)

Deprecated The auth key that the PubNub client sends with its requests, for the Access Manager (PAM v2). Default value notice: This setting is deprecated because it relates to deprecated Access Manager (PAM V2) and will be removed in the future. Please, migrate to new Access Manager (PAM V3) https://www.pubnub.com/docs/general/resources/migration-guides/pam-v3-migration.

String

publishKey (security)

The publish key from your PubNub account. Required for the PUBLISH and FIRE operations.

String

secretKey (security)

The secret key from your PubNub account. When set, the PubNub client signs its requests with it.

String

secure (security)

Whether the PubNub client connects to PubNub over HTTPS. When false, it uses HTTP.

true

boolean

subscribeKey (security)

The subscribe key from your PubNub account. Required when the endpoint creates the PubNub client, that is when the pubnub option is not set.

String

Endpoint Options

The PubNub endpoint is configured using URI syntax:

pubnub:channel

With the following path and query parameters:

Path Parameters

Name Description Default Type

channel (common)

Required The PubNub channel to publish to or subscribe to.

String

Query Parameters

Name Description Default Type

uuid (common)

Required The user ID (UUID) of the PubNub client that the endpoint creates. No user ID is generated when it is not set. GETSTATE and SETSTATE also use it as the user whose presence state they get or set, unless the CamelPubNubUUID header is set.

String

withPresence (consumer)

Whether to also subscribe to the presence events of the channel.

false

boolean

bridgeErrorHandler (consumer (advanced))

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. Important: This is only possible if the 3rd party component allows Camel to be alerted if an exception was thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not possible. In other situations we may improve the Camel component to hook into the 3rd party component and make this possible for future releases. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored.

false

boolean

exceptionHandler (consumer (advanced))

To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored.

ExceptionHandler

exchangePattern (consumer (advanced))

Sets the exchange pattern when the consumer creates an exchange.

Enum values:

  • InOnly

  • InOut

ExchangePattern

operation (producer)

The operation to perform. PUBLISH (used when not set) publishes the message body to the channel. FIRE sends the message body only to the PubNub Functions event handlers of the channel: subscribers do not receive it, and it is not stored in the history. HERENOW gets the occupancy of the channel with the user IDs and presence state of its subscribers. GETSTATE gets the presence state of a user on the channel. SETSTATE sets the message body (a JSON object) as the presence state of a user on the channel. GETHISTORY gets up to the 100 most recent messages stored for the channel. The CamelPubNubOperation header overrides this option.

Enum values:

  • HERENOW

  • GETSTATE

  • SETSTATE

  • GETHISTORY

  • PUBLISH

  • FIRE

String

lazyStartProducer (producer (advanced))

Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing.

false

boolean

pubnub (advanced)

Autowired A PubNub client to use instead of creating one. When set, the publishKey, subscribeKey, secretKey, authKey and secure options are not used, and the endpoint does not destroy the client when it stops.

PubNub

authKey (security)

Deprecated The auth key that the PubNub client sends with its requests, for the Access Manager (PAM v2). Default value notice: This setting is deprecated because it relates to deprecated Access Manager (PAM V2) and will be removed in the future. Please, migrate to new Access Manager (PAM V3) https://www.pubnub.com/docs/general/resources/migration-guides/pam-v3-migration.

String

publishKey (security)

The publish key from your PubNub account. Required for the PUBLISH and FIRE operations.

String

secretKey (security)

The secret key from your PubNub account. When set, the PubNub client signs its requests with it.

String

secure (security)

Whether the PubNub client connects to PubNub over HTTPS. When false, it uses HTTP.

true

boolean

subscribeKey (security)

The subscribe key from your PubNub account. Required when the endpoint creates the PubNub client, that is when the pubnub option is not set.

String

Message Headers

The PubNub component supports the following message header(s), which is/are listed below:

Name Description Default Type

CamelPubNubOperation (producer)

Constant: OPERATION

The operation to perform, instead of the operation option.

String

CamelPubNubTimeToken (common)

Constant: TIMETOKEN

The PubNub timetoken of the event.

Long

CamelPubNubChannel (consumer)

Constant: CHANNEL

The channel the message belongs to.

String

CamelPubNubOverrideChannel (producer)

Constant: OVERRIDE_CHANNEL

The channel to use instead of the channel configured on the endpoint.

String

CamelPubNubUUID (producer)

Constant: UUID

The user ID (UUID) whose presence state GETSTATE and SETSTATE get or set, instead of the uuid option.

String

CamelMessageTimestamp (consumer)

Constant: MESSAGE_TIMESTAMP

The PubNub timetoken of the received message or presence event, the same value as CamelPubNubTimeToken: a count of 100-nanosecond units since the epoch (not milliseconds).

Long

Message Body

The message body at each side of the PubNub component: Consumer is the body of the messages the consumer creates, Consumer reply the bodies a consumer that answers its caller can reply with, Producer input the bodies the producer can send or write, and Producer output the body after the producer.

Side Body Description

Consumer

pojo (com.pubnub.api.models.consumer.pubsub.PNMessageResult)

The PubNub PNMessageResult; its getMessage() is the payload as a Gson JsonElement. It converts to a String: a string message as its text, any other message as JSON. With withPresence, a presence event comes as a PNPresenceEventResult. The channel and timetoken are in the CamelPubNubChannel and CamelPubNubTimeToken headers.

  • With withPresence=true: pojo

Producer input

text, value, map, list or pojo

The message to publish or fire, serialized to JSON by the PubNub client: text is sent as a JSON string (not parsed), a Map or a POJO as a JSON object, bytes as an array of numbers; a stream or a file fails, and an empty body fails. SETSTATE needs a Map or a POJO (a JSON object); the other operations do not read the body.

  • With operation=SETSTATE: map or pojo

  • With operation=GETHISTORY: any

  • With operation=GETSTATE: any

  • With operation=HERENOW: any

Producer output

unchanged

PUBLISH and FIRE leave the body unchanged, with the timetoken in the CamelPubNubTimeToken header. GETHISTORY gives a List of PNHistoryItemResult; GETSTATE, HERENOW and SETSTATE the result object of the PubNub client.

  • With operation=GETHISTORY: list or unchanged

  • With operation=GETSTATE: pojo (com.pubnub.api.models.consumer.presence.PNGetStateResult)

  • With operation=HERENOW: pojo (com.pubnub.api.models.consumer.presence.PNHereNowResult)

  • With operation=SETSTATE: pojo (com.pubnub.api.models.consumer.presence.PNSetStateResult)

The bodies are the ones with the default options. A side that is not listed is not known, and tooling does not guess it. The carriers, the sides and the tools that use them are described in Message Body Types.

Usage

Message body

The message body can contain any JSON serializable data, including Objects, Arrays, Integers, and Strings. Message data should not contain special Java V4 classes or functions as these will not serialize. String content can include any single-byte or multibyte UTF-8.

Object serialization when sending is done automatically. Pass the full object as the message payload. PubNub will take care of object serialization.

When receiving the message body uses objects provided by the PubNub API. A message is a PNMessageResult, and getMessage() is the payload as a Gson JsonElement. The PNMessageResult converts to a String, so ${body} or convertBodyTo(String.class) gives the payload: a string message as its text, and any other message (an object, an array, a number) as JSON.

Examples

Publishing events

Default operation when producing. The following snippet publishes the event generated by PojoBean to the channel iot.

Java-only: publishing events with a bean processor
from("timer:mytimer")
    // generate some data as POJO.
    .bean(PojoBean.class)
    .to("pubnub:iot?publishKey=mypublishKey");

Fire events aka BLOCKS Event Handlers

See blocks catalog for all kinds of serverless functions that can be invoked. Example of geolocation lookup

Java-only: fire events with geolocation lookup
from("timer:geotimer")
    .process(exchange -> exchange.getIn().setBody(new Foo("bar", "TEXT")))
    .to("pubnub:eon-maps-geolocation-input?operation=fire&publishKey=mypubkey&subscribeKey=mysubkey");

from("pubnub:eon-map-geolocation-output?subscribeKey=mysubkey)
    // geolocation output will be logged here
    .log("${body}");

Subscribing to events

The following snippet listens for events on the iot channel. If you can add the option withPresence, you will also receive channel Join, Leave asf events.

  • Java

  • XML

  • YAML

from("pubnub:iot?subscribeKey=mySubscribeKey")
    .log("${body}")
    .to("mock:result");
<route>
  <from uri="pubnub:iot?subscribeKey=mySubscribeKey"/>
  <log message="${body}"/>
  <to uri="mock:result"/>
</route>
- route:
    from:
      uri: pubnub:iot
      parameters:
        subscribeKey: mySubscribeKey
      steps:
        - log:
            message: "${body}"
        - to:
            uri: mock:result

Performing operations

  • herenow: obtain information about the current state of a channel including a list of unique user-ids currently subscribed to the channel and the total occupancy count of the channel:

  • Java

  • XML

  • YAML

from("direct:control")
    .to("pubnub:myChannel?publishKey=mypublishKey&subscribeKey=mySubscribeKey&operation=herenow")
    .to("mock:result");
<route>
  <from uri="direct:control"/>
  <to uri="pubnub:myChannel?publishKey=mypublishKey&amp;subscribeKey=mySubscribeKey&amp;operation=herenow"/>
  <to uri="mock:result"/>
</route>
- route:
    from:
      uri: direct:control
      steps:
        - to:
            uri: pubnub:myChannel
            parameters:
              publishKey: mypublishKey
              subscribeKey: mySubscribeKey
              operation: herenow
        - to:
            uri: mock:result
  • setstate: used to set key/value pairs specific to a subscriber uuid:

Java-only: setting state with a bean processor
from("direct:control")
    .bean(StateGenerator.class)
    .to("pubnub:myChannel?publishKey=mypublishKey&subscribeKey=mySubscribeKey&operation=setstate&uuid=myuuid");
  • gethistory: Fetches historical messages of a channel:

  • Java

  • XML

  • YAML

from("direct:control")
    .to("pubnub:myChannel?publishKey=mypublishKey&subscribeKey=mySubscribeKey&operation=gethistory");
<route>
  <from uri="direct:control"/>
  <to uri="pubnub:myChannel?publishKey=mypublishKey&amp;subscribeKey=mySubscribeKey&amp;operation=gethistory"/>
</route>
- route:
    from:
      uri: direct:control
      steps:
        - to:
            uri: pubnub:myChannel
            parameters:
              publishKey: mypublishKey
              subscribeKey: mySubscribeKey
              operation: gethistory