fixed async timing and 404 bug, refactored code

This commit is contained in:
Tom Hombergs 2018-08-15 23:10:18 +02:00
parent 2b229332b9
commit 623e29cecb
6 changed files with 256 additions and 349 deletions

View File

@ -47,6 +47,17 @@
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>2.4.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-jdk14</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.10.0</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

View File

@ -1,217 +0,0 @@
package com.baeldung.samples.jerseyrx;
import io.reactivex.Flowable;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import org.glassfish.jersey.client.rx.rxjava.RxObservableInvokerProvider;
import org.glassfish.jersey.client.rx.rxjava.RxObservableInvoker;
import java.util.logging.Logger;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.InvocationCallback;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;
import org.glassfish.jersey.client.rx.rxjava2.RxFlowableInvoker;
import org.glassfish.jersey.client.rx.rxjava2.RxFlowableInvokerProvider;
import rx.Observable;
/**
*
* @author baeldung
*/
public class ClientOrchestration {
Client client = ClientBuilder.newClient();
WebTarget userIdService = client.target("http://localhost:8080/serviceA/id");
WebTarget nameService = client.target("http://localhost:8080/serviceA/{empId}/name");
WebTarget hashService = client.target("http://localhost:8080/serviceA/{comboIDandName}/hash");
LinkedList<Throwable> failures = new LinkedList<>();
Logger logger = Logger.getLogger("ClientOrchestrator");
public void callBackOrchestrate() {
logger.info("Orchestrating with the pyramid of doom");
userIdService.request()
.accept(MediaType.APPLICATION_JSON)
.async()
.get(new InvocationCallback<EmployeeDTO>() {
@Override
public void completed(EmployeeDTO empIdList) {
logger.info("[InvocationCallback] Got all the IDs " + empIdList.getEmpIds());
List<Long> empIds = empIdList.getEmpIds();
CountDownLatch completionTracker = new CountDownLatch(empIds.size()); //used to keep track of the progress of the subsequent calls
empIds.forEach((id) -> {
//for each employee ID, get the name
nameService.resolveTemplate("empId", id).request()
.async()
.get(new InvocationCallback<String>() {
@Override
public void completed(String response) {
completionTracker.countDown();
hashService.resolveTemplate("comboIDandName", response + id).request().async().get(new InvocationCallback<String>() {
@Override
public void completed(String response) {
logger.log(Level.INFO, "[InvocationCallback] The hash output {0}", response);
}
@Override
public void failed(Throwable throwable) {
completionTracker.countDown();
failures.add(throwable);
logger.log(Level.WARNING, "[InvocationCallback] An error has occurred in the hashing request step {0}", throwable.getMessage());
}
});
}
@Override
public void failed(Throwable throwable) {
completionTracker.countDown();
failures.add(throwable);
logger.log(Level.WARNING, "[InvocationCallback] An error has occurred in the username request step {0}", throwable.getMessage());
}
});
});
try {
if (!completionTracker.await(10, TimeUnit.SECONDS)) { //wait for inner requests to complete in 10 seconds
logger.warning("[InvocationCallback] Some requests didn't complete within the timeout");
}
} catch (InterruptedException ex) {
failures.add(ex);
Logger.getLogger(ClientOrchestration.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
public void failed(Throwable throwable) {
failures.add(throwable);
logger.warning("Couldn't get the list of IDs");
}
});
}
public void rxOrchestrate() {
logger.info("Orchestrating with a CompletionStage");
CompletionStage<EmployeeDTO> userIdStage = userIdService.request().accept(MediaType.APPLICATION_JSON)
.rx()
.get(new GenericType<EmployeeDTO>() {
})
.exceptionally((throwable) -> {
failures.add(throwable);
logger.warning("[CompletionStage] An error has occurred");
return null;
});
userIdStage.thenAcceptAsync(empIdDto -> {
logger.info("[CompletionStage] Got all the IDs " + empIdDto.getEmpIds());
empIdDto.getEmpIds().stream().forEach((Long id) -> {
CompletableFuture<String> completable = nameService.resolveTemplate("empId", id)
.request()
.rx()
.get(String.class)
.toCompletableFuture();
completable.thenAccept((String userName) -> {
hashService.resolveTemplate("comboIDandName", userName + id)
.request()
.rx()
.get(String.class)
.toCompletableFuture()
.thenAcceptAsync(hashValue -> logger.log(Level.INFO, "[CompletionFuture] The hash output {0}", hashValue))
.exceptionally((throwable) -> {
failures.add(throwable);
logger.log(Level.WARNING, "[CompletionStage] Hash computation failed for {0}", id);
return null;
});
});
});
});
}
public void observableJavaOrchestrate() {
logger.info("Orchestrating with Observables");
Observable<EmployeeDTO> observableUserIdService = userIdService.register(RxObservableInvokerProvider.class).request()
.accept(MediaType.APPLICATION_JSON)
.rx(RxObservableInvoker.class)
.get(new GenericType<EmployeeDTO>() {
}).asObservable();
observableUserIdService.subscribe((EmployeeDTO empIdList) -> {
logger.info("[Observable] Got all the IDs " + empIdList.getEmpIds());
Observable.from(empIdList.getEmpIds()).subscribe(id
-> nameService.register(RxObservableInvokerProvider.class)
.resolveTemplate("empId", id)
.request()
.rx(RxObservableInvoker.class)
.get(String.class)
.asObservable() //gotten the name for the given empId
.doOnError((throwable) -> {
failures.add(throwable);
logger.log(Level.WARNING, " [Observable] An error has occurred in the username request step {0}", throwable.getMessage());
})
.subscribe(userName -> hashService.register(RxObservableInvokerProvider.class)
.resolveTemplate("comboIDandName", userName + id)
.request()
.rx(RxObservableInvoker.class)
.get(String.class)
.asObservable() //gotten the hash value for empId+username
.doOnError((throwable) -> {
failures.add(throwable);
logger.log(Level.WARNING, " [Observable]An error has occurred in the hashing request step {0}", throwable.getMessage());
})
.subscribe(hashValue -> logger.log(Level.INFO, "[Observable] The hash output {0}", hashValue))));
});
}
public void flowableJavaOrchestrate() {
Flowable<EmployeeDTO> userIdFlowable = userIdService.register(RxFlowableInvokerProvider.class)
.request()
.rx(RxFlowableInvoker.class)
.get(new GenericType<EmployeeDTO>() {
});
userIdFlowable.subscribe((EmployeeDTO dto) -> {
logger.info("Orchestrating with Flowable");
List<Long> listOfIds = dto.getEmpIds();
Flowable.just(listOfIds).subscribe(id
-> nameService.register(RxFlowableInvokerProvider.class)
.resolveTemplate("empId", id)
.request()
.rx(RxFlowableInvoker.class)
.get(String.class) //gotten the name for the given empId
.doOnError((throwable) -> {
failures.add(throwable);
logger.log(Level.WARNING, "[Flowable] An error has occurred in the username request step {0}", throwable.getMessage());
})
.subscribe(userName -> hashService.register(RxFlowableInvokerProvider.class)
.resolveTemplate("comboIDandName", userName + id)
.request()
.rx(RxFlowableInvoker.class)
.get(String.class) //gotten the hash value for empId+username
.doOnError((throwable) -> {
failures.add(throwable);
logger.warning(" [Flowable] An error has occurred in the hashing request step " + throwable.getMessage());
})
.subscribe(hashValue -> logger.log(Level.INFO, "[Flowable] The hash output {0}", hashValue))));
});
}
}

View File

@ -1,54 +0,0 @@
package com.baeldung.samples.jerseyrx;
import java.util.List;
import java.util.Objects;
/**
*
* @author baeldung
*/
public class EmployeeDTO {
private List<Long> empIds;
public List<Long> getEmpIds() {
return empIds;
}
public void setEmpIds(List<Long> empIds) {
this.empIds = empIds;
}
@Override
public int hashCode() {
int hash = 5;
hash = 59 * hash + Objects.hashCode(this.empIds);
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final EmployeeDTO other = (EmployeeDTO) obj;
if (!Objects.equals(this.empIds, other.empIds)) {
return false;
}
return true;
}
@Override
public String toString() {
return "EmployeeDTO{" + "empIds=" + empIds + '}';
}
}

View File

@ -0,0 +1,244 @@
package com.baeldung.samples.jerseyrx;
import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static org.assertj.core.api.Assertions.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.InvocationCallback;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;
import org.glassfish.jersey.client.rx.rxjava.RxObservableInvoker;
import org.glassfish.jersey.client.rx.rxjava.RxObservableInvokerProvider;
import org.glassfish.jersey.client.rx.rxjava2.RxFlowableInvoker;
import org.glassfish.jersey.client.rx.rxjava2.RxFlowableInvokerProvider;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import io.reactivex.Flowable;
import rx.Observable;
/**
*
* @author baeldung
*/
public class ClientOrchestrationIntegrationTest {
private Client client = ClientBuilder.newClient();
private WebTarget userIdService = client.target("http://localhost:8080/id-service/ids");
private WebTarget nameService = client.target("http://localhost:8080/name-service/users/{userId}/name");
private WebTarget hashService = client.target("http://localhost:8080/hash-service/{rawValue}");
private Logger logger = LoggerFactory.getLogger(ClientOrchestrationIntegrationTest.class);
private String expectedUserIds = "[1,2,3,4,5,6]";
private List<String> expectedNames = Arrays.asList("n/a", "Thor", "Hulk", "BlackWidow", "BlackPanther", "TheTick", "Hawkeye");
private List<String> expectedHashValues = Arrays.asList("roht1", "kluh2", "WodiwKcalb3", "RehtnapKclab4", "kciteht5", "eyekwah6");
@Rule
public WireMockRule wireMockServer = new WireMockRule();
@Before
public void setup() {
stubFor(get(urlEqualTo("/id-service/ids")).willReturn(aResponse().withBody(expectedUserIds).withHeader("Content-Type", "application/json")));
stubFor(get(urlEqualTo("/name-service/users/1/name")).willReturn(aResponse().withBody(expectedNames.get(1))));
stubFor(get(urlEqualTo("/name-service/users/2/name")).willReturn(aResponse().withBody(expectedNames.get(2))));
stubFor(get(urlEqualTo("/name-service/users/3/name")).willReturn(aResponse().withBody(expectedNames.get(3))));
stubFor(get(urlEqualTo("/name-service/users/4/name")).willReturn(aResponse().withBody(expectedNames.get(4))));
stubFor(get(urlEqualTo("/name-service/users/5/name")).willReturn(aResponse().withBody(expectedNames.get(5))));
stubFor(get(urlEqualTo("/name-service/users/6/name")).willReturn(aResponse().withBody(expectedNames.get(6))));
stubFor(get(urlEqualTo("/hash-service/Thor1")).willReturn(aResponse().withBody(expectedHashValues.get(0))));
stubFor(get(urlEqualTo("/hash-service/Hulk2")).willReturn(aResponse().withBody(expectedHashValues.get(1))));
stubFor(get(urlEqualTo("/hash-service/BlackWidow3")).willReturn(aResponse().withBody(expectedHashValues.get(2))));
stubFor(get(urlEqualTo("/hash-service/BlackPanther4")).willReturn(aResponse().withBody(expectedHashValues.get(3))));
stubFor(get(urlEqualTo("/hash-service/TheTick5")).willReturn(aResponse().withBody(expectedHashValues.get(4))));
stubFor(get(urlEqualTo("/hash-service/Hawkeye6")).willReturn(aResponse().withBody(expectedHashValues.get(5))));
}
@Test
public void callBackOrchestrate() throws InterruptedException {
List<String> receivedHashValues = new ArrayList<>();
userIdService.request().accept(MediaType.APPLICATION_JSON).async().get(new InvocationCallback<List<Long>>() {
@Override
public void completed(List<Long> employeeIds) {
logger.info("[CallbackExample] id-service result: {}", employeeIds);
CountDownLatch completionTracker = new CountDownLatch(employeeIds.size()); // used to keep track of the progress of the subsequent calls
employeeIds.forEach((id) -> {
// for each employee ID, get the name
nameService.resolveTemplate("userId", id).request().async().get(new InvocationCallback<String>() {
@Override
public void completed(String response) {
logger.info("[CallbackExample] name-service result: {}", response);
completionTracker.countDown();
hashService.resolveTemplate("rawValue", response + id).request().async().get(new InvocationCallback<String>() {
@Override
public void completed(String response) {
logger.info("[CallbackExample] hash-service result: {}", response);
receivedHashValues.add(response);
}
@Override
public void failed(Throwable throwable) {
completionTracker.countDown();
logger.warn("[CallbackExample] An error has occurred in the hashing request step!", throwable);
}
});
}
@Override
public void failed(Throwable throwable) {
completionTracker.countDown();
logger.warn("[CallbackExample] An error has occurred in the username request step!", throwable);
}
});
});
try {
// wait for inner requests to complete in 10 seconds
if (!completionTracker.await(10, TimeUnit.SECONDS)) {
logger.warn("[CallbackExample] Some requests didn't complete within the timeout");
}
} catch (InterruptedException e) {
logger.error("Interrupted!", e);
}
}
@Override
public void failed(Throwable throwable) {
logger.warn("[CallbackExample] An error has occurred in the userId request step!", throwable);
}
});
// wait for async calls to complete
Thread.sleep(1000);
assertThat(receivedHashValues).containsAll(expectedHashValues);
}
@Test
public void rxOrchestrate() throws InterruptedException {
List<String> receivedHashValues = new ArrayList<>();
CompletionStage<List<Long>> userIdStage = userIdService.request().accept(MediaType.APPLICATION_JSON).rx().get(new GenericType<List<Long>>() {
}).exceptionally((throwable) -> {
logger.warn("[CompletionStageExample] An error has occurred");
return null;
});
userIdStage.thenAcceptAsync(employeeIds -> {
logger.info("[CompletionStageExample] id-service result: {}", employeeIds);
employeeIds.forEach((Long id) -> {
CompletableFuture<String> completable = nameService.resolveTemplate("userId", id).request().rx().get(String.class).toCompletableFuture();
completable.thenAccept((String userName) -> {
logger.info("[CompletionStageExample] name-service result: {}", userName);
hashService.resolveTemplate("rawValue", userName + id).request().rx().get(String.class).toCompletableFuture().thenAcceptAsync(hashValue -> {
logger.info("[CompletionStageExample] hash-service result: {}", hashValue);
receivedHashValues.add(hashValue);
}).exceptionally((throwable) -> {
logger.warn("[CompletionStageExample] Hash computation failed for {}", id);
return null;
});
});
});
});
// wait for async calls to complete
Thread.sleep(1000);
assertThat(receivedHashValues).containsAll(expectedHashValues);
}
@Test
public void observableJavaOrchestrate() throws InterruptedException {
List<String> receivedHashValues = new ArrayList<>();
Observable<List<Long>> observableUserIdService = userIdService.register(RxObservableInvokerProvider.class).request().accept(MediaType.APPLICATION_JSON).rx(RxObservableInvoker.class).get(new GenericType<List<Long>>() {
}).asObservable();
observableUserIdService.subscribe((List<Long> employeeIds) -> {
logger.info("[ObservableExample] id-service result: {}", employeeIds);
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
// userId
.doOnError((throwable) -> {
logger.warn("[ObservableExample] An error has occurred in the username request step {}", throwable.getMessage());
}).subscribe(userName -> {
logger.info("[ObservableExample] name-service result: {}", userName);
hashService.register(RxObservableInvokerProvider.class).resolveTemplate("rawValue", userName + id).request().rx(RxObservableInvoker.class).get(String.class).asObservable() // gotten the hash value for
// userId+username
.doOnError((throwable) -> {
logger.warn("[ObservableExample] An error has occurred in the hashing request step {}", throwable.getMessage());
}).subscribe(hashValue -> {
logger.info("[ObservableExample] hash-service result: {}", hashValue);
receivedHashValues.add(hashValue);
});
}));
});
// wait for async calls to complete
Thread.sleep(1000);
assertThat(receivedHashValues).containsAll(expectedHashValues);
}
@Test
public void flowableJavaOrchestrate() throws InterruptedException {
List<String> receivedHashValues = new ArrayList<>();
Flowable<List<Long>> userIdFlowable = userIdService.register(RxFlowableInvokerProvider.class).request().rx(RxFlowableInvoker.class).get(new GenericType<List<Long>>() {
});
userIdFlowable.subscribe((List<Long> employeeIds) -> {
logger.info("[FlowableExample] id-service result: {}", employeeIds);
Flowable.fromIterable(employeeIds).subscribe(id -> {
nameService.register(RxFlowableInvokerProvider.class).resolveTemplate("userId", id).request().rx(RxFlowableInvoker.class).get(String.class) // gotten the name for the given userId
.doOnError((throwable) -> {
logger.warn("[FlowableExample] An error has occurred in the username request step {}", throwable.getMessage());
}).subscribe(userName -> {
logger.info("[FlowableExample] name-service result: {}", userName);
hashService.register(RxFlowableInvokerProvider.class).resolveTemplate("rawValue", userName + id).request().rx(RxFlowableInvoker.class).get(String.class) // gotten the hash value for userId+username
.doOnError((throwable) -> {
logger.warn(" [FlowableExample] An error has occurred in the hashing request step!", throwable);
}).subscribe(hashValue -> {
logger.info("[FlowableExample] hash-service result: {}", hashValue);
receivedHashValues.add(hashValue);
});
});
});
});
// wait for async calls to complete
Thread.sleep(1000);
assertThat(receivedHashValues).containsAll(expectedHashValues);
}
}

View File

@ -1,78 +0,0 @@
package com.baeldung.samples.jerseyrx;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import java.util.LinkedList;
import java.util.logging.Logger;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import static junit.framework.Assert.assertTrue;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
/**
*
* @author baeldung
*/
public class ClientOrchestrationTest {
Client client = ClientBuilder.newClient();
WebTarget userIdService = client.target("http://localhost:8080/serviceA/id");
WebTarget nameService = client.target("http://localhost:8080/serviceA/{empId}/name");
WebTarget hashService = client.target("http://localhost:8080/serviceA/{comboIDandName}/hash");
LinkedList<Throwable> failures = new LinkedList<>();
Logger logger = Logger.getLogger("ClientOrchestrator");
ClientOrchestration orchestrator = new ClientOrchestration();
String jsonIdList = "{\"empIds\":[1,2,3,4,5,6]}";
String[] nameList = new String[]{"n/a", "Thor", "Hulk", "BlackWidow", "BlackPanther", "TheTick", "Hawkeye"};
String[] hashResultList = new String[]{"roht1", "kluh2", "WodiwKcalb3", "RehtnapKclab4", "kciteht5", "eyekwah6"};
@Rule
public WireMockRule wireMockServer = new WireMockRule();
@Before
public void setup() {
stubFor(get(urlEqualTo("/serviceA/id")).willReturn(aResponse().withBody(jsonIdList).withHeader("Content-Type", "application/json")));
stubFor(get(urlEqualTo("/serviceA/1/name")).willReturn(aResponse().withBody(nameList[1])));
stubFor(get(urlEqualTo("/serviceA/2/name")).willReturn(aResponse().withBody(nameList[2])));
stubFor(get(urlEqualTo("/serviceA/3/name")).willReturn(aResponse().withBody(nameList[3])));
stubFor(get(urlEqualTo("/serviceA/4/name")).willReturn(aResponse().withBody(nameList[4])));
stubFor(get(urlEqualTo("/serviceA/5/name")).willReturn(aResponse().withBody(nameList[5])));
stubFor(get(urlEqualTo("/serviceA/6/name")).willReturn(aResponse().withBody(nameList[6])));
stubFor(get(urlEqualTo("/serviceA/Thor1/hash")).willReturn(aResponse().withBody(hashResultList[0])));
stubFor(get(urlEqualTo("/serviceA/Hulk2/hash")).willReturn(aResponse().withBody(hashResultList[1])));
stubFor(get(urlEqualTo("/serviceA/BlackWidow3/hash")).willReturn(aResponse().withBody(hashResultList[2])));
stubFor(get(urlEqualTo("/serviceA/BlackPanther4/hash")).willReturn(aResponse().withBody(hashResultList[3])));
stubFor(get(urlEqualTo("/serviceA/TheTick5/hash")).willReturn(aResponse().withBody(hashResultList[4])));
stubFor(get(urlEqualTo("/serviceA/Hawkeye6/hash")).willReturn(aResponse().withBody(hashResultList[5])));
}
@Test
public void hits() {
orchestrator.callBackOrchestrate();
orchestrator.rxOrchestrate();
orchestrator.observableJavaOrchestrate();
orchestrator.flowableJavaOrchestrate();
assertTrue(orchestrator.failures.isEmpty());
}
}

View File

@ -188,6 +188,7 @@
<module>spring-integration</module>
<module>spring-jenkins-pipeline</module>
<module>spring-jersey</module>
<module>jersey-client-rx</module>
<module>jmeter</module>
<module>spring-jms</module>
<module>spring-jooq</module>