Camel Components

Weather

Since Camel 2.12

Both producer and consumer are supported

The Weather component is used for polling weather information from Open Weather Map - a site that provides free global weather and forecast information. The information is returned as a json String object.

Camel will poll for updates to the current weather and forecasts once per hour by default. It can also be used to query the weather api based on the parameters defined on the endpoint which is used as producer.

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

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

URI format

weather://<unused name>[?options]

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 Weather 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

Endpoint Options

The Weather endpoint is configured using URI syntax:

weather:name

With the following path and query parameters:

Path Parameters

Name Description Default Type

name (common)

Required The name value is not used.

String

Query Parameters

Name Description Default Type

headerName (common)

The name of the header to store the response in, instead of the message body. The producer then leaves the body as it is, and the consumer sends an exchange without a body.

String

language (common)

The language of the weather descriptions in the response, sent as the lang query parameter.

Enum values:

  • en

  • ru

  • it

  • es

  • sp

  • uk

  • ua

  • de

  • pt

  • ro

  • pl

  • fi

  • nl

  • fr

  • bg

  • sv

  • se

  • zh_tw

  • zh

  • zh_cn

  • tr

  • hr

  • ca

en

WeatherLanguage

mode (common)

The format of the response from OpenWeatherMap: JSON, XML or HTML. XML and HTML are sent as the mode query parameter.

Enum values:

  • HTML

  • JSON

  • XML

JSON

WeatherMode

period (common)

The length of a forecast, sent as the cnt query parameter: the number of days of the daily forecast, or the number of 3-hour steps with weatherApi Hourly. Only the first number in the value is read, so 7 days is the same as 7, and a value with no number, or 0, is ignored. If empty, the current weather is queried instead of a forecast, except with weatherApi Hourly or Daily, which then get the forecast with the length that OpenWeatherMap uses by default.

String

units (common)

The units of measurement in the response, for example of temperature and wind speed, sent as the units query parameter. If not set, OpenWeatherMap uses its standard units, with the temperature in Kelvin.

Enum values:

  • IMPERIAL

  • METRIC

WeatherUnits

weatherApi (common)

The OpenWeatherMap API to call. Station queries weather stations instead of cities, for ids, for lat and lon with cnt, and for a bounding box. When period is set, Hourly gets the 3-hour forecast and any other value, or none, the daily forecast; without period, Hourly gets the 3-hour forecast and Daily the daily forecast, with the length that OpenWeatherMap uses by default, and any other value, or none, the current weather.

Enum values:

  • Current

  • Station

  • Hourly

  • Daily

WeatherApi

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

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

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

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

geoLocationProvider (advanced)

A custom org.apache.camel.component.weather.geolocation.GeoLocationProvider for the latitude and longitude of the location when location is empty or current, and none of lat and lon, zip or ids is set. The default looks up geolocationRequestHostIP with the ipstack API, and needs geolocationAccessKey.

GeoLocationProvider

httpClient (advanced)

To use a custom org.apache.hc.client5.http.impl.classic.CloseableHttpClient, for example one with an HTTP proxy, for the requests to OpenWeatherMap and to the default geoLocationProvider. By default each endpoint creates its own client, closes it when it stops, and creates a new one when it is started again. A client that is set is not closed by the endpoint.

CloseableHttpClient

cnt (filter)

The number of results, sent as the cnt query parameter, for example the number of cities or stations to find around lat and lon. The period option takes precedence over this option.

Integer

ids (filter)

The ID of a city, or of a station with weatherApi Station, or a comma-separated list of city IDs to get the current weather of all of them in one request. It is used when lat, lon and zip are not set, and takes precedence over the location option.

String

lat (filter)

The latitude of the location, used together with lon, and taking precedence over the zip, ids and location options. For a bounding box query (with rightLon and topLat) it is the bottom latitude. With cnt set, the query finds that many cities, or stations with weatherApi Station, around the point.

String

location (filter)

The city to get the weather for, by name and optionally a country code, for example London,uk. If empty or current, the latitude and longitude come from the geoLocationProvider. The lat and lon, zip and ids options take precedence over this option, and the CamelWeatherLocation header replaces it for the producer.

String

lon (filter)

The longitude of the location, used together with lat. For a bounding box query (with rightLon and topLat) it is the left longitude.

String

rightLon (filter)

The right longitude of a bounding box query, which also needs lat, lon, topLat and zoom. The query gets the weather of the cities in the box, or of the stations with weatherApi Station.

String

topLat (filter)

The top latitude of a bounding box query, which also needs lat, lon, rightLon and zoom.

String

zip (filter)

The zip code and the country code of the location, for example 94040,us. It is used when lat and lon are not set, and takes precedence over the ids and location options.

String

zoom (filter)

The map zoom level of a bounding box query, which also needs lat, lon, rightLon and topLat.

Integer

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 before the next poll.

3600000

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

appid (security)

Required The API key of the OpenWeatherMap account, sent as the APPID query parameter of every request.

String

geolocationAccessKey (security)

The access key of the ipstack API, which the default geoLocationProvider uses. It is needed only when the location is looked up: location is empty or current, and none of lat and lon, zip or ids is set.

String

geolocationRequestHostIP (security)

The IP address that the default geoLocationProvider looks up with the ipstack API to find the latitude and longitude of the location. It is needed only when the location is looked up, as for geolocationAccessKey.

String

Message Headers

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

Name Description Default Type

CamelWeatherLocation (producer)

Constant: WEATHER_LOCATION

The location to query, in the format of the location option, which this header replaces for the producer. The producer ignores it when lat and lon, zip or ids are set, and current or an empty value looks up the location.

String

CamelWeatherQuery (common)

Constant: WEATHER_QUERY

The URL of the request that the consumer or the producer sent to OpenWeatherMap, with its query parameters. The value of the APPID parameter is masked as xxxxxx.

String

Message Body

The message body at each side of the Weather 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

text (java.lang.String), as json

The OpenWeatherMap response as a String: JSON, or XML or HTML with mode. With headerName the response is in that header and the body is null.

Not known when mode or headerName is set.

Producer input

any

The body is not read: the query comes from the options, and the CamelWeatherLocation header overrides the location.

Producer output

text (java.lang.String), as json

The OpenWeatherMap response as a String: JSON, or XML or HTML with mode. With headerName the response is in that header and the body is left unchanged.

Not known when mode or headerName is set.

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

Exchange data format

Camel will deliver the body as a json formatted java.lang.String (see the mode option above).

Examples

In this sample we find the 7-day weather forecast for Madrid, Spain:

  • Java

  • XML

  • YAML

from("weather:foo?location=Madrid,Spain&period=7 days&appid=APIKEY&geolocationAccessKey=IPSTACK_ACCESS_KEY&geolocationRequestHostIP=LOCAL_IP")
    .to("jms:queue:weather");
<route>
  <from uri="weather:foo?location=Madrid,Spain&amp;period=7 days&amp;appid=APIKEY&amp;geolocationAccessKey=IPSTACK_ACCESS_KEY&amp;geolocationRequestHostIP=LOCAL_IP"/>
  <to uri="jms:queue:weather"/>
</route>
- route:
    from:
      uri: weather:foo
      parameters:
        location: "Madrid,Spain"
        period: "7 days"
        appid: APIKEY
        geolocationAccessKey: IPSTACK_ACCESS_KEY
        geolocationRequestHostIP: LOCAL_IP
      steps:
        - to:
            uri: jms:queue:weather

To just find the current weather for your current location, you can use this:

  • Java

  • XML

  • YAML

from("weather:foo?appid=APIKEY&geolocationAccessKey=IPSTACK_ACCESS_KEY&geolocationRequestHostIP=LOCAL_IP")
    .to("jms:queue:weather");
<route>
  <from uri="weather:foo?appid=APIKEY&amp;geolocationAccessKey=IPSTACK_ACCESS_KEY&amp;geolocationRequestHostIP=LOCAL_IP"/>
  <to uri="jms:queue:weather"/>
</route>
- route:
    from:
      uri: weather:foo
      parameters:
        appid: APIKEY
        geolocationAccessKey: IPSTACK_ACCESS_KEY
        geolocationRequestHostIP: LOCAL_IP
      steps:
        - to:
            uri: jms:queue:weather

And to find the weather using the producer, we do:

  • Java

  • XML

  • YAML

from("direct:start")
  .to("weather:foo?location=Madrid,Spain&appid=APIKEY&geolocationAccessKey=IPSTACK_ACCESS_KEY&geolocationRequestHostIP=LOCAL_IP");
<route>
  <from uri="direct:start"/>
  <to uri="weather:foo?location=Madrid,Spain&amp;appid=APIKEY&amp;geolocationAccessKey=IPSTACK_ACCESS_KEY&amp;geolocationRequestHostIP=LOCAL_IP"/>
</route>
- route:
    from:
      uri: direct:start
      steps:
        - to:
            uri: weather:foo
            parameters:
              location: "Madrid,Spain"
              appid: APIKEY
              geolocationAccessKey: IPSTACK_ACCESS_KEY
              geolocationRequestHostIP: LOCAL_IP

And we can send in a message with a header to get the weather for any location as shown:

Java-only: ProducerTemplate API usage
String json = template.requestBodyAndHeader("direct:start", "", "CamelWeatherLocation", "Paris,France&appid=APIKEY", String.class);

And to get the weather at the current location, then:

Java-only: ProducerTemplate API usage
String json = template.requestBodyAndHeader("direct:start", "", "CamelWeatherLocation", "current&appid=APIKEY", String.class);