Merge branch 'BAEL-3283-latest' into BAEL-3283

This commit is contained in:
sandip singh
2019-10-31 23:25:14 +05:30
parent db85c8f275
commit f6c3f9ebcb
20562 changed files with 1643286 additions and 0 deletions
+13
View File
@@ -0,0 +1,13 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear
+8
View File
@@ -0,0 +1,8 @@
## Spring Jersey
This module contains articles about Spring with Jersey
## REST API with Jersey & Spring Example Project
- [REST API with Jersey and Spring](https://www.baeldung.com/jersey-rest-api-with-spring)
- [JAX-RS Client with Jersey](https://www.baeldung.com/jersey-jax-rs-client)
- [Reactive JAX-RS Client API](https://www.baeldung.com/jax-rs-reactive-client)
+235
View File
@@ -0,0 +1,235 @@
<?xml version="1.0" encoding="UTF-8"?>
<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">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>spring-jersey</artifactId>
<version>0.1-SNAPSHOT</version>
<name>spring-jersey</name>
<packaging>war</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<!-- core library -->
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>${jersey.version}</version>
</dependency>
<!-- servlet api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${javax.servlet-api.version}</version>
<scope>provided</scope>
</dependency>
<!-- optional library -->
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-spring4</artifactId>
<version>${jersey.version}</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- http client -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>${httpclient.version}</version>
<scope>test</scope>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>${httpcore.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.ext.rx</groupId>
<artifactId>jersey-rx-client-rxjava</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.ext.rx</groupId>
<artifactId>jersey-rx-client-rxjava2</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>com.github.tomakehurst</groupId>
<artifactId>wiremock</artifactId>
<version>${wiremock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-jdk14</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj-core.version}</version>
<scope>test</scope>
</dependency>
<!-- Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>${spring-boot.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<profiles>
<profile>
<id>live</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*IntTest.java</exclude>
</excludes>
<includes>
<include>**/*LiveTest.java</include>
</includes>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.cargo</groupId>
<artifactId>cargo-maven2-plugin</artifactId>
<version>${cargo-maven2-plugin.version}</version>
<configuration>
<wait>false</wait>
</configuration>
<executions>
<execution>
<id>start-server</id>
<phase>pre-integration-test</phase>
<goals>
<goal>start</goal>
</goals>
</execution>
<execution>
<id>stop-server</id>
<phase>post-integration-test</phase>
<goals>
<goal>stop</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<build>
<finalName>spring-jersey</finalName>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>${maven-war-plugin.version}</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.cargo</groupId>
<artifactId>cargo-maven2-plugin</artifactId>
<version>${cargo-maven2-plugin.version}</version>
<configuration>
<wait>true</wait>
<container>
<containerId>jetty8x</containerId>
<type>embedded</type>
</container>
<configuration>
<properties>
<cargo.servlet.port>8082</cargo.servlet.port>
</properties>
</configuration>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<jersey.version>2.29.1</jersey.version>
<cargo-maven2-plugin.version>1.6.1</cargo-maven2-plugin.version>
<httpcore.version>4.4.9</httpcore.version>
<httpclient.version>4.5.5</httpclient.version>
<javax.servlet-api.version>4.0.0</javax.servlet-api.version>
<wiremock.version>2.25.1</wiremock.version>
<assertj-core.version>3.10.0</assertj-core.version>
<spring-boot.version>1.5.10.RELEASE</spring-boot.version>
</properties>
</project>
@@ -0,0 +1,31 @@
package com.baeldung.client.rest;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.baeldung.server.model.Employee;
public class RestClient {
private static final String REST_URI = "http://localhost:8082/spring-jersey/resources/employees";
private Client client = ClientBuilder.newClient();
public Response createJsonEmployee(Employee emp) {
return client.target(REST_URI).request(MediaType.APPLICATION_JSON).post(Entity.entity(emp, MediaType.APPLICATION_JSON));
}
public Employee getJsonEmployee(int id) {
return client.target(REST_URI).path(String.valueOf(id)).request(MediaType.APPLICATION_JSON).get(Employee.class);
}
public Response createXmlEmployee(Employee emp) {
return client.target(REST_URI).request(MediaType.APPLICATION_XML).post(Entity.entity(emp, MediaType.APPLICATION_XML));
}
public Employee getXmlEmployee(int id) {
return client.target(REST_URI).path(String.valueOf(id)).request(MediaType.APPLICATION_XML).get(Employee.class);
}
}
@@ -0,0 +1,22 @@
package com.baeldung.server.config;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
@Order(Ordered.HIGHEST_PRECEDENCE)
public class ApplicationInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
servletContext.addListener(new ContextLoaderListener(context));
servletContext.setInitParameter("contextConfigLocation", "com.baeldung.server");
}
}
@@ -0,0 +1,19 @@
package com.baeldung.server.config;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
import com.baeldung.server.exception.AlreadyExistsExceptionHandler;
import com.baeldung.server.exception.NotFoundExceptionHandler;
import com.baeldung.server.rest.EmployeeResource;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
@ApplicationPath("/resources")
public class RestConfig extends Application {
public Set<Class<?>> getClasses() {
return new HashSet<Class<?>>(Arrays.asList(EmployeeResource.class, NotFoundExceptionHandler.class, AlreadyExistsExceptionHandler.class));
}
}
@@ -0,0 +1,12 @@
package com.baeldung.server.exception;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
@Provider
public class AlreadyExistsExceptionHandler implements ExceptionMapper<EmployeeAlreadyExists> {
public Response toResponse(EmployeeAlreadyExists ex) {
return Response.status(Response.Status.CONFLICT.getStatusCode()).build();
}
}
@@ -0,0 +1,5 @@
package com.baeldung.server.exception;
public class EmployeeAlreadyExists extends RuntimeException {
}
@@ -0,0 +1,5 @@
package com.baeldung.server.exception;
public class EmployeeNotFound extends RuntimeException {
}
@@ -0,0 +1,12 @@
package com.baeldung.server.exception;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
@Provider
public class NotFoundExceptionHandler implements ExceptionMapper<EmployeeNotFound> {
public Response toResponse(EmployeeNotFound ex) {
return Response.status(Response.Status.NOT_FOUND).build();
}
}
@@ -0,0 +1,34 @@
package com.baeldung.server.model;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Employee {
private int id;
private String firstName;
public Employee() {
}
public Employee(int id, String firstName) {
this.id = id;
this.firstName = firstName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
}
@@ -0,0 +1,18 @@
package com.baeldung.server.repository;
import java.util.List;
import com.baeldung.server.model.Employee;
public interface EmployeeRepository {
public List<Employee> getAllEmployees();
public Employee getEmployee(int id);
public void updateEmployee(Employee employee, int id);
public void deleteEmployee(int id);
public void addEmployee(Employee employee);
}
@@ -0,0 +1,65 @@
package com.baeldung.server.repository;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Component;
import com.baeldung.server.exception.EmployeeAlreadyExists;
import com.baeldung.server.exception.EmployeeNotFound;
import com.baeldung.server.model.Employee;
@Component
public class EmployeeRepositoryImpl implements EmployeeRepository {
private List<Employee> employeeList;
public EmployeeRepositoryImpl() {
employeeList = new ArrayList<Employee>();
employeeList.add(new Employee(1, "Jane"));
employeeList.add(new Employee(2, "Jack"));
employeeList.add(new Employee(3, "George"));
}
public List<Employee> getAllEmployees() {
return employeeList;
}
public Employee getEmployee(int id) {
for (Employee emp : employeeList) {
if (emp.getId() == id) {
return emp;
}
}
throw new EmployeeNotFound();
}
public void updateEmployee(Employee employee, int id) {
for (Employee emp : employeeList) {
if (emp.getId() == id) {
emp.setId(employee.getId());
emp.setFirstName(employee.getFirstName());
return;
}
}
throw new EmployeeNotFound();
}
public void deleteEmployee(int id) {
for (Employee emp : employeeList) {
if (emp.getId() == id) {
employeeList.remove(emp);
return;
}
}
throw new EmployeeNotFound();
}
public void addEmployee(Employee employee) {
for (Employee emp : employeeList) {
if (emp.getId() == employee.getId()) {
throw new EmployeeAlreadyExists();
}
}
employeeList.add(employee);
}
}
@@ -0,0 +1,64 @@
package com.baeldung.server.rest;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import org.springframework.beans.factory.annotation.Autowired;
import com.baeldung.server.model.Employee;
import com.baeldung.server.repository.EmployeeRepository;
@Path("/employees")
public class EmployeeResource {
@Autowired
private EmployeeRepository employeeRepository;
@GET
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public List<Employee> getAllEmployees() {
return employeeRepository.getAllEmployees();
}
@GET
@Path("/{id}")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Employee getEmployee(@PathParam("id") int id) {
return employeeRepository.getEmployee(id);
}
@PUT
@Path("/{id}")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response updateEmployee(Employee employee, @PathParam("id") int id) {
employeeRepository.updateEmployee(employee, id);
return Response.status(Response.Status.OK.getStatusCode()).build();
}
@DELETE
@Path("/{id}")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response deleteEmployee(@PathParam("id") int id) {
employeeRepository.deleteEmployee(id);
return Response.status(Response.Status.OK.getStatusCode()).build();
}
@POST
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response addEmployee(Employee employee, @Context UriInfo uriInfo) {
employeeRepository.addEmployee(new Employee(employee.getId(), employee.getFirstName()));
return Response.status(Response.Status.CREATED.getStatusCode()).header("Location", String.format("%s/%s", uriInfo.getAbsolutePath().toString(), employee.getId())).build();
}
}
@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<logger name="org.springframework" level="WARN" />
<logger name="org.springframework.transaction" level="WARN" />
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>
@@ -0,0 +1,53 @@
package com.baeldung.client;
import static org.junit.Assert.assertEquals;
import javax.ws.rs.core.Response;
import org.junit.Test;
import com.baeldung.client.rest.RestClient;
import com.baeldung.server.model.Employee;
public class JerseyClientLiveTest {
public static final int HTTP_CREATED = 201;
private RestClient client = new RestClient();
@Test
public void givenCorrectObject_whenCorrectJsonRequest_thenResponseCodeCreated() {
Employee emp = new Employee(6, "Johny");
Response response = client.createJsonEmployee(emp);
assertEquals(response.getStatus(), HTTP_CREATED);
}
@Test
public void givenCorrectObject_whenCorrectXmlRequest_thenResponseCodeCreated() {
Employee emp = new Employee(7, "Jacky");
Response response = client.createXmlEmployee(emp);
assertEquals(response.getStatus(), HTTP_CREATED);
}
@Test
public void givenCorrectId_whenCorrectJsonRequest_thenCorrectEmployeeRetrieved() {
int employeeId = 1;
Employee emp = client.getJsonEmployee(employeeId);
assertEquals(emp.getFirstName(), "Jane");
}
@Test
public void givenCorrectId_whenCorrectXmlRequest_thenCorrectEmployeeRetrieved() {
int employeeId = 1;
Employee emp = client.getXmlEmployee(employeeId);
assertEquals(emp.getFirstName(), "Jane");
}
}
@@ -0,0 +1,272 @@
package com.baeldung.clientrx;
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<>();
final CountDownLatch completionTracker = new CountDownLatch(expectedHashValues.size()); // used to keep track of the progress of the subsequent calls
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);
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);
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);
completionTracker.countDown();
}
@Override
public void failed(Throwable throwable) {
logger.warn("[CallbackExample] An error has occurred in the hashing request step!", throwable);
}
});
}
@Override
public void failed(Throwable throwable) {
logger.warn("[CallbackExample] An error has occurred in the username request step!", throwable);
}
});
});
}
@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
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);
}
assertThat(receivedHashValues).containsAll(expectedHashValues);
}
@Test
public void rxOrchestrate() throws InterruptedException {
List<String> receivedHashValues = new ArrayList<>();
final CountDownLatch completionTracker = new CountDownLatch(expectedHashValues.size()); // used to keep track of the progress of the subsequent calls
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);
completionTracker.countDown();
}).exceptionally((throwable) -> {
logger.warn("[CompletionStageExample] Hash computation failed for {}", id);
completionTracker.countDown();
return null;
});
});
});
});
// wait for async calls to complete
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);
}
assertThat(receivedHashValues).containsAll(expectedHashValues);
}
@Test
public void observableJavaOrchestrate() throws InterruptedException {
List<String> receivedHashValues = new ArrayList<>();
final CountDownLatch completionTracker = new CountDownLatch(expectedHashValues.size()); // used to keep track of the progress of the subsequent calls
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);
completionTracker.countDown();
});
}));
});
// wait for async calls to complete
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);
}
assertThat(receivedHashValues).containsAll(expectedHashValues);
}
@Test
public void flowableJavaOrchestrate() throws InterruptedException {
List<String> receivedHashValues = new ArrayList<>();
final CountDownLatch completionTracker = new CountDownLatch(expectedHashValues.size()); // used to keep track of the progress of the subsequent calls
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);
completionTracker.countDown();
});
});
});
});
// wait for async calls to complete
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);
}
assertThat(receivedHashValues).containsAll(expectedHashValues);
}
}
@@ -0,0 +1,92 @@
package com.baeldung.server;
import static org.junit.Assert.assertEquals;
import com.baeldung.server.model.Employee;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.junit.Test;
import java.io.IOException;
public class JerseyApiLiveTest {
private static final String SERVICE_URL = "http://localhost:8082/spring-jersey/resources/employees";
@Test
public void givenGetAllEmployees_whenCorrectRequest_thenResponseCodeSuccess() throws IOException {
final HttpUriRequest request = new HttpGet(SERVICE_URL);
final HttpResponse httpResponse = HttpClientBuilder.create().build().execute(request);
assertEquals(httpResponse.getStatusLine().getStatusCode(), HttpStatus.SC_OK);
}
@Test
public void givenGetEmployee_whenEmployeeExists_thenResponseCodeSuccess() throws IOException {
final HttpUriRequest request = new HttpGet(SERVICE_URL + "/1");
final HttpResponse httpResponse = HttpClientBuilder.create().build().execute(request);
assertEquals(httpResponse.getStatusLine().getStatusCode(), HttpStatus.SC_OK);
}
@Test
public void givenGetEmployee_whenEmployeeDoesNotExist_thenResponseCodeNotFound() throws IOException {
final HttpUriRequest request = new HttpGet(SERVICE_URL + "/1000");
final HttpResponse httpResponse = HttpClientBuilder.create().build().execute(request);
assertEquals(httpResponse.getStatusLine().getStatusCode(), HttpStatus.SC_NOT_FOUND);
}
@Test
public void givenGetEmployee_whenJsonRequested_thenCorrectDataRetrieved() throws IOException {
final HttpUriRequest request = new HttpGet(SERVICE_URL + "/1");
request.setHeader("Accept", "application/json");
final HttpResponse httpResponse = HttpClientBuilder.create().build().execute(request);
ObjectMapper mapper = new ObjectMapper();
Employee emp = mapper.readValue(httpResponse.getEntity().getContent(), Employee.class);
assertEquals(emp.getFirstName(), "Jane");
}
@Test
public void givenAddEmployee_whenJsonRequestSent_thenResponseCodeCreated() throws IOException {
final HttpPost request = new HttpPost(SERVICE_URL);
Employee emp = new Employee(5, "Johny");
ObjectMapper mapper = new ObjectMapper();
String empJson = mapper.writeValueAsString(emp);
StringEntity input = new StringEntity(empJson);
input.setContentType("application/json");
request.setEntity(input);
final HttpResponse httpResponse = HttpClientBuilder.create().build().execute(request);
assertEquals(httpResponse.getStatusLine().getStatusCode(), HttpStatus.SC_CREATED);
}
@Test
public void givenAddEmployee_whenRequestForExistingObjectSent_thenResponseCodeConflict() throws IOException {
final HttpPost request = new HttpPost(SERVICE_URL);
Employee emp = new Employee(1, "Johny");
ObjectMapper mapper = new ObjectMapper();
String empJson = mapper.writeValueAsString(emp);
StringEntity input = new StringEntity(empJson);
input.setContentType("application/json");
request.setEntity(input);
final HttpResponse httpResponse = HttpClientBuilder.create().build().execute(request);
assertEquals(httpResponse.getStatusLine().getStatusCode(), HttpStatus.SC_CONFLICT);
}
}
@@ -0,0 +1,17 @@
package org.baeldung;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.baeldung.server.config.RestConfig;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = RestConfig.class)
public class SpringContextIntegrationTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}
@@ -0,0 +1,17 @@
package org.baeldung;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.baeldung.server.config.RestConfig;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = RestConfig.class)
public class SpringContextTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}