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> 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,*.yamlfiles, 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 |
|---|---|---|---|
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 | |
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 | |
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 | |
Used for enabling or disabling all consumer based health checks from this component. | true | boolean | |
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:
Query Parameters
| Name | Description | Default | Type |
|---|---|---|---|
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 | ||
The language of the weather descriptions in the response, sent as the lang query parameter. Enum values:
| en | WeatherLanguage | |
The format of the response from OpenWeatherMap: JSON, XML or HTML. XML and HTML are sent as the mode query parameter. Enum values:
| JSON | WeatherMode | |
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 | ||
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:
| WeatherUnits | ||
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:
| WeatherApi | ||
If the polling consumer did not poll any files, you can enable this option to send an empty message (no body) instead. | false | boolean | |
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 | |
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 | ||
Sets the exchange pattern when the consumer creates an exchange. Enum values:
| ExchangePattern | ||
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 | ||
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 | |
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 | ||
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 | ||
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 | ||
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 | ||
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 | ||
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 | ||
The longitude of the location, used together with lat. For a bounding box query (with rightLon and topLat) it is the left longitude. | String | ||
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 | ||
The top latitude of a bounding box query, which also needs lat, lon, rightLon and zoom. | String | ||
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 | ||
The map zoom level of a bounding box query, which also needs lat, lon, rightLon and topLat. | Integer | ||
The number of subsequent error polls (failed due some error) that should happen before the backoffMultipler should kick-in. | int | ||
The number of subsequent idle polls that should happen before the backoffMultipler should kick-in. | 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. | int | ||
Milliseconds before the next poll. | 3600000 | long | |
If greedy is enabled, then the ScheduledPollConsumer will run immediately again, if the previous run polled 1 or more messages. | false | boolean | |
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 | |
Milliseconds before the first poll starts. | 1000 | long | |
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 | |
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 | LoggingLevel | |
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 | ||
To use a cron scheduler from either camel-spring or camel-quartz component. Use value spring or quartz for built in scheduler. | none | Object | |
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 | ||
Whether the scheduler should be auto started. | true | boolean | |
Time unit for initialDelay and delay options. Enum values:
| MILLISECONDS | TimeUnit | |
Controls if fixed delay or fixed rate is used. See ScheduledExecutorService in JDK for details. | true | boolean | |
Required The API key of the OpenWeatherMap account, sent as the APPID query parameter of every request. | String | ||
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 | ||
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: | 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 | |
| Constant: | 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 |
| 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 |
Producer input |
| The body is not read: the query comes from the options, and the CamelWeatherLocation header overrides the location. |
Producer output |
| 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 |
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.
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&period=7 days&appid=APIKEY&geolocationAccessKey=IPSTACK_ACCESS_KEY&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&geolocationAccessKey=IPSTACK_ACCESS_KEY&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&appid=APIKEY&geolocationAccessKey=IPSTACK_ACCESS_KEY&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:
String json = template.requestBodyAndHeader("direct:start", "", "CamelWeatherLocation", "Paris,France&appid=APIKEY", String.class); And to get the weather at the current location, then:
String json = template.requestBodyAndHeader("direct:start", "", "CamelWeatherLocation", "current&appid=APIKEY", String.class);