Camel Components

Twitter Direct Message

Since Camel 2.10

Both producer and consumer are supported

The Twitter Direct Message Component consumes/produces a user’s direct messages.

Consumer interval of time

When using the Direct Message consumer, it will consider only the last 30-day direct messages

Usage

The credentials of the Twitter application are component options, for example in application.properties:

camel.component.twitter-directmessage.consumer-key = {{env:TWITTER_CONSUMER_KEY}}
camel.component.twitter-directmessage.consumer-secret = {{env:TWITTER_CONSUMER_SECRET}}
camel.component.twitter-directmessage.access-token = {{env:TWITTER_ACCESS_TOKEN}}
camel.component.twitter-directmessage.access-token-secret = {{env:TWITTER_ACCESS_TOKEN_SECRET}}

The following route polls the direct messages of the account every minute, and logs their text. The consumer ignores the user of the URI:

- route:
    from:
      uri: twitter-directmessage:myaccount
      parameters:
        delay: 60000
      steps:
        - log:
            message: "${body.text}"

A producer sends the message body as a direct message to the user of the URI. The CamelTwitterUser header overrides it. A message with no body fails with an InvalidPayloadException, and no direct message is sent:

- route:
    from:
      uri: direct:notify
      steps:
        - to:
            uri: twitter-directmessage:camelfriend

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 Twitter Direct Message component supports the following options which are listed below.

Name Description Default Type

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

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

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

healthCheckConsumerEnabled (health)

Used for enabling or disabling all consumer based health checks from this component.

true

boolean

healthCheckProducerEnabled (health)

Used for enabling or disabling all producer based health checks from this component. Notice: Camel has by default disabled all producer based health-checks. You can turn on producer checks globally by setting camel.health.producersEnabled=true.

true

boolean

httpProxyHost (proxy)

The host name of an HTTP proxy to call the Twitter API through, for all endpoints of the component. When set, httpProxyPort must be set too. An endpoint can override it.

String

httpProxyPassword (proxy)

The password of httpProxyUser on the HTTP proxy, for all endpoints of the component. An endpoint can override it.

String

httpProxyPort (proxy)

The port of the HTTP proxy, required when httpProxyHost is set, for all endpoints of the component. An endpoint can override it.

int

httpProxyUser (proxy)

The user name to authenticate on the HTTP proxy with, together with httpProxyPassword, for all endpoints of the component. An endpoint can override it.

String

accessToken (security)

The OAuth access token of the Twitter account that the endpoints act as, for all endpoints of the component. An endpoint can override it.

String

accessTokenSecret (security)

The OAuth access token secret that goes with accessToken, for all endpoints of the component. An endpoint can override it.

String

consumerKey (security)

The OAuth consumer key (API key) of the Twitter app, for all endpoints of the component. An endpoint can override it. The four consumerKey, consumerSecret, accessToken and accessTokenSecret options are required, here or on the endpoint.

String

consumerSecret (security)

The OAuth consumer secret (API key secret) of the Twitter app, for all endpoints of the component. An endpoint can override it.

String

Endpoint Options

The Twitter Direct Message endpoint is configured using URI syntax:

twitter-directmessage:user

With the following path and query parameters:

Path Parameters

Name Description Default Type

user (common)

Required The screen name of the user that the producer sends the direct message to; the CamelTwitterUser header overrides it. The consumer ignores it, and reads the direct messages of the account of the access token.

String

Query Parameters

Name Description Default Type

sendEmptyMessageWhenIdle (consumer)

If the polling consumer did not poll any files, you can enable this option to send an empty message (no body) instead.

false

boolean

type (consumer)

How the consumer reads. With polling, each poll of the scheduler (see delay) reads the tweets or direct messages (sinceId and filterOld say which ones). With direct, the consumer also reads once when it starts, without a since id, and the scheduler then polls as well, without starting after sinceId. The producer does not use it.

Enum values:

  • polling

  • direct

polling

EndpointType

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

distanceMetric (consumer (advanced))

The unit of radius in a geographic search: km for kilometers or mi for miles. Set it together with radius: the twitter-search consumer does not apply the default km, and the poll fails when it is not set.

Enum values:

  • km

  • mi

km

String

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

extendedMode (consumer (advanced))

Whether every Twitter API call of the endpoint asks for the extended mode of tweets (tweet_mode=extended), so that getText() of a tweet returns its full text, also beyond 140 characters, instead of a truncated text.

true

boolean

latitude (consumer (advanced))

The latitude, in decimal degrees, of the center of the area of a geographic search. A twitter-search consumer sends the geocode of the search only when latitude, longitude and radius are all set. The twitter-search producer and the other schemes do not use it.

Double

locations (consumer (advanced))

Not used: no twitter-directmessage, twitter-search or twitter-timeline endpoint reads this option.

String

longitude (consumer (advanced))

The longitude, in decimal degrees, of the center of the area of a geographic search. A twitter-search consumer sends the geocode of the search only when latitude, longitude and radius are all set. The twitter-search producer and the other schemes do not use it.

Double

pollStrategy (consumer (advanced))

A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing you to provide your custom implementation to control error handling usually occurred during the poll operation before an Exchange have been created and being routed in Camel.

PollingConsumerPollStrategy

radius (consumer (advanced))

The radius, in the unit of distanceMetric, of the area of a geographic search around latitude and longitude. A twitter-search consumer sends the geocode of the search only when latitude, longitude and radius are all set. The twitter-search producer and the other schemes do not use it.

Double

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

count (filter)

The number of results to request per call (the count of the Twitter API): the tweets per page of a twitter-search search, the tweets per poll of a twitter-timeline polling consumer, and the direct messages per request of a twitter-directmessage consumer. It must be 1 or more. The CamelTwitterCount header overrides it for the twitter-search producer.

5

Integer

filterOld (filter)

Whether to skip what an earlier poll already returned, by keeping the highest id seen (in memory only, starting from sinceId). A twitter-search consumer sends that id as the since id of the search, so each poll returns newer tweets only; without it each poll repeats the whole search. A twitter-directmessage consumer drops the direct messages up to that id. It has no effect on a twitter-timeline consumer, which always polls with the since id of the newest tweet seen, nor on the twitter-search producer, which always sends the sinceId option.

true

boolean

lang (filter)

Restricts the search to tweets in this language, given as an ISO 639-1 code such as en (the lang of the Twitter search). Only twitter-search uses it; the CamelTwitterSearchLanguage header overrides it for the producer.

String

numberOfPages (filter)

For twitter-search, the number of pages of results to read per poll or per producer call: each further page is one more search request, and the reading stops early when there is no next page. A twitter-timeline polling consumer sends it as the page of the timeline request, so it selects which page to read, not how many. The CamelTwitterNumberOfPages header overrides it for the twitter-search producer. twitter-directmessage does not use it.

1

Integer

sinceId (filter)

The id to start after: only tweets or direct messages with a greater id are read (the since_id of the Twitter API), for example to resume after a restart. A polling consumer starts from it and then moves on to the newest id it receives: twitter-search sends it as the since id when filterOld is on, twitter-timeline always sends it (it must be 1 or more), and twitter-directmessage drops the direct messages up to it when filterOld is on and it is above 1. The twitter-search producer sends it with every search unless the CamelTwitterSinceId header is set. A direct consumer does not use it.

1

long

userIds (filter)

Not used: no twitter-directmessage, twitter-search or twitter-timeline endpoint reads this option.

String

httpProxyHost (proxy)

The host name of an HTTP proxy to call the Twitter API through. When set, httpProxyPort must be set too. It overrides the httpProxyHost of the component.

String

httpProxyPassword (proxy)

The password of httpProxyUser on the HTTP proxy. It overrides the httpProxyPassword of the component.

String

httpProxyPort (proxy)

The port of the HTTP proxy, required when httpProxyHost is set. It overrides the httpProxyPort of the component.

Integer

httpProxyUser (proxy)

The user name to authenticate on the HTTP proxy with, together with httpProxyPassword. It overrides the httpProxyUser of the component.

String

backoffErrorThreshold (scheduler)

The number of subsequent error polls (failed due some error) that should happen before the backoffMultipler should kick-in.

int

backoffIdleThreshold (scheduler)

The number of subsequent idle polls that should happen before the backoffMultipler should kick-in.

int

backoffMultiplier (scheduler)

To let the scheduled polling consumer backoff if there has been a number of subsequent idles/errors in a row. The multiplier is then the number of polls that will be skipped before the next actual attempt is happening again. When this option is in use then backoffIdleThreshold and/or backoffErrorThreshold must also be configured.

int

delay (scheduler)

Milliseconds between two polls of the consumer, or in the unit of the timeUnit option. The Twitter endpoints default to 30 seconds.

30000

long

greedy (scheduler)

If greedy is enabled, then the ScheduledPollConsumer will run immediately again, if the previous run polled 1 or more messages.

false

boolean

healthCheckMaxPollDuration (scheduler)

How long a poll may run before the health check of the consumer reports DOWN. The health check is otherwise based on the polls that are done, so it stays UP while a poll hangs, for example on a read without timeout from a connection that went silent. A poll includes routing the messages it polled, so set this above the longest poll you expect. The poll is not interrupted. The value is in millis (not affected by timeUnit). The default 0 turns this off.

0

long

initialDelay (scheduler)

Milliseconds before the first poll starts.

1000

long

repeatCount (scheduler)

Specifies a maximum limit of number of fires. So if you set it to 1, the scheduler will only fire once. If you set it to 5, it will only fire five times. A value of zero or negative means fire forever.

0

long

runLoggingLevel (scheduler)

The consumer logs a start/complete log line when it polls. This option allows you to configure the logging level for that.

Enum values:

  • TRACE

  • DEBUG

  • INFO

  • WARN

  • ERROR

  • OFF

TRACE

LoggingLevel

scheduledExecutorService (scheduler)

Allows for configuring a custom/shared thread pool to use for the consumer. By default each consumer has its own single threaded thread pool.

ScheduledExecutorService

scheduler (scheduler)

To use a cron scheduler from either camel-spring or camel-quartz component. Use value spring or quartz for built in scheduler.

none

Object

schedulerProperties (scheduler)

To configure additional properties when using a custom scheduler or any of the Quartz, Spring based scheduler. This is a multi-value option with prefix: scheduler.

Map

startScheduler (scheduler)

Whether the scheduler should be auto started.

true

boolean

timeUnit (scheduler)

Time unit for initialDelay and delay options.

Enum values:

  • NANOSECONDS

  • MICROSECONDS

  • MILLISECONDS

  • SECONDS

  • MINUTES

  • HOURS

  • DAYS

MILLISECONDS

TimeUnit

useFixedDelay (scheduler)

Controls if fixed delay or fixed rate is used. See ScheduledExecutorService in JDK for details.

true

boolean

accessToken (security)

The OAuth access token of the Twitter account that the endpoint acts as. It overrides the accessToken of the component. The four consumerKey, consumerSecret, accessToken and accessTokenSecret options are required.

String

accessTokenSecret (security)

The OAuth access token secret that goes with accessToken. It overrides the accessTokenSecret of the component.

String

consumerKey (security)

The OAuth consumer key (API key) of the Twitter app. It overrides the consumerKey of the component. The four consumerKey, consumerSecret, accessToken and accessTokenSecret options are required.

String

consumerSecret (security)

The OAuth consumer secret (API key secret) of the Twitter app. It overrides the consumerSecret of the component.

String

sortById (sort)

Whether a consumer sorts the tweets of each poll by id, so the oldest is routed first. It sorts the tweets of twitter-search and twitter-timeline consumers; the direct messages of twitter-directmessage keep the order of the Twitter API, newest first. The twitter-search producer does not sort its list.

true

boolean

Message Headers

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

Name Description Default Type

CamelTwitterUser (common)

Constant: TWITTER_USER

The screen name of the user that the producer sends the direct message to, instead of the user of the endpoint URI.

String

CamelTwitterEventType (common)

Constant: TWITTER_EVENT_TYPE

What the consumer received: STATUS for a tweet of twitter-search or twitter-timeline, DIRECT_MESSAGE for a direct message of twitter-directmessage.

String

Message Body

The message body at each side of the Twitter Direct Message 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 (twitter4j.v1.DirectMessage)

One direct message of the account per exchange, with its text in getText(). It converts to text as the date, the sender id and the text.

Producer input

text, bytes, stream or file

The text of the direct message: bytes, a stream or a file are read as text, and a Map or a POJO is sent as its toString(). The CamelTwitterUser header overrides the user to send to. No body fails.

Producer output

unchanged

Unchanged.

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.