You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@camel.apache.org by nf...@apache.org on 2023/03/17 11:40:31 UTC

[camel] 13/19: CAMEL-18995: camel-weather - Upgrade to HttpComponents 5.x

This is an automated email from the ASF dual-hosted git repository.

nfilotto pushed a commit to branch CAMEL-18995/upgrade-httpcomponents-5
in repository https://gitbox.apache.org/repos/asf/camel.git

commit 865bfb4269899956ad6de82c76eeb66dcc2b9363
Author: Nicolas Filotto <nf...@talend.com>
AuthorDate: Fri Mar 17 12:32:41 2023 +0100

    CAMEL-18995: camel-weather - Upgrade to HttpComponents 5.x
---
 components/camel-weather/pom.xml                   |  6 +-
 .../weather/WeatherEndpointConfigurer.java         |  4 +-
 .../apache/camel/component/weather/weather.json    |  2 +-
 .../component/weather/WeatherConfiguration.java    |  4 +-
 .../camel/component/weather/WeatherConsumer.java   | 73 +++++++++++++---------
 .../camel/component/weather/WeatherEndpoint.java   | 11 ++--
 .../camel/component/weather/WeatherProducer.java   | 65 ++++++++++---------
 .../geolocation/FreeGeoIpGeoLocationProvider.java  | 52 +++++++--------
 8 files changed, 121 insertions(+), 96 deletions(-)

diff --git a/components/camel-weather/pom.xml b/components/camel-weather/pom.xml
index 3bdddc179df..81dc0a30502 100644
--- a/components/camel-weather/pom.xml
+++ b/components/camel-weather/pom.xml
@@ -38,9 +38,9 @@
         </dependency>
 
         <dependency>
-            <groupId>org.apache.httpcomponents</groupId>
-            <artifactId>httpclient</artifactId>
-            <version>${httpclient4-version}</version>
+            <groupId>org.apache.httpcomponents.client5</groupId>
+            <artifactId>httpclient5</artifactId>
+            <version>${httpclient-version}</version>
         </dependency>
 
         <!-- Jackson -->
diff --git a/components/camel-weather/src/generated/java/org/apache/camel/component/weather/WeatherEndpointConfigurer.java b/components/camel-weather/src/generated/java/org/apache/camel/component/weather/WeatherEndpointConfigurer.java
index 03f3f49b6f4..185e87319ad 100644
--- a/components/camel-weather/src/generated/java/org/apache/camel/component/weather/WeatherEndpointConfigurer.java
+++ b/components/camel-weather/src/generated/java/org/apache/camel/component/weather/WeatherEndpointConfigurer.java
@@ -46,7 +46,7 @@ public class WeatherEndpointConfigurer extends PropertyConfigurerSupport impleme
         case "headername":
         case "headerName": target.getConfiguration().setHeaderName(property(camelContext, java.lang.String.class, value)); return true;
         case "httpclient":
-        case "httpClient": target.getConfiguration().setHttpClient(property(camelContext, org.apache.http.impl.client.CloseableHttpClient.class, value)); return true;
+        case "httpClient": target.getConfiguration().setHttpClient(property(camelContext, org.apache.hc.client5.http.impl.classic.CloseableHttpClient.class, value)); return true;
         case "ids": target.getConfiguration().setIds(property(camelContext, java.lang.String.class, value)); return true;
         case "initialdelay":
         case "initialDelay": target.setInitialDelay(property(camelContext, long.class, value)); return true;
@@ -118,7 +118,7 @@ public class WeatherEndpointConfigurer extends PropertyConfigurerSupport impleme
         case "headername":
         case "headerName": return java.lang.String.class;
         case "httpclient":
-        case "httpClient": return org.apache.http.impl.client.CloseableHttpClient.class;
+        case "httpClient": return org.apache.hc.client5.http.impl.classic.CloseableHttpClient.class;
         case "ids": return java.lang.String.class;
         case "initialdelay":
         case "initialDelay": return long.class;
diff --git a/components/camel-weather/src/generated/resources/org/apache/camel/component/weather/weather.json b/components/camel-weather/src/generated/resources/org/apache/camel/component/weather/weather.json
index b0172ed7151..d0864797e1b 100644
--- a/components/camel-weather/src/generated/resources/org/apache/camel/component/weather/weather.json
+++ b/components/camel-weather/src/generated/resources/org/apache/camel/component/weather/weather.json
@@ -46,7 +46,7 @@
     "pollStrategy": { "kind": "parameter", "displayName": "Poll Strategy", "group": "consumer (advanced)", "label": "consumer,advanced", "required": false, "type": "object", "javaType": "org.apache.camel.spi.PollingConsumerPollStrategy", "deprecated": false, "autowired": false, "secret": false, "description": "A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing you to provide your custom implementation to control error handling usually occurred during the poll operation  [...]
     "lazyStartProducer": { "kind": "parameter", "displayName": "Lazy Start Producer", "group": "producer (advanced)", "label": "producer,advanced", "required": false, "type": "boolean", "javaType": "boolean", "deprecated": false, "autowired": false, "secret": false, "defaultValue": false, "description": "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 other [...]
     "geoLocationProvider": { "kind": "parameter", "displayName": "Geo Location Provider", "group": "advanced", "label": "advanced", "required": false, "type": "object", "javaType": "org.apache.camel.component.weather.geolocation.GeoLocationProvider", "deprecated": false, "autowired": false, "secret": false, "configurationClass": "org.apache.camel.component.weather.WeatherConfiguration", "configurationField": "configuration", "description": "A custum geolocation provider to determine the  [...]
-    "httpClient": { "kind": "parameter", "displayName": "Http Client", "group": "advanced", "label": "advanced", "required": false, "type": "object", "javaType": "org.apache.http.impl.client.CloseableHttpClient", "deprecated": false, "autowired": false, "secret": false, "configurationClass": "org.apache.camel.component.weather.WeatherConfiguration", "configurationField": "configuration", "description": "To use an existing configured http client (for example with http proxy)" },
+    "httpClient": { "kind": "parameter", "displayName": "Http Client", "group": "advanced", "label": "advanced", "required": false, "type": "object", "javaType": "org.apache.hc.client5.http.impl.classic.CloseableHttpClient", "deprecated": false, "autowired": false, "secret": false, "configurationClass": "org.apache.camel.component.weather.WeatherConfiguration", "configurationField": "configuration", "description": "To use an existing configured http client (for example with http proxy)" },
     "cnt": { "kind": "parameter", "displayName": "Cnt", "group": "filter", "label": "filter", "required": false, "type": "integer", "javaType": "java.lang.Integer", "deprecated": false, "autowired": false, "secret": false, "configurationClass": "org.apache.camel.component.weather.WeatherConfiguration", "configurationField": "configuration", "description": "Number of results to be found" },
     "ids": { "kind": "parameter", "displayName": "Ids", "group": "filter", "label": "filter", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": false, "configurationClass": "org.apache.camel.component.weather.WeatherConfiguration", "configurationField": "configuration", "description": "List of id's of city\/stations. You can separate multiple ids by comma." },
     "lat": { "kind": "parameter", "displayName": "Lat", "group": "filter", "label": "filter", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": false, "configurationClass": "org.apache.camel.component.weather.WeatherConfiguration", "configurationField": "configuration", "description": "Latitude of location. You can use lat and lon options instead of location. For boxed queries this is the bottom latitude." },
diff --git a/components/camel-weather/src/main/java/org/apache/camel/component/weather/WeatherConfiguration.java b/components/camel-weather/src/main/java/org/apache/camel/component/weather/WeatherConfiguration.java
index 99c0c92d905..fc192fb6008 100644
--- a/components/camel-weather/src/main/java/org/apache/camel/component/weather/WeatherConfiguration.java
+++ b/components/camel-weather/src/main/java/org/apache/camel/component/weather/WeatherConfiguration.java
@@ -28,8 +28,8 @@ import org.apache.camel.spi.UriParam;
 import org.apache.camel.spi.UriParams;
 import org.apache.camel.spi.UriPath;
 import org.apache.camel.support.ObjectHelper;
-import org.apache.http.impl.client.CloseableHttpClient;
-import org.apache.http.impl.client.HttpClients;
+import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
+import org.apache.hc.client5.http.impl.classic.HttpClients;
 
 import static org.apache.camel.component.weather.WeatherLanguage.en;
 import static org.apache.camel.component.weather.WeatherMode.JSON;
diff --git a/components/camel-weather/src/main/java/org/apache/camel/component/weather/WeatherConsumer.java b/components/camel-weather/src/main/java/org/apache/camel/component/weather/WeatherConsumer.java
index 850f3dafcbb..3b9bc75afc7 100644
--- a/components/camel-weather/src/main/java/org/apache/camel/component/weather/WeatherConsumer.java
+++ b/components/camel-weather/src/main/java/org/apache/camel/component/weather/WeatherConsumer.java
@@ -18,13 +18,13 @@ package org.apache.camel.component.weather;
 
 import org.apache.camel.Exchange;
 import org.apache.camel.Processor;
+import org.apache.camel.RuntimeCamelException;
 import org.apache.camel.support.ScheduledPollConsumer;
 import org.apache.camel.util.ObjectHelper;
-import org.apache.http.HttpResponse;
-import org.apache.http.HttpStatus;
-import org.apache.http.client.HttpClient;
-import org.apache.http.client.methods.HttpGet;
-import org.apache.http.util.EntityUtils;
+import org.apache.hc.client5.http.classic.HttpClient;
+import org.apache.hc.client5.http.classic.methods.HttpGet;
+import org.apache.hc.core5.http.HttpStatus;
+import org.apache.hc.core5.http.io.entity.EntityUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -56,33 +56,48 @@ public class WeatherConsumer extends ScheduledPollConsumer {
         HttpClient httpClient = getEndpoint().getConfiguration().getHttpClient();
         HttpGet getMethod = new HttpGet(query);
         try {
-            HttpResponse response = httpClient.execute(getMethod);
-            if (HttpStatus.SC_OK != response.getStatusLine().getStatusCode()) {
-                LOG.warn("HTTP call for weather returned error status code {} - {} as a result with query: {}", status,
-                        response.getStatusLine().getStatusCode(), query);
-                return 0;
-            }
-            String weather = EntityUtils.toString(response.getEntity(), "UTF-8");
-            LOG.debug("Got back the Weather information {}", weather);
-            if (ObjectHelper.isEmpty(weather)) {
-                // empty response
-                return 0;
-            }
+            return httpClient.execute(
+                    getMethod,
+                    response -> {
+                        try {
+                            if (HttpStatus.SC_OK != response.getCode()) {
+                                LOG.warn("HTTP call for weather returned error status code {} - {} as a result with query: {}",
+                                        status,
+                                        response.getCode(), query);
+                                return 0;
+                            }
+                            String weather = EntityUtils.toString(response.getEntity(), "UTF-8");
+                            LOG.debug("Got back the Weather information {}", weather);
+                            if (ObjectHelper.isEmpty(weather)) {
+                                // empty response
+                                return 0;
+                            }
 
-            Exchange exchange = getEndpoint().createExchange();
-            String header = getEndpoint().getConfiguration().getHeaderName();
-            if (header != null) {
-                exchange.getIn().setHeader(header, weather);
-            } else {
-                exchange.getIn().setBody(weather);
-            }
-            exchange.getIn().setHeader(WeatherConstants.WEATHER_QUERY, query);
+                            Exchange exchange = getEndpoint().createExchange();
+                            String header = getEndpoint().getConfiguration().getHeaderName();
+                            if (header != null) {
+                                exchange.getIn().setHeader(header, weather);
+                            } else {
+                                exchange.getIn().setBody(weather);
+                            }
+                            exchange.getIn().setHeader(WeatherConstants.WEATHER_QUERY, query);
 
-            getProcessor().process(exchange);
+                            try {
+                                getProcessor().process(exchange);
+                            } catch (Exception e) {
+                                throw new RuntimeCamelException(e);
+                            }
 
-            return 1;
-        } finally {
-            getMethod.releaseConnection();
+                            return 1;
+                        } finally {
+                            getMethod.reset();
+                        }
+                    });
+        } catch (RuntimeCamelException e) {
+            if (e.getCause() instanceof Exception ex) {
+                throw ex;
+            }
+            throw e;
         }
     }
 
diff --git a/components/camel-weather/src/main/java/org/apache/camel/component/weather/WeatherEndpoint.java b/components/camel-weather/src/main/java/org/apache/camel/component/weather/WeatherEndpoint.java
index bf8ed254633..a5cb97c08b4 100644
--- a/components/camel-weather/src/main/java/org/apache/camel/component/weather/WeatherEndpoint.java
+++ b/components/camel-weather/src/main/java/org/apache/camel/component/weather/WeatherEndpoint.java
@@ -23,7 +23,7 @@ import org.apache.camel.Producer;
 import org.apache.camel.spi.UriEndpoint;
 import org.apache.camel.spi.UriParam;
 import org.apache.camel.support.DefaultPollingEndpoint;
-import org.apache.http.client.utils.HttpClientUtils;
+import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
 
 /**
  * Poll the weather information from Open Weather Map.
@@ -33,9 +33,9 @@ import org.apache.http.client.utils.HttpClientUtils;
 public class WeatherEndpoint extends DefaultPollingEndpoint {
 
     @UriParam
-    private WeatherConfiguration configuration;
+    private final WeatherConfiguration configuration;
 
-    private WeatherQuery weatherQuery;
+    private final WeatherQuery weatherQuery;
 
     public WeatherEndpoint(String uri, WeatherComponent component, WeatherConfiguration properties) {
         super(uri, component);
@@ -71,7 +71,10 @@ public class WeatherEndpoint extends DefaultPollingEndpoint {
     protected void doStop() throws Exception {
         super.doStop();
 
-        HttpClientUtils.closeQuietly(getConfiguration().getHttpClient());
+        CloseableHttpClient client = getConfiguration().getHttpClient();
+        if (client != null) {
+            client.close();
+        }
     }
 
 }
diff --git a/components/camel-weather/src/main/java/org/apache/camel/component/weather/WeatherProducer.java b/components/camel-weather/src/main/java/org/apache/camel/component/weather/WeatherProducer.java
index 4e623ee46b5..fb18d562aee 100644
--- a/components/camel-weather/src/main/java/org/apache/camel/component/weather/WeatherProducer.java
+++ b/components/camel-weather/src/main/java/org/apache/camel/component/weather/WeatherProducer.java
@@ -19,11 +19,10 @@ package org.apache.camel.component.weather;
 import org.apache.camel.Exchange;
 import org.apache.camel.support.DefaultProducer;
 import org.apache.camel.util.ObjectHelper;
-import org.apache.http.HttpResponse;
-import org.apache.http.HttpStatus;
-import org.apache.http.client.HttpClient;
-import org.apache.http.client.methods.HttpGet;
-import org.apache.http.util.EntityUtils;
+import org.apache.hc.client5.http.classic.HttpClient;
+import org.apache.hc.client5.http.classic.methods.HttpGet;
+import org.apache.hc.core5.http.HttpStatus;
+import org.apache.hc.core5.http.io.entity.EntityUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -52,32 +51,38 @@ public class WeatherProducer extends DefaultProducer {
         }
 
         HttpClient httpClient = getEndpoint().getConfiguration().getHttpClient();
-        HttpGet method = new HttpGet(q);
-        try {
-            LOG.debug("Going to execute the Weather query {}", q);
-            HttpResponse response = httpClient.execute(method);
-            if (HttpStatus.SC_OK != response.getStatusLine().getStatusCode()) {
-                throw new IllegalStateException(
-                        "Got the invalid http status value '" + response.getStatusLine().getStatusCode()
-                                                + "' as the result of the query '" + query + "'");
-            }
-            String weather = EntityUtils.toString(response.getEntity(), "UTF-8");
-            LOG.debug("Got back the Weather information {}", weather);
+        String uri = q;
+        HttpGet method = new HttpGet(uri);
+        httpClient.execute(
+                method,
+                response -> {
+                    try {
+                        LOG.debug("Going to execute the Weather query {}", uri);
+                        if (HttpStatus.SC_OK != response.getCode()) {
+                            throw new IllegalStateException(
+                                    "Got the invalid http status value '" + response.getCode()
+                                                            + "' as the result of the query '" + query + "'");
+                        }
+                        String weather = EntityUtils.toString(response.getEntity(), "UTF-8");
+                        LOG.debug("Got back the Weather information {}", weather);
 
-            if (ObjectHelper.isEmpty(weather)) {
-                throw new IllegalStateException(
-                        "Got the unexpected value '" + weather + "' as the result of the query '" + q + "'");
-            }
+                        if (ObjectHelper.isEmpty(weather)) {
+                            throw new IllegalStateException(
+                                    "Got the unexpected value '" + weather + "' as the result of the query '" + uri + "'");
+                        }
+
+                        String header = getEndpoint().getConfiguration().getHeaderName();
+                        if (header != null) {
+                            exchange.getIn().setHeader(header, weather);
+                        } else {
+                            exchange.getIn().setBody(weather);
+                        }
+                        exchange.getIn().setHeader(WeatherConstants.WEATHER_QUERY, uri);
+                        return null;
+                    } finally {
+                        method.reset();
+                    }
+                });
 
-            String header = getEndpoint().getConfiguration().getHeaderName();
-            if (header != null) {
-                exchange.getIn().setHeader(header, weather);
-            } else {
-                exchange.getIn().setBody(weather);
-            }
-            exchange.getIn().setHeader(WeatherConstants.WEATHER_QUERY, q);
-        } finally {
-            method.releaseConnection();
-        }
     }
 }
diff --git a/components/camel-weather/src/main/java/org/apache/camel/component/weather/geolocation/FreeGeoIpGeoLocationProvider.java b/components/camel-weather/src/main/java/org/apache/camel/component/weather/geolocation/FreeGeoIpGeoLocationProvider.java
index 3b2cde4a8de..1776075b9aa 100644
--- a/components/camel-weather/src/main/java/org/apache/camel/component/weather/geolocation/FreeGeoIpGeoLocationProvider.java
+++ b/components/camel-weather/src/main/java/org/apache/camel/component/weather/geolocation/FreeGeoIpGeoLocationProvider.java
@@ -19,11 +19,10 @@ package org.apache.camel.component.weather.geolocation;
 import com.fasterxml.jackson.databind.JsonNode;
 import com.fasterxml.jackson.databind.ObjectMapper;
 import org.apache.camel.component.weather.WeatherConfiguration;
-import org.apache.http.HttpResponse;
-import org.apache.http.HttpStatus;
-import org.apache.http.client.HttpClient;
-import org.apache.http.client.methods.HttpGet;
-import org.apache.http.util.EntityUtils;
+import org.apache.hc.client5.http.classic.HttpClient;
+import org.apache.hc.client5.http.classic.methods.HttpGet;
+import org.apache.hc.core5.http.HttpStatus;
+import org.apache.hc.core5.http.io.entity.EntityUtils;
 
 import static org.apache.camel.util.ObjectHelper.isEmpty;
 import static org.apache.camel.util.ObjectHelper.notNull;
@@ -49,28 +48,31 @@ public class FreeGeoIpGeoLocationProvider implements GeoLocationProvider {
         String url = String.format("http://api.ipstack.com/%s?access_key=%s&legacy=1&output=json",
                 configuration.getGeolocationRequestHostIP(), configuration.getGeolocationAccessKey());
         HttpGet getMethod = new HttpGet(url);
-        try {
-            HttpResponse response = httpClient.execute(getMethod);
-            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
-                throw new IllegalStateException(
-                        "Got the unexpected http-status '" + response.getStatusLine().getStatusCode()
-                                                + "' for the geolocation");
-            }
-            String geoLocation = EntityUtils.toString(response.getEntity(), "UTF-8");
-            if (isEmpty(geoLocation)) {
-                throw new IllegalStateException("Got the unexpected value '" + geoLocation + "' for the geolocation");
-            }
+        return httpClient.execute(
+                getMethod,
+                response -> {
+                    try {
+                        if (response.getCode() != HttpStatus.SC_OK) {
+                            throw new IllegalStateException(
+                                    "Got the unexpected http-status '" + response.getCode()
+                                                            + "' for the geolocation");
+                        }
+                        String geoLocation = EntityUtils.toString(response.getEntity(), "UTF-8");
+                        if (isEmpty(geoLocation)) {
+                            throw new IllegalStateException(
+                                    "Got the unexpected value '" + geoLocation + "' for the geolocation");
+                        }
 
-            ObjectMapper mapper = new ObjectMapper();
-            JsonNode node = mapper.readValue(geoLocation, JsonNode.class);
-            JsonNode latitudeNode = notNull(node.get("latitude"), "latitude");
-            JsonNode longitudeNode = notNull(node.get("longitude"), "longitude");
-
-            return new GeoLocation(longitudeNode.asText(), latitudeNode.asText());
-        } finally {
-            getMethod.releaseConnection();
-        }
+                        ObjectMapper mapper = new ObjectMapper();
+                        JsonNode node = mapper.readValue(geoLocation, JsonNode.class);
+                        JsonNode latitudeNode = notNull(node.get("latitude"), "latitude");
+                        JsonNode longitudeNode = notNull(node.get("longitude"), "longitude");
 
+                        return new GeoLocation(longitudeNode.asText(), latitudeNode.asText());
+                    } finally {
+                        getMethod.reset();
+                    }
+                });
     }
 
 }