|
| 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 | +} |
0 commit comments