Skip to content

Commit 17cf6fc

Browse files
committed
Merge branch 'master' of https://github.com/eugenp/tutorials
2 parents 9971969 + 2501cc9 commit 17cf6fc

File tree

9 files changed

+393
-0
lines changed

9 files changed

+393
-0
lines changed

jersey-client-rx/pom.xml

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
3+
<modelVersion>4.0.0</modelVersion>
4+
<groupId>com.baeldung.samples</groupId>
5+
<artifactId>jersey-client-rx</artifactId>
6+
<version>1.0</version>
7+
<packaging>jar</packaging>
8+
<dependencies>
9+
<dependency>
10+
<groupId>org.glassfish.jersey.inject</groupId>
11+
<artifactId>jersey-hk2</artifactId>
12+
<version>2.27</version>
13+
</dependency>
14+
<dependency>
15+
<groupId>org.glassfish.jersey.core</groupId>
16+
<artifactId>jersey-client</artifactId>
17+
<version>2.27</version>
18+
</dependency>
19+
<dependency>
20+
<groupId>org.glassfish.jersey.ext.rx</groupId>
21+
<artifactId>jersey-rx-client-rxjava</artifactId>
22+
<version>2.27</version>
23+
</dependency>
24+
<dependency>
25+
<groupId>org.glassfish.jersey.ext.rx</groupId>
26+
<artifactId>jersey-rx-client-rxjava2</artifactId>
27+
<version>2.27</version>
28+
</dependency>
29+
<dependency>
30+
<groupId>com.github.tomakehurst</groupId>
31+
<artifactId>wiremock</artifactId>
32+
<version>1.58</version>
33+
<scope>test</scope>
34+
</dependency>
35+
<dependency>
36+
<groupId>org.junit.vintage</groupId>
37+
<artifactId>junit-vintage-engine</artifactId>
38+
<version>5.2.0</version>
39+
</dependency>
40+
<dependency>
41+
<groupId>org.glassfish.jersey.media</groupId>
42+
<artifactId>jersey-media-json-jackson</artifactId>
43+
<version>2.25</version>
44+
</dependency>
45+
<dependency>
46+
<groupId>com.fasterxml.jackson.jaxrs</groupId>
47+
<artifactId>jackson-jaxrs-json-provider</artifactId>
48+
<version>2.4.1</version>
49+
</dependency>
50+
<dependency>
51+
<groupId>org.slf4j</groupId>
52+
<artifactId>slf4j-jdk14</artifactId>
53+
<version>1.7.25</version>
54+
</dependency>
55+
<dependency>
56+
<groupId>org.assertj</groupId>
57+
<artifactId>assertj-core</artifactId>
58+
<version>3.10.0</version>
59+
<scope>test</scope>
60+
</dependency>
61+
</dependencies>
62+
<properties>
63+
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
64+
<maven.compiler.source>1.8</maven.compiler.source>
65+
<maven.compiler.target>1.8</maven.compiler.target>
66+
</properties>
67+
</project>

jersey-client-rx/readme.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# Fluent, Reactive Jersey Client Orchestration #
2+
3+
### Sample code demonstrating the options for asynchronous, reactive RESTful service consumption with JAX-RS ###
Lines changed: 272 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,272 @@
1+
package com.baeldung.samples.jerseyrx;
2+
3+
import static com.github.tomakehurst.wiremock.client.WireMock.*;
4+
import static org.assertj.core.api.Assertions.*;
5+
6+
import java.util.ArrayList;
7+
import java.util.Arrays;
8+
import java.util.List;
9+
import java.util.concurrent.CompletableFuture;
10+
import java.util.concurrent.CompletionStage;
11+
import java.util.concurrent.CountDownLatch;
12+
import java.util.concurrent.TimeUnit;
13+
14+
import javax.ws.rs.client.Client;
15+
import javax.ws.rs.client.ClientBuilder;
16+
import javax.ws.rs.client.InvocationCallback;
17+
import javax.ws.rs.client.WebTarget;
18+
import javax.ws.rs.core.GenericType;
19+
import javax.ws.rs.core.MediaType;
20+
21+
import org.glassfish.jersey.client.rx.rxjava.RxObservableInvoker;
22+
import org.glassfish.jersey.client.rx.rxjava.RxObservableInvokerProvider;
23+
import org.glassfish.jersey.client.rx.rxjava2.RxFlowableInvoker;
24+
import org.glassfish.jersey.client.rx.rxjava2.RxFlowableInvokerProvider;
25+
import org.junit.Before;
26+
import org.junit.Rule;
27+
import org.junit.Test;
28+
import org.slf4j.Logger;
29+
import org.slf4j.LoggerFactory;
30+
31+
import com.github.tomakehurst.wiremock.junit.WireMockRule;
32+
33+
import io.reactivex.Flowable;
34+
import rx.Observable;
35+
36+
/**
37+
*
38+
* @author baeldung
39+
*/
40+
public class ClientOrchestrationIntegrationTest {
41+
42+
private Client client = ClientBuilder.newClient();
43+
44+
private WebTarget userIdService = client.target("http://localhost:8080/id-service/ids");
45+
private WebTarget nameService = client.target("http://localhost:8080/name-service/users/{userId}/name");
46+
private WebTarget hashService = client.target("http://localhost:8080/hash-service/{rawValue}");
47+
48+
private Logger logger = LoggerFactory.getLogger(ClientOrchestrationIntegrationTest.class);
49+
50+
private String expectedUserIds = "[1,2,3,4,5,6]";
51+
52+
private List<String> expectedNames = Arrays.asList("n/a", "Thor", "Hulk", "BlackWidow", "BlackPanther", "TheTick", "Hawkeye");
53+
54+
private List<String> expectedHashValues = Arrays.asList("roht1", "kluh2", "WodiwKcalb3", "RehtnapKclab4", "kciteht5", "eyekwah6");
55+
56+
@Rule
57+
public WireMockRule wireMockServer = new WireMockRule();
58+
59+
@Before
60+
public void setup() {
61+
62+
stubFor(get(urlEqualTo("/id-service/ids")).willReturn(aResponse().withBody(expectedUserIds).withHeader("Content-Type", "application/json")));
63+
64+
stubFor(get(urlEqualTo("/name-service/users/1/name")).willReturn(aResponse().withBody(expectedNames.get(1))));
65+
stubFor(get(urlEqualTo("/name-service/users/2/name")).willReturn(aResponse().withBody(expectedNames.get(2))));
66+
stubFor(get(urlEqualTo("/name-service/users/3/name")).willReturn(aResponse().withBody(expectedNames.get(3))));
67+
stubFor(get(urlEqualTo("/name-service/users/4/name")).willReturn(aResponse().withBody(expectedNames.get(4))));
68+
stubFor(get(urlEqualTo("/name-service/users/5/name")).willReturn(aResponse().withBody(expectedNames.get(5))));
69+
stubFor(get(urlEqualTo("/name-service/users/6/name")).willReturn(aResponse().withBody(expectedNames.get(6))));
70+
71+
stubFor(get(urlEqualTo("/hash-service/Thor1")).willReturn(aResponse().withBody(expectedHashValues.get(0))));
72+
stubFor(get(urlEqualTo("/hash-service/Hulk2")).willReturn(aResponse().withBody(expectedHashValues.get(1))));
73+
stubFor(get(urlEqualTo("/hash-service/BlackWidow3")).willReturn(aResponse().withBody(expectedHashValues.get(2))));
74+
stubFor(get(urlEqualTo("/hash-service/BlackPanther4")).willReturn(aResponse().withBody(expectedHashValues.get(3))));
75+
stubFor(get(urlEqualTo("/hash-service/TheTick5")).willReturn(aResponse().withBody(expectedHashValues.get(4))));
76+
stubFor(get(urlEqualTo("/hash-service/Hawkeye6")).willReturn(aResponse().withBody(expectedHashValues.get(5))));
77+
78+
}
79+
80+
@Test
81+
public void callBackOrchestrate() throws InterruptedException {
82+
List<String> receivedHashValues = new ArrayList<>();
83+
84+
final CountDownLatch completionTracker = new CountDownLatch(expectedHashValues.size()); // used to keep track of the progress of the subsequent calls
85+
86+
userIdService.request().accept(MediaType.APPLICATION_JSON).async().get(new InvocationCallback<List<Long>>() {
87+
@Override
88+
public void completed(List<Long> employeeIds) {
89+
logger.info("[CallbackExample] id-service result: {}", employeeIds);
90+
employeeIds.forEach((id) -> {
91+
// for each employee ID, get the name
92+
nameService.resolveTemplate("userId", id).request().async().get(new InvocationCallback<String>() {
93+
94+
@Override
95+
public void completed(String response) {
96+
logger.info("[CallbackExample] name-service result: {}", response);
97+
98+
hashService.resolveTemplate("rawValue", response + id).request().async().get(new InvocationCallback<String>() {
99+
@Override
100+
public void completed(String response) {
101+
logger.info("[CallbackExample] hash-service result: {}", response);
102+
receivedHashValues.add(response);
103+
completionTracker.countDown();
104+
}
105+
106+
@Override
107+
public void failed(Throwable throwable) {
108+
logger.warn("[CallbackExample] An error has occurred in the hashing request step!", throwable);
109+
}
110+
});
111+
}
112+
113+
@Override
114+
public void failed(Throwable throwable) {
115+
logger.warn("[CallbackExample] An error has occurred in the username request step!", throwable);
116+
}
117+
});
118+
});
119+
120+
}
121+
122+
@Override
123+
public void failed(Throwable throwable) {
124+
logger.warn("[CallbackExample] An error has occurred in the userId request step!", throwable);
125+
}
126+
});
127+
128+
// wait for async calls to complete
129+
try {
130+
// wait for inner requests to complete in 10 seconds
131+
if (!completionTracker.await(10, TimeUnit.SECONDS)) {
132+
logger.warn("[CallbackExample] Some requests didn't complete within the timeout");
133+
}
134+
} catch (InterruptedException e) {
135+
logger.error("Interrupted!", e);
136+
}
137+
138+
assertThat(receivedHashValues).containsAll(expectedHashValues);
139+
}
140+
141+
@Test
142+
public void rxOrchestrate() throws InterruptedException {
143+
List<String> receivedHashValues = new ArrayList<>();
144+
145+
final CountDownLatch completionTracker = new CountDownLatch(expectedHashValues.size()); // used to keep track of the progress of the subsequent calls
146+
147+
CompletionStage<List<Long>> userIdStage = userIdService.request().accept(MediaType.APPLICATION_JSON).rx().get(new GenericType<List<Long>>() {
148+
}).exceptionally((throwable) -> {
149+
logger.warn("[CompletionStageExample] An error has occurred");
150+
return null;
151+
});
152+
153+
userIdStage.thenAcceptAsync(employeeIds -> {
154+
logger.info("[CompletionStageExample] id-service result: {}", employeeIds);
155+
employeeIds.forEach((Long id) -> {
156+
CompletableFuture<String> completable = nameService.resolveTemplate("userId", id).request().rx().get(String.class).toCompletableFuture();
157+
158+
completable.thenAccept((String userName) -> {
159+
logger.info("[CompletionStageExample] name-service result: {}", userName);
160+
hashService.resolveTemplate("rawValue", userName + id).request().rx().get(String.class).toCompletableFuture().thenAcceptAsync(hashValue -> {
161+
logger.info("[CompletionStageExample] hash-service result: {}", hashValue);
162+
receivedHashValues.add(hashValue);
163+
completionTracker.countDown();
164+
}).exceptionally((throwable) -> {
165+
logger.warn("[CompletionStageExample] Hash computation failed for {}", id);
166+
completionTracker.countDown();
167+
return null;
168+
});
169+
170+
});
171+
172+
});
173+
});
174+
175+
// wait for async calls to complete
176+
try {
177+
// wait for inner requests to complete in 10 seconds
178+
if (!completionTracker.await(10, TimeUnit.SECONDS)) {
179+
logger.warn("[CallbackExample] Some requests didn't complete within the timeout");
180+
}
181+
} catch (InterruptedException e) {
182+
logger.error("Interrupted!", e);
183+
}
184+
185+
assertThat(receivedHashValues).containsAll(expectedHashValues);
186+
}
187+
188+
@Test
189+
public void observableJavaOrchestrate() throws InterruptedException {
190+
List<String> receivedHashValues = new ArrayList<>();
191+
192+
final CountDownLatch completionTracker = new CountDownLatch(expectedHashValues.size()); // used to keep track of the progress of the subsequent calls
193+
194+
Observable<List<Long>> observableUserIdService = userIdService.register(RxObservableInvokerProvider.class).request().accept(MediaType.APPLICATION_JSON).rx(RxObservableInvoker.class).get(new GenericType<List<Long>>() {
195+
}).asObservable();
196+
197+
observableUserIdService.subscribe((List<Long> employeeIds) -> {
198+
logger.info("[ObservableExample] id-service result: {}", employeeIds);
199+
Observable.from(employeeIds).subscribe(id -> nameService.register(RxObservableInvokerProvider.class).resolveTemplate("userId", id).request().rx(RxObservableInvoker.class).get(String.class).asObservable() // gotten the name for the given
200+
// userId
201+
.doOnError((throwable) -> {
202+
logger.warn("[ObservableExample] An error has occurred in the username request step {}", throwable.getMessage());
203+
}).subscribe(userName -> {
204+
logger.info("[ObservableExample] name-service result: {}", userName);
205+
hashService.register(RxObservableInvokerProvider.class).resolveTemplate("rawValue", userName + id).request().rx(RxObservableInvoker.class).get(String.class).asObservable() // gotten the hash value for
206+
// userId+username
207+
.doOnError((throwable) -> {
208+
logger.warn("[ObservableExample] An error has occurred in the hashing request step {}", throwable.getMessage());
209+
}).subscribe(hashValue -> {
210+
logger.info("[ObservableExample] hash-service result: {}", hashValue);
211+
receivedHashValues.add(hashValue);
212+
completionTracker.countDown();
213+
});
214+
}));
215+
});
216+
217+
// wait for async calls to complete
218+
try {
219+
// wait for inner requests to complete in 10 seconds
220+
if (!completionTracker.await(10, TimeUnit.SECONDS)) {
221+
logger.warn("[CallbackExample] Some requests didn't complete within the timeout");
222+
}
223+
} catch (InterruptedException e) {
224+
logger.error("Interrupted!", e);
225+
}
226+
227+
assertThat(receivedHashValues).containsAll(expectedHashValues);
228+
}
229+
230+
@Test
231+
public void flowableJavaOrchestrate() throws InterruptedException {
232+
List<String> receivedHashValues = new ArrayList<>();
233+
234+
final CountDownLatch completionTracker = new CountDownLatch(expectedHashValues.size()); // used to keep track of the progress of the subsequent calls
235+
236+
Flowable<List<Long>> userIdFlowable = userIdService.register(RxFlowableInvokerProvider.class).request().rx(RxFlowableInvoker.class).get(new GenericType<List<Long>>() {
237+
});
238+
239+
userIdFlowable.subscribe((List<Long> employeeIds) -> {
240+
logger.info("[FlowableExample] id-service result: {}", employeeIds);
241+
Flowable.fromIterable(employeeIds).subscribe(id -> {
242+
nameService.register(RxFlowableInvokerProvider.class).resolveTemplate("userId", id).request().rx(RxFlowableInvoker.class).get(String.class) // gotten the name for the given userId
243+
.doOnError((throwable) -> {
244+
logger.warn("[FlowableExample] An error has occurred in the username request step {}", throwable.getMessage());
245+
}).subscribe(userName -> {
246+
logger.info("[FlowableExample] name-service result: {}", userName);
247+
hashService.register(RxFlowableInvokerProvider.class).resolveTemplate("rawValue", userName + id).request().rx(RxFlowableInvoker.class).get(String.class) // gotten the hash value for userId+username
248+
.doOnError((throwable) -> {
249+
logger.warn(" [FlowableExample] An error has occurred in the hashing request step!", throwable);
250+
}).subscribe(hashValue -> {
251+
logger.info("[FlowableExample] hash-service result: {}", hashValue);
252+
receivedHashValues.add(hashValue);
253+
completionTracker.countDown();
254+
});
255+
});
256+
});
257+
});
258+
259+
// wait for async calls to complete
260+
try {
261+
// wait for inner requests to complete in 10 seconds
262+
if (!completionTracker.await(10, TimeUnit.SECONDS)) {
263+
logger.warn("[CallbackExample] Some requests didn't complete within the timeout");
264+
}
265+
} catch (InterruptedException e) {
266+
logger.error("Interrupted!", e);
267+
}
268+
269+
assertThat(receivedHashValues).containsAll(expectedHashValues);
270+
}
271+
272+
}

pom.xml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -584,6 +584,7 @@
584584
<module>spring-security-thymeleaf</module>
585585
<module>persistence-modules/java-jdbi</module>
586586
<module>jersey</module>
587+
<module>jersey-client-rx</module>
587588
<module>java-spi</module>
588589
<module>performance-tests</module>
589590
<module>twilio</module>
@@ -1123,6 +1124,7 @@
11231124
<module>spring-security-thymeleaf</module>
11241125
<module>persistence-modules/java-jdbi</module>
11251126
<module>jersey</module>
1127+
<module>jersey-client-rx</module>
11261128
<module>java-spi</module>
11271129
<module>performance-tests</module>
11281130
<module>twilio</module>
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
package com.baeldung.dependency.exception.app;
2+
3+
import org.springframework.boot.SpringApplication;
4+
import org.springframework.boot.autoconfigure.SpringBootApplication;
5+
import org.springframework.context.annotation.ComponentScan;
6+
7+
@SpringBootApplication
8+
@ComponentScan(basePackages = "com.baeldung.dependency.exception")
9+
public class CustomConfiguration {
10+
public static void main(String[] args) {
11+
SpringApplication.run(CustomConfiguration.class, args);
12+
}
13+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
package com.baeldung.dependency.exception.app;
2+
3+
import com.baeldung.dependency.exception.repository.InventoryRepository;
4+
import org.springframework.stereotype.Service;
5+
6+
@Service
7+
public class PurchaseDeptService {
8+
private InventoryRepository repository;
9+
10+
public PurchaseDeptService(InventoryRepository repository) {
11+
this.repository = repository;
12+
}
13+
}

0 commit comments

Comments
 (0)