Skip to content

Instantly share code, notes, and snippets.

@psamsotha

psamsotha/AsyncTest.java

Last active Aug 27, 2018
Embed
What would you like to do?
A Jersey client test using Jersey Test Framework to show how to make async requests.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Path;
import javax.ws.rs.client.InvocationCallback;
import javax.ws.rs.container.AsyncResponse;
import javax.ws.rs.container.Suspended;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.server.ManagedAsync;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.junit.Test;
/**
* Async client test using Jersey Test Framework. Only one required dependency.
* To show that the request are asynchronous, I used a header to show which
* request is being sent and the data is sent back and put into a list.
* You should see that the list is not in the order the requests were sent
* because of the random sleep.
*
* <dependency>
* <groupId>org.glassfish.jersey.test-framework.providers</groupId>
* <artifactId>jersey-test-framework-provider-grizzly2</artifactId>
* <version>2.25.1</version>
* <scope>test</scope>
* </dependency>
*/
public class AsyncTest extends JerseyTest {
@Path("test")
public static class TestResource {
@GET
@ManagedAsync
public void get(@Suspended AsyncResponse res,
@HeaderParam("X-Request-Number") int num) throws Exception {
String data = "TestData #" + num;
Random random = new Random();
Thread.sleep(random.nextInt(1000));
res.resume(Response.ok(data).type("text/plain").build());
}
}
@Override
public ResourceConfig configure() {
return new ResourceConfig()
.register(new TestResource());
}
@Test
public void testIt() throws Exception {
final List<String> results = Collections.synchronizedList(new ArrayList<>());
final CountDownLatch latch = new CountDownLatch(10);
for (int i = 1; i <= 10; i++) {
target("test").request()
.header("X-Request-Number", i)
.async()
.get(new InvocationCallback<Response>() {
@Override
public void completed(Response res) {
String data = res.readEntity(String.class);
results.add(data);
latch.countDown();
}
@Override
public void failed(Throwable t) {
t.printStackTrace();
latch.countDown();
}
});
}
latch.await();
System.out.println(results);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.