use of javax.ws.rs.client.WebTarget in project jersey by jersey.
the class ManagedAsyncResourceTest method testLongRunningResource.
@Test
public void testLongRunningResource() throws InterruptedException {
final WebTarget resourceTarget = target().path(App.ASYNC_LONG_RUNNING_MANAGED_OP_PATH);
final String expectedResponse = SimpleJerseyExecutorManagedLongRunningResource.NOTIFICATION_RESPONSE;
final int MAX_MESSAGES = 100;
final int LATCH_WAIT_TIMEOUT = 10 * getAsyncTimeoutMultiplier();
final boolean debugMode = false;
final boolean sequentialGet = false;
final Object sequentialGetLock = new Object();
final ExecutorService executor = Executors.newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("async-resource-test-%d").setUncaughtExceptionHandler(new JerseyProcessingUncaughtExceptionHandler()).build());
final Map<Integer, String> getResponses = new ConcurrentHashMap<Integer, String>();
final CountDownLatch getRequestLatch = new CountDownLatch(MAX_MESSAGES);
try {
for (int i = 0; i < MAX_MESSAGES; i++) {
final int requestId = i;
executor.submit(new Runnable() {
@Override
public void run() {
if (debugMode || sequentialGet) {
synchronized (sequentialGetLock) {
get();
}
} else {
get();
}
}
private void get() {
try {
int attemptCounter = 0;
while (true) {
attemptCounter++;
try {
final String response = resourceTarget.queryParam("id", requestId).request().get(String.class);
getResponses.put(requestId, response);
break;
} catch (Throwable t) {
LOGGER.log(Level.SEVERE, String.format("Error sending GET request <%s> for %d. time.", requestId, attemptCounter), t);
}
if (attemptCounter > 3) {
break;
}
Thread.sleep(10);
}
} catch (InterruptedException ignored) {
LOGGER.log(Level.WARNING, String.format("Error sending GET message <%s>: Interrupted", requestId), ignored);
} finally {
getRequestLatch.countDown();
}
}
});
}
if (debugMode) {
getRequestLatch.await();
} else {
if (!getRequestLatch.await(LATCH_WAIT_TIMEOUT, TimeUnit.SECONDS)) {
LOGGER.log(Level.SEVERE, "Waiting for all GET requests to complete has timed out.");
}
}
} finally {
executor.shutdownNow();
}
StringBuilder messageBuilder = new StringBuilder("GET responses received: ").append(getResponses.size()).append("\n");
for (Map.Entry<Integer, String> getResponseEntry : getResponses.entrySet()) {
messageBuilder.append("GET response for message ").append(getResponseEntry.getKey()).append(": ").append(getResponseEntry.getValue()).append('\n');
}
LOGGER.info(messageBuilder.toString());
for (Map.Entry<Integer, String> entry : getResponses.entrySet()) {
assertTrue("Unexpected GET notification response for message " + entry.getKey(), entry.getValue().contains(expectedResponse));
}
assertEquals(MAX_MESSAGES, getResponses.size());
}
use of javax.ws.rs.client.WebTarget in project jersey by jersey.
the class Main method runClient.
/**
* Client - business logic.
*
* @param args command-line arguments.
* @return exit code of the utility. {@code 0} if everything completed without errors, {@code -1} otherwise.
*/
static int runClient(final String[] args) {
// Parsing command-line arguments
final Config config = Config.parse(args);
System.out.println(String.format("\nStarting to execute %d requests:\n", config.requests));
// Creating JAX-RS client
final Client client = ClientBuilder.newClient();
// Targeting echo resource at URI "<baseUri>/long-running/(sync|async)/{echo}"
final WebTarget echoResource = client.target(config.baseUri).path("long-running/{mode}/{echo}").resolveTemplate("mode", (config.sync) ? "sync" : "async");
final CountDownLatch latch = new CountDownLatch(config.requests);
final Queue<String> errors = new ConcurrentLinkedQueue<String>();
final AtomicInteger requestCounter = new AtomicInteger(0);
final long tic = System.currentTimeMillis();
for (int i = 0; i < config.requests; i++) {
final int reqId = i;
echoResource.resolveTemplate("echo", reqId).request().async().get(new InvocationCallback<String>() {
private final AtomicInteger retries = new AtomicInteger(0);
@Override
public void completed(String response) {
final String requestId = Integer.toString(reqId);
if (requestId.equals(response)) {
System.out.print("*");
requestCounter.incrementAndGet();
} else {
System.out.print("!");
errors.offer(String.format("Echo response '%s' not equal to request '%s'", response, requestId));
}
latch.countDown();
}
@Override
public void failed(Throwable error) {
if (error.getCause() instanceof IOException && retries.getAndIncrement() < 3) {
// resend
echoResource.resolveTemplate("echo", reqId).request().async().get(this);
} else {
System.out.print("!");
errors.offer(String.format("Request '%d' has failed: %s", reqId, error.toString()));
latch.countDown();
}
}
});
}
try {
if (!latch.await(60, TimeUnit.SECONDS)) {
errors.offer("Waiting for requests to complete has timed out.");
}
} catch (InterruptedException e) {
errors.offer("Waiting for requests to complete has been interrupted.");
}
final long toc = System.currentTimeMillis();
System.out.println(String.format("\n\nExecution finished in %d ms.\nSuccess rate: %6.2f %%", toc - tic, ((double) requestCounter.get() / config.requests) * 100));
if (errors.size() > 0) {
System.out.println("Following errors occurred during the request execution");
for (String error : errors) {
System.out.println("\t" + error);
}
}
client.close();
return errors.size() > 0 ? -1 : 0;
}
use of javax.ws.rs.client.WebTarget in project jersey by jersey.
the class ItemStoreResourceTest method testItemsStore.
/**
* Test the item addition, addition event broadcasting and item retrieval from {@link ItemStoreResource}.
*
* @throws Exception in case of a test failure.
*/
@Test
public void testItemsStore() throws Exception {
final List<String> items = Collections.unmodifiableList(Arrays.asList("foo", "bar", "baz"));
final WebTarget itemsTarget = target("items");
// countdown on all events
final CountDownLatch latch = new CountDownLatch(items.size() * MAX_LISTENERS * 2);
final List<Queue<Integer>> indexQueues = new ArrayList<Queue<Integer>>(MAX_LISTENERS);
final EventSource[] sources = new EventSource[MAX_LISTENERS];
final AtomicInteger sizeEventsCount = new AtomicInteger(0);
for (int i = 0; i < MAX_LISTENERS; i++) {
final int id = i;
final EventSource es = EventSource.target(itemsTarget.path("events")).named("SOURCE " + id).build();
sources[id] = es;
final Queue<Integer> indexes = new ConcurrentLinkedQueue<Integer>();
indexQueues.add(indexes);
es.register(new EventListener() {
@SuppressWarnings("MagicNumber")
@Override
public void onEvent(InboundEvent inboundEvent) {
try {
if (inboundEvent.getName() == null) {
final String data = inboundEvent.readData();
LOGGER.info("[-i-] SOURCE " + id + ": Received event id=" + inboundEvent.getId() + " data=" + data);
indexes.add(items.indexOf(data));
} else if ("size".equals(inboundEvent.getName())) {
sizeEventsCount.incrementAndGet();
}
} catch (Exception ex) {
LOGGER.log(Level.SEVERE, "[-x-] SOURCE " + id + ": Error getting event data.", ex);
indexes.add(-999);
} finally {
latch.countDown();
}
}
});
}
try {
open(sources);
for (String item : items) {
postItem(itemsTarget, item);
}
assertTrue("Waiting to receive all events has timed out.", latch.await((1000 + MAX_LISTENERS * EventSource.RECONNECT_DEFAULT) * getAsyncTimeoutMultiplier(), TimeUnit.MILLISECONDS));
// need to force disconnect on server in order for EventSource.close(...) to succeed with HttpUrlConnection
sendCommand(itemsTarget, "disconnect");
} finally {
close(sources);
}
String postedItems = itemsTarget.request().get(String.class);
for (String item : items) {
assertTrue("Item '" + item + "' not stored on server.", postedItems.contains(item));
}
int queueId = 0;
for (Queue<Integer> indexes : indexQueues) {
for (int i = 0; i < items.size(); i++) {
assertTrue("Event for '" + items.get(i) + "' not received in queue " + queueId, indexes.contains(i));
}
assertEquals("Not received the expected number of events in queue " + queueId, items.size(), indexes.size());
queueId++;
}
assertEquals("Number of received 'size' events does not match.", items.size() * MAX_LISTENERS, sizeEventsCount.get());
}
use of javax.ws.rs.client.WebTarget in project jersey by jersey.
the class AsyncResourceTest method testLongRunningResource.
@Test
public void testLongRunningResource() throws InterruptedException {
final WebTarget resourceTarget = target().path(App.ASYNC_LONG_RUNNING_OP_PATH);
final String expectedResponse = SimpleLongRunningResource.NOTIFICATION_RESPONSE;
final int MAX_MESSAGES = 100;
final int LATCH_WAIT_TIMEOUT = 25 * getAsyncTimeoutMultiplier();
final boolean debugMode = false;
final boolean sequentialGet = false;
final Object sequentialGetLock = new Object();
final ExecutorService executor = Executors.newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("async-resource-test-%02d").setUncaughtExceptionHandler(new JerseyProcessingUncaughtExceptionHandler()).build());
final Map<Integer, String> getResponses = new ConcurrentHashMap<Integer, String>();
final CountDownLatch getRequestLatch = new CountDownLatch(MAX_MESSAGES);
try {
for (int i = 0; i < MAX_MESSAGES; i++) {
final int requestId = i;
executor.submit(new Runnable() {
@Override
public void run() {
if (debugMode || sequentialGet) {
synchronized (sequentialGetLock) {
get();
}
} else {
get();
}
}
private void get() {
try {
int attemptCounter = 0;
while (true) {
attemptCounter++;
try {
final String response = resourceTarget.request().get(String.class);
getResponses.put(requestId, response);
break;
} catch (Throwable t) {
LOGGER.log(Level.SEVERE, String.format("Error sending GET request <%s> for %d. time.", requestId, attemptCounter), t);
}
if (attemptCounter > 3) {
break;
}
Thread.sleep(10);
}
} catch (InterruptedException ignored) {
LOGGER.log(Level.WARNING, String.format("Error sending GET message <%s>: Interrupted", requestId), ignored);
} finally {
getRequestLatch.countDown();
}
}
});
}
if (debugMode) {
getRequestLatch.await();
} else {
if (!getRequestLatch.await(LATCH_WAIT_TIMEOUT, TimeUnit.SECONDS)) {
LOGGER.log(Level.SEVERE, "Waiting for all GET requests to complete has timed out.");
}
}
} finally {
executor.shutdownNow();
}
final ArrayList<Map.Entry<Integer, String>> responseEntryList = new ArrayList<Map.Entry<Integer, String>>(getResponses.entrySet());
Collections.sort(responseEntryList, new Comparator<Map.Entry<Integer, String>>() {
@Override
public int compare(Map.Entry<Integer, String> o1, Map.Entry<Integer, String> o2) {
return o1.getKey().compareTo(o2.getKey());
}
});
StringBuilder messageBuilder = new StringBuilder("GET responses received: ").append(responseEntryList.size()).append("\n");
for (Map.Entry<Integer, String> getResponseEntry : responseEntryList) {
messageBuilder.append(String.format("GET response for message %02d: ", getResponseEntry.getKey())).append(getResponseEntry.getValue()).append('\n');
}
LOGGER.info(messageBuilder.toString());
for (Map.Entry<Integer, String> entry : responseEntryList) {
assertEquals(String.format("Unexpected GET notification response for message %02d", entry.getKey()), expectedResponse, entry.getValue());
}
assertEquals(MAX_MESSAGES, getResponses.size());
}
use of javax.ws.rs.client.WebTarget in project jersey by jersey.
the class MainWindow method sendMessages.
private void sendMessages(final Main.Config config) {
// Creating JAX-RS client
final Client client = ClientBuilder.newClient();
// Targeting echo resource at URI "<baseUri>/long-running/(sync|async)/{echo}"
final WebTarget echoResource = client.target(config.baseUri).path("long-running/{mode}/{echo}").resolveTemplate("mode", (config.sync) ? "sync" : "async");
final CountDownLatch latch = new CountDownLatch(config.requests);
final AtomicInteger requestCounter = new AtomicInteger(0);
final long tic = System.currentTimeMillis();
for (int i = 0; i < config.requests; i++) {
final int reqId = i;
final JLabel requestStatusLabel = createRequestStatusLabel();
echoResource.resolveTemplate("echo", reqId).request().async().get(new InvocationCallback<String>() {
private final AtomicInteger retries = new AtomicInteger(0);
@Override
public void completed(final String response) {
invokeAndWait(new Runnable() {
@Override
public void run() {
final String requestId = Integer.toString(reqId);
if (requestId.equals(response)) {
requestStatusLabel.setBackground(SUCCESS_COLOR);
requestStatusLabel.setToolTipText(requestId);
requestCounter.incrementAndGet();
} else {
requestStatusLabel.setBackground(ERROR_COLOR);
requestStatusLabel.setToolTipText(String.format("Echo response '%s' not equal to request '%s'", response, requestId));
}
latch.countDown();
}
});
}
@Override
public void failed(final Throwable error) {
if (error.getCause() instanceof IOException && retries.getAndIncrement() < 3) {
// resend
echoResource.resolveTemplate("echo", reqId).request().async().get(this);
} else {
invokeAndWait(new Runnable() {
@Override
public void run() {
requestStatusLabel.setBackground(ERROR_COLOR);
requestStatusLabel.setToolTipText(String.format("Request '%d' has failed: %s", reqId, error.toString()));
latch.countDown();
}
});
}
}
});
}
try {
if (!latch.await(60, TimeUnit.SECONDS)) {
System.out.println("Waiting for requests to complete has timed out.");
}
} catch (InterruptedException e) {
System.out.println("Waiting for requests to complete has been interrupted.");
}
final long toc = System.currentTimeMillis();
invokeAndWait(new Runnable() {
@Override
public void run() {
finishStatusLabel.setText(String.format("Execution finished in %d ms.", toc - tic));
successRateStatusLabel.setText(String.format("Success rate: %6.2f %%", ((double) requestCounter.get() / config.requests) * 100));
}
});
client.close();
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
runButton.setEnabled(true);
}
});
}
Aggregations