[[ConfluenceContent]]
[[Twitter-Twitter]]
Twitter
~~~~~~~

*Available as of Camel 2.10*

The Twitter component enables the most useful features of the Twitter
API by encapsulating http://twitter4j.org/[Twitter4J]. It allows direct,
polling, or event-driven consumption of timelines, users, trends, and
direct messages. Also, it supports producing messages as status updates
or direct messages.

Twitter now requires the use of OAuth for all client application
authentication. In order to use camel-twitter with your account, you'll
need to create a new application within Twitter at
https://dev.twitter.com/apps/new and grant the application access to
your account. Finally, generate your access token and secret.

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

[source,xml]
----
<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-twitter</artifactId>
    <version>${camel-version}</version>
</dependency>
----

[[Twitter-URIformat]]
URI format
^^^^^^^^^^

[source]
----
twitter://endpoint[?options]
----

[[Twitter-TwitterComponent]]
Twitter component
^^^^^^^^^^^^^^^^^

The twitter component can be configured with the Twitter account
settings which is mandatory to configure before using.



// component options: START
The Twitter component supports 8 options which are listed below.



[width="100%",cols="2s,1m,8",options="header"]
|=======================================================================
| Name | Java Type | Description
| accessToken | String | The access token
| accessTokenSecret | String | The access token secret
| consumerKey | String | The consumer key
| consumerSecret | String | The consumer secret
| httpProxyHost | String | The http proxy host which can be used for the camel-twitter.
| httpProxyUser | String | The http proxy user which can be used for the camel-twitter.
| httpProxyPassword | String | The http proxy password which can be used for the camel-twitter.
| httpProxyPort | int | The http proxy port which can be used for the camel-twitter.
|=======================================================================
// component options: END



You can also configure these options directly in the endpoint.

[[Twitter-ConsumerEndpoints]]
Consumer endpoints
^^^^^^^^^^^^^^^^^^

Rather than the endpoints returning a List through one single route
exchange, camel-twitter creates one route exchange per returned object.
As an example, if "timeline/home" results in five statuses, the route
will be executed five times (one for each Status).

[width="100%",cols="10%,10%,10%,70%",options="header",]
|=======================================================================
|Endpoint |Context |Body Type |Notice
|directmessage |direct, polling |twitter4j.DirectMessage | 

|search |direct, polling |twitter4j.Status | 

|streaming/filter |event, polling |twitter4j.Status | 

|streaming/sample |event, polling |twitter4j.Status | 

|streaming/user |event, polling |twitter4j.Status |**Camel 2.16**: To
receive tweets from protected users and accounts.

|timeline/home |direct, polling |twitter4j.Status | 

|timeline/mentions |direct, polling |twitter4j.Status | 

|[line-through]*timeline/public* |[line-through]*direct, polling*
|[line-through]*twitter4j.Status* |[line-through]*@deprecated. Use
timeline/home or direct/home instead. Removed from *Camel 2.11*
onwards.*

|timeline/retweetsofme |direct, polling |twitter4j.Status | 

|timeline/user |direct, polling |twitter4j.Status | 

|[line-through]*trends/daily* |[line-through]**Camel 2.10.1:* direct,
polling* |[line-through]*twitter4j.Status* |[line-through]*@deprecated.
Removed from Camel 2.11 onwards.*

|[line-through]*trends/weekly* |[line-through]**Camel 2.10.1:* direct,
polling* |[line-through]*twitter4j.Status* |[line-through]*@deprecated.
Removed from Camel 2.11 onwards.*
|=======================================================================

[[Twitter-ProducerEndpoints]]
Producer endpoints
^^^^^^^^^^^^^^^^^^

[width="100%",cols="20%,80%",options="header",]
|==============================
|Endpoint |Body Type
|directmessage |String
|search |List<twitter4j.Status>
|timeline/user |String
|==============================

[[Twitter-URIOptions]]
URI options
^^^^^^^^^^^




// endpoint options: START
The Twitter component supports 43 endpoint options which are listed below:

[width="100%",cols="2s,1,1m,1m,5",options="header"]
|=======================================================================
| Name | Group | Default | Java Type | Description
| kind | common |  | String | *Required* What polling mode to use direct polling or event based. The event mode is only supported when the endpoint kind is event based.
| accessToken | common |  | String | The access token. Can also be configured on the TwitterComponent level instead.
| accessTokenSecret | common |  | String | The access secret. Can also be configured on the TwitterComponent level instead.
| consumerKey | common |  | String | The consumer key. Can also be configured on the TwitterComponent level instead.
| consumerSecret | common |  | String | The consumer secret. Can also be configured on the TwitterComponent level instead.
| user | common |  | String | Username used for user timeline consumption direct message production etc.
| bridgeErrorHandler | consumer | false | boolean | Allows for bridging the consumer to the Camel routing Error Handler which mean any exceptions occurred while the consumer is trying to pickup incoming messages or the likes will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions that will be logged at WARN/ERROR level and ignored.
| sendEmptyMessageWhenIdle | consumer | false | boolean | If the polling consumer did not poll any files you can enable this option to send an empty message (no body) instead.
| type | consumer | direct | EndpointType | Endpoint type to use. Only streaming supports event type.
| distanceMetric | consumer (advanced) | km | String | Used by the non-stream geography search to search by radius using the configured metrics. The unit can either be mi for miles or km for kilometers. You need to configure all the following options: longitude latitude radius and distanceMetric.
| exceptionHandler | consumer (advanced) |  | ExceptionHandler | To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this options is not in use. By default the consumer will deal with exceptions that will be logged at WARN/ERROR level and ignored.
| latitude | consumer (advanced) |  | Double | Used by the non-stream geography search to search by latitude. You need to configure all the following options: longitude latitude radius and distanceMetric.
| locations | consumer (advanced) |  | String | Bounding boxes created by pairs of lat/lons. Can be used for streaming/filter. A pair is defined as latlon. And multiple paris can be separated by semi colon.
| longitude | consumer (advanced) |  | Double | Used by the non-stream geography search to search by longitude. You need to configure all the following options: longitude latitude radius and distanceMetric.
| pollStrategy | consumer (advanced) |  | PollingConsumerPollStrategy | 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.
| radius | consumer (advanced) |  | Double | Used by the non-stream geography search to search by radius. You need to configure all the following options: longitude latitude radius and distanceMetric.
| twitterStream | consumer (advanced) |  | TwitterStream | To use a custom instance of TwitterStream
| exchangePattern | advanced | InOnly | ExchangePattern | Sets the default exchange pattern when creating an exchange
| synchronous | advanced | false | boolean | Sets whether synchronous processing should be strictly used or Camel is allowed to use asynchronous processing (if supported).
| backoffErrorThreshold | scheduler |  | int | The number of subsequent error polls (failed due some error) that should happen before the backoffMultipler should kick-in.
| backoffIdleThreshold | scheduler |  | int | The number of subsequent idle polls that should happen before the backoffMultipler should kick-in.
| backoffMultiplier | scheduler |  | int | 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.
| delay | scheduler | 60000 | long | Milliseconds before the next poll.
| greedy | scheduler | false | boolean | If greedy is enabled then the ScheduledPollConsumer will run immediately again if the previous run polled 1 or more messages.
| initialDelay | scheduler | 1000 | long | Milliseconds before the first poll starts.
| runLoggingLevel | scheduler | TRACE | LoggingLevel | The consumer logs a start/complete log line when it polls. This option allows you to configure the logging level for that.
| scheduledExecutorService | scheduler |  | ScheduledExecutorService | Allows for configuring a custom/shared thread pool to use for the consumer. By default each consumer has its own single threaded thread pool.
| scheduler | scheduler | none | ScheduledPollConsumerScheduler | To use a cron scheduler from either camel-spring or camel-quartz2 component
| schedulerProperties | scheduler |  | Map | To configure additional properties when using a custom scheduler or any of the Quartz2 Spring based scheduler.
| startScheduler | scheduler | true | boolean | Whether the scheduler should be auto started.
| timeUnit | scheduler | MILLISECONDS | TimeUnit | Time unit for initialDelay and delay options.
| useFixedDelay | scheduler | true | boolean | Controls if fixed delay or fixed rate is used. See ScheduledExecutorService in JDK for details.
| count | filter |  | Integer | Limiting number of results per page.
| filterOld | filter | true | boolean | Filter out old tweets that has previously been polled. This state is stored in memory only and based on last tweet id.
| keywords | filter |  | String | Can be used for search and streaming/filter. Multiple values can be separated with comma.
| lang | filter |  | String | The lang string ISO_639-1 which will be used for searching
| numberOfPages | filter | 1 | Integer | The number of pages result which you want camel-twitter to consume.
| sinceId | filter | 1 | long | The last tweet id which will be used for pulling the tweets. It is useful when the camel route is restarted after a long running.
| userIds | filter |  | String | To filter by user ids for streaming/filter. Multiple values can be separated by comma.
| httpProxyHost | proxy |  | String | The http proxy host which can be used for the camel-twitter. Can also be configured on the TwitterComponent level instead.
| httpProxyPassword | proxy |  | String | The http proxy password which can be used for the camel-twitter. Can also be configured on the TwitterComponent level instead.
| httpProxyPort | proxy |  | Integer | The http proxy port which can be used for the camel-twitter. Can also be configured on the TwitterComponent level instead.
| httpProxyUser | proxy |  | String | The http proxy user which can be used for the camel-twitter. Can also be configured on the TwitterComponent level instead.
|=======================================================================
// endpoint options: END




[[Twitter-Messageheaders]]
Message headers
^^^^^^^^^^^^^^^

[width="100%",cols="20%,80%",options="header",]
|=======================================================================
|Name |Description
|`CamelTwitterKeywords` |This header is used by the search producer to
change the search key words dynamically.

|`CamelTwitterSearchLanguage` |*Camel 2.11.0:* This header can override
the option of `lang` which set the search language for the search
endpoint dynamically

|`CamelTwitterCount` |*Camel 2.11.0* This header can override the option
of `count` which sets the max twitters that will be returned.

|`CamelTwitterNumberOfPages` |*Camel 2.11.0* This header can override
the option of `numberOfPages` which sets how many pages we want to
twitter returns.
|=======================================================================

[[Twitter-Messagebody]]
Message body
^^^^^^^^^^^^

All message bodies utilize objects provided by the Twitter4J API.

[[Twitter-Usecases]]
Use cases
^^^^^^^^^

NOTE: *API Rate Limits:* Twitter REST APIs encapsulated by http://twitter4j.org/[Twitter4J] are
subjected to https://dev.twitter.com/rest/public/rate-limiting[API Rate
Limiting]. You can find the per method limits in the
https://dev.twitter.com/rest/public/rate-limits[API Rate Limits]
documentation. Note that endpoints/resources not listed in that page are
default to 15 requests per allotted user per window.

[[Twitter-TocreateastatusupdatewithinyourTwitterprofile,sendthisproduceraStringbody]]
To create a status update within your Twitter profile, send this producer a String body:
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

[source,java]
----
from("direct:foo")
  .to("twitter://timeline/user?consumerKey=[s]&consumerSecret=[s]&accessToken=[s]&accessTokenSecret=[s]);
----

[[Twitter-Topoll,every60sec.,allstatusesonyourhometimeline]]
To poll, every 60 sec., all statuses on your home timeline:
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

[source,java]
----
from("twitter://timeline/home?type=polling&delay=60&consumerKey=[s]&consumerSecret=[s]&accessToken=[s]&accessTokenSecret=[s]")
  .to("bean:blah");
----

[[Twitter-TosearchforallstatuseswiththekeywordCamel]]
To search for all statuses with the keyword 'camel':
++++++++++++++++++++++++++++++++++++++++++++++++++++

[source,java]
----
from("twitter://search?type=direct&keywords=camel&consumerKey=[s]&consumerSecret=[s]&accessToken=[s]&accessTokenSecret=[s]")
  .to("bean:blah");
----

[[Twitter-Searchingusingaproducerwithstatickeywords]]
Searching using a producer with static keywords:
++++++++++++++++++++++++++++++++++++++++++++++++

[source,java]
----
from("direct:foo")
  .to("twitter://search?keywords=camel&consumerKey=[s]&consumerSecret=[s]&accessToken=[s]&accessTokenSecret=[s]");
----

[[Twitter-Searchingusingaproducerwithdynamickeywordsfromheader]]
Searching using a producer with dynamic keywords from header:
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

In the `bar` header we have the keywords we want to search, so we can
assign this value to the `CamelTwitterKeywords` header:

[source,java]
----
from("direct:foo")
  .setHeader("CamelTwitterKeywords", header("bar"))
  .to("twitter://search?consumerKey=[s]&consumerSecret=[s]&accessToken=[s]&accessTokenSecret=[s]");
----

[[Twitter-Example]]
Example
^^^^^^^

See also the link:twitter-websocket-example.html[Twitter Websocket
Example].

[[Twitter-SeeAlso]]
See Also
^^^^^^^^

* link:configuring-camel.html[Configuring Camel]
* link:component.html[Component]
* link:endpoint.html[Endpoint]
* link:getting-started.html[Getting Started]

* link:twitter-websocket-example.html[Twitter Websocket Example]
