Skip to content

Commit fbc94a1

Browse files
committed
Changed from Closable Connection to Pooling to avoid using closed connections. Update Apache Http Client version. Added example to update addresses Alias using Threads
1 parent ffff19f commit fbc94a1

File tree

3 files changed

+131
-5
lines changed

3 files changed

+131
-5
lines changed

pom.xml

+2-2
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
<modelVersion>4.0.0</modelVersion>
55
<groupId>io.github.route4me</groupId>
66
<artifactId>route4me-java-sdk</artifactId>
7-
<version>1.14.1</version>
7+
<version>1.14.2</version>
88
<packaging>jar</packaging>
99
<properties>
1010
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
@@ -74,7 +74,7 @@
7474
<dependency>
7575
<groupId>org.apache.httpcomponents</groupId>
7676
<artifactId>httpclient</artifactId>
77-
<version>4.5.13</version>
77+
<version>4.5.14</version>
7878
</dependency>
7979
<dependency>
8080
<groupId>junit</groupId>

src/main/java/com/route4me/sdk/Manager.java

+13-3
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
import org.apache.http.entity.StringEntity;
2525
import org.apache.http.impl.client.CloseableHttpClient;
2626
import org.apache.http.impl.client.HttpClients;
27+
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
2728
import org.apache.logging.log4j.LogManager;
2829

2930
public abstract class Manager {
@@ -34,7 +35,6 @@ public abstract class Manager {
3435
private RequestConfig requestProxyConfig;
3536
private boolean disableRedirects;
3637
private String callBackURL;
37-
3838

3939
public Manager(String apiKey) {
4040
this.apiKey = apiKey;
@@ -182,9 +182,12 @@ private <T> T makeRequest(RequestMethod method, URIBuilder builder, HttpEntity b
182182
}
183183

184184
private <T> T makeRequest(RequestMethod method, URIBuilder builder, HttpEntity body, Class<T> clazz, Type type, String requestContentType) throws APIException {
185+
PoolingHttpClientConnectionManager poolingConnManager = new PoolingHttpClientConnectionManager();
186+
poolingConnManager.setMaxTotal(10);
187+
poolingConnManager.setDefaultMaxPerRoute(10);
188+
CloseableHttpClient client = HttpClients.custom().setConnectionManager(poolingConnManager).build();
185189
try {
186190
// Redirects Management
187-
CloseableHttpClient client = HttpClients.createDefault();
188191
if (this.disableRedirects) {
189192
builder.addParameter("redirect", "0");
190193
client = HttpClients.custom().disableRedirectHandling().build();
@@ -259,6 +262,13 @@ private <T> T makeRequest(RequestMethod method, URIBuilder builder, HttpEntity b
259262
}
260263
} catch (URISyntaxException ex) {
261264
throw new IllegalArgumentException(ex);
265+
} finally {
266+
try {
267+
client.close();
268+
} catch (IOException ex) {
269+
logger.error(ex);
270+
return null;
271+
}
262272
}
263273
}
264274

@@ -284,5 +294,5 @@ public String getCallBackURL() {
284294
public void setCallBackURL(String callBackURL) {
285295
this.callBackURL = callBackURL;
286296
}
287-
297+
288298
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
/*
2+
* The MIT License
3+
*
4+
* Copyright 2023 Route4Me.
5+
*
6+
* Permission is hereby granted, free of charge, to any person obtaining a copy
7+
* of this software and associated documentation files (the "Software"), to deal
8+
* in the Software without restriction, including without limitation the rights
9+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10+
* copies of the Software, and to permit persons to whom the Software is
11+
* furnished to do so, subject to the following conditions:
12+
*
13+
* The above copyright notice and this permission notice shall be included in
14+
* all copies or substantial portions of the Software.
15+
*
16+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22+
* THE SOFTWARE.
23+
*/
24+
package com.route4me.sdk.examples.addresses;
25+
26+
import com.route4me.sdk.exception.APIException;
27+
import com.route4me.sdk.services.routing.Address;
28+
import com.route4me.sdk.services.routing.Route;
29+
import com.route4me.sdk.services.routing.RoutesRequest;
30+
import com.route4me.sdk.services.routing.RoutingManager;
31+
import java.util.ArrayList;
32+
import java.util.List;
33+
import java.util.UUID;
34+
import java.util.concurrent.Callable;
35+
import java.util.concurrent.ExecutionException;
36+
import java.util.concurrent.ExecutorService;
37+
import java.util.concurrent.Executors;
38+
import java.util.concurrent.Future;
39+
import java.util.concurrent.TimeUnit;
40+
import java.util.concurrent.TimeoutException;
41+
import java.util.logging.Level;
42+
import java.util.logging.Logger;
43+
import org.apache.logging.log4j.LogManager;
44+
45+
/**
46+
*
47+
* @author route4me
48+
*/
49+
public class TheadBasedAddressesAliasUpdater implements Callable {
50+
51+
private final Address address;
52+
private final String routeID;
53+
private final RoutingManager manager;
54+
protected static final org.apache.logging.log4j.Logger logger = LogManager.getLogger(TheadBasedAddressesAliasUpdater.class);
55+
56+
public TheadBasedAddressesAliasUpdater(RoutingManager manager, String routeID, Address address) {
57+
58+
this.manager = manager;
59+
this.routeID = routeID;
60+
this.address = address;
61+
}
62+
63+
private Address updateAddressFirstName() {
64+
UUID uuid = UUID.randomUUID();
65+
address.setAlias(uuid.toString().toUpperCase());
66+
Address updatedAddress = null;
67+
try {
68+
updatedAddress = manager.updateAddressAttribute(routeID, address.getRouteDestinationId(), address);
69+
} catch (APIException ex) {
70+
logger.error(ex);
71+
}
72+
return updatedAddress;
73+
}
74+
75+
@Override
76+
public Object call() throws Exception {
77+
78+
Address updatedAddress = updateAddressFirstName();
79+
return updatedAddress;
80+
}
81+
82+
public static void main(String[] args) {
83+
84+
String apiKey = System.getenv("R4M_API_KEY");
85+
RoutingManager manager = new RoutingManager(apiKey);
86+
87+
ExecutorService executor = Executors.newFixedThreadPool(10);
88+
String routeID = "5ED2D6B7E7FCB926D6B164A530DA4224";
89+
List<Future<Address>> workers = new ArrayList<>();
90+
try {
91+
Route route = manager.getRoute(new RoutesRequest().setId(routeID));
92+
for (Address address : route.getAddresses()) {
93+
System.out.println("Current Alias: " + address.getAlias() + " Route Destination ID: " + address.getRouteDestinationId());
94+
95+
Callable callableWorker = new TheadBasedAddressesAliasUpdater(manager, routeID, address);
96+
Future<Address> future = executor.submit(callableWorker);
97+
workers.add(future);
98+
}
99+
executor.shutdown();
100+
System.out.println("\nUpdating Address in Parallel...\n");
101+
while (!executor.isTerminated()) {
102+
}
103+
for (Future<Address> worker : workers) {
104+
try {
105+
Address updatedAddress = worker.get(60, TimeUnit.MILLISECONDS);
106+
System.out.println("Updated Alias: " + updatedAddress.getAlias() + " Route Destination ID: " + updatedAddress.getRouteDestinationId());
107+
} catch (InterruptedException | ExecutionException | TimeoutException ex) {
108+
logger.error("Thread Execution Exception. " + ex);
109+
}
110+
}
111+
} catch (APIException ex) {
112+
Logger.getLogger(TheadBasedAddressesAliasUpdater.class.getName()).log(Level.SEVERE, null, ex);
113+
}
114+
115+
}
116+
}

0 commit comments

Comments
 (0)