use of javax.ws.rs.ProcessingException in project jersey by jersey.
the class InterceptorCustomTest method testIOException.
@Test
public void testIOException() throws IOException {
client().register(IOExceptionReaderInterceptor.class);
WebTarget target = target().path("test");
Response response = target.request().put(Entity.entity(ENTITY, MediaType.TEXT_PLAIN_TYPE));
try {
response.readEntity(String.class);
fail("ProcessingException expected.");
} catch (ProcessingException e) {
assertTrue(e.getCause() instanceof IOException);
}
}
use of javax.ws.rs.ProcessingException in project jersey by jersey.
the class AsyncServletResourceITCase method testAsyncRequestCanceling.
/**
* Test canceling of an async request to a servlet-deployed resource.
*
* @throws InterruptedException in case the waiting for all requests to complete was interrupted.
*/
@Test
public void testAsyncRequestCanceling() throws InterruptedException {
final WebTarget resourceTarget = target("async/canceled");
resourceTarget.register(LoggingFeature.class);
final int MAX_MESSAGES = 10;
final int LATCH_WAIT_TIMEOUT = 10 * getAsyncTimeoutMultiplier();
final boolean debugMode = false;
final boolean sequentialGet = false;
final boolean sequentialPost = false;
final Object sequentialGetLock = new Object();
final Object sequentialPostLock = new Object();
final ExecutorService executor = Executors.newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("async-canceled-resource-test-%d").setUncaughtExceptionHandler(new JerseyProcessingUncaughtExceptionHandler()).build());
final Map<Integer, String> postResponses = new ConcurrentHashMap<Integer, String>();
final Map<Integer, String> getResponses = new ConcurrentHashMap<Integer, String>();
final CountDownLatch postRequestLatch = new CountDownLatch(MAX_MESSAGES);
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() {
//noinspection PointlessBooleanExpression,ConstantConditions
if (debugMode || sequentialGet) {
synchronized (sequentialGetLock) {
get();
}
} else {
get();
}
}
private void get() {
try {
final String response = resourceTarget.queryParam("id", requestId).request().get(String.class);
getResponses.put(requestId, response);
} catch (WebApplicationException ex) {
final Response response = ex.getResponse();
getResponses.put(requestId, response.getStatus() + ": " + response.readEntity(String.class));
} finally {
getRequestLatch.countDown();
}
}
});
executor.submit(new Runnable() {
@Override
public void run() {
//noinspection PointlessBooleanExpression,ConstantConditions
if (debugMode || sequentialPost) {
synchronized (sequentialPostLock) {
post();
}
} else {
post();
}
}
private void post() throws ProcessingException {
try {
final String response = resourceTarget.request().post(Entity.text("" + requestId), String.class);
postResponses.put(requestId, response);
} finally {
postRequestLatch.countDown();
}
}
});
}
//noinspection ConstantConditions
if (debugMode) {
postRequestLatch.await();
getRequestLatch.await();
} else {
assertTrue("Waiting for all POST requests to complete has timed out.", postRequestLatch.await(LATCH_WAIT_TIMEOUT, TimeUnit.SECONDS));
assertTrue("Waiting for all GET requests to complete has timed out.", getRequestLatch.await(LATCH_WAIT_TIMEOUT, TimeUnit.SECONDS));
}
} finally {
executor.shutdownNow();
}
StringBuilder messageBuilder = new StringBuilder();
for (Map.Entry<Integer, String> postResponseEntry : postResponses.entrySet()) {
messageBuilder.append("POST response for message ").append(postResponseEntry.getKey()).append(": ").append(postResponseEntry.getValue()).append('\n');
}
messageBuilder.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());
assertEquals(MAX_MESSAGES, postResponses.size());
for (Map.Entry<Integer, String> postResponseEntry : postResponses.entrySet()) {
assertTrue("Unexpected POST notification response for message " + postResponseEntry.getKey(), postResponseEntry.getValue().startsWith(AsyncServletResource.CANCELED));
}
assertEquals(MAX_MESSAGES, getResponses.size());
final Collection<Integer> getResponseKeys = getResponses.keySet();
for (int i = 0; i < MAX_MESSAGES; i++) {
assertTrue("Detected a GET message response loss: " + i, getResponseKeys.contains(i));
final String getResponseEntry = getResponses.get(i);
assertTrue("Unexpected canceled GET response status for request " + i, getResponseEntry.startsWith("503: "));
}
}
use of javax.ws.rs.ProcessingException in project jersey by jersey.
the class ItemStoreResourceITCase method testEventSourceReconnect.
/**
* Test the {@link EventSource} reconnect feature.
*
* @throws Exception in case of a test failure.
*/
@Test
public void testEventSourceReconnect() throws Exception {
final WebTarget itemsTarget = target("items");
// countdown only on new item events
final CountDownLatch latch = new CountDownLatch(MAX_ITEMS * MAX_LISTENERS * 2);
final List<Queue<String>> receivedQueues = new ArrayList<Queue<String>>(MAX_LISTENERS);
final EventSource[] sources = new EventSource[MAX_LISTENERS];
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<String> received = new ConcurrentLinkedQueue<String>();
receivedQueues.add(received);
es.register(new EventListener() {
@Override
public void onEvent(InboundEvent inboundEvent) {
try {
if (inboundEvent.getName() == null) {
latch.countDown();
final String data = inboundEvent.readData();
LOGGER.info("[-i-] SOURCE " + id + ": Received event id=" + inboundEvent.getId() + " data=" + data);
received.add(data);
}
} catch (ProcessingException ex) {
LOGGER.log(Level.SEVERE, "[-x-] SOURCE " + id + ": Error getting event data.", ex);
received.add("[data processing error]");
}
}
});
}
final String[] postedItems = new String[MAX_ITEMS * 2];
try {
open(sources);
for (int i = 0; i < MAX_ITEMS; i++) {
final String item = String.format("round-1-%02d", i);
postItem(itemsTarget, item);
postedItems[i] = item;
sendCommand(itemsTarget, "disconnect");
Thread.sleep(100);
}
final int reconnectDelay = 1;
sendCommand(itemsTarget, "reconnect " + reconnectDelay);
sendCommand(itemsTarget, "disconnect");
Thread.sleep(reconnectDelay * 1000);
for (int i = 0; i < MAX_ITEMS; i++) {
final String item = String.format("round-2-%02d", i);
postedItems[i + MAX_ITEMS] = item;
postItem(itemsTarget, item);
}
sendCommand(itemsTarget, "reconnect now");
assertTrue("Waiting to receive all events has timed out.", latch.await((1 + MAX_LISTENERS * (MAX_ITEMS + 1) * reconnectDelay) * getAsyncTimeoutMultiplier(), TimeUnit.SECONDS));
// need to force disconnect on server in order for EventSource.close(...) to succeed with HttpUrlConnection
sendCommand(itemsTarget, "disconnect");
} finally {
close(sources);
}
final String storedItems = itemsTarget.request().get(String.class);
for (String item : postedItems) {
assertThat("Posted item '" + item + "' stored on server", storedItems, containsString(item));
}
int sourceId = 0;
for (Queue<String> queue : receivedQueues) {
assertThat("Received events in source " + sourceId, queue, describedAs("Collection containing %0", hasItems(postedItems), Arrays.asList(postedItems).toString()));
assertThat("Size of received queue for source " + sourceId, queue.size(), equalTo(postedItems.length));
sourceId++;
}
}
use of javax.ws.rs.ProcessingException in project jersey by jersey.
the class AsyncServletResourceTest method testAsyncRequestCanceling.
/**
* Test canceling of an async request to a servlet-deployed resource.
*
* @throws InterruptedException in case the waiting for all requests to complete was interrupted.
*/
@Test
public void testAsyncRequestCanceling() throws InterruptedException {
final WebTarget resourceTarget = target("async/canceled");
resourceTarget.register(LoggingFeature.class);
final int MAX_MESSAGES = 10;
final int LATCH_WAIT_TIMEOUT = 10;
final boolean debugMode = false;
final boolean sequentialGet = false;
final boolean sequentialPost = false;
final Object sequentialGetLock = new Object();
final Object sequentialPostLock = new Object();
final ExecutorService executor = Executors.newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("async-canceled-resource-test-%d").setUncaughtExceptionHandler(new JerseyProcessingUncaughtExceptionHandler()).build());
final Map<Integer, String> postResponses = new ConcurrentHashMap<>();
final Map<Integer, String> getResponses = new ConcurrentHashMap<>();
final CountDownLatch postRequestLatch = new CountDownLatch(MAX_MESSAGES);
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() {
//noinspection PointlessBooleanExpression,ConstantConditions
if (debugMode || sequentialGet) {
synchronized (sequentialGetLock) {
get();
}
} else {
get();
}
}
private void get() {
try {
final String response = resourceTarget.queryParam("id", requestId).request().get(String.class);
getResponses.put(requestId, response);
} catch (final WebApplicationException ex) {
final Response response = ex.getResponse();
getResponses.put(requestId, response.getStatus() + ": " + response.readEntity(String.class));
} finally {
getRequestLatch.countDown();
}
}
});
executor.submit(new Runnable() {
@Override
public void run() {
//noinspection PointlessBooleanExpression,ConstantConditions
if (debugMode || sequentialPost) {
synchronized (sequentialPostLock) {
post();
}
} else {
post();
}
}
private void post() throws ProcessingException {
try {
final String response = resourceTarget.request().post(Entity.text("" + requestId), String.class);
postResponses.put(requestId, response);
} finally {
postRequestLatch.countDown();
}
}
});
}
//noinspection ConstantConditions
if (debugMode) {
postRequestLatch.await();
getRequestLatch.await();
} else {
assertTrue("Waiting for all POST requests to complete has timed out.", postRequestLatch.await(LATCH_WAIT_TIMEOUT * getAsyncTimeoutMultiplier(), TimeUnit.SECONDS));
assertTrue("Waiting for all GET requests to complete has timed out.", getRequestLatch.await(LATCH_WAIT_TIMEOUT * getAsyncTimeoutMultiplier(), TimeUnit.SECONDS));
}
} finally {
executor.shutdownNow();
}
final StringBuilder messageBuilder = new StringBuilder();
for (final Map.Entry<Integer, String> postResponseEntry : postResponses.entrySet()) {
messageBuilder.append("POST response for message ").append(postResponseEntry.getKey()).append(": ").append(postResponseEntry.getValue()).append('\n');
}
messageBuilder.append('\n');
for (final 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());
assertEquals(MAX_MESSAGES, postResponses.size());
for (final Map.Entry<Integer, String> postResponseEntry : postResponses.entrySet()) {
assertTrue("Unexpected POST notification response for message " + postResponseEntry.getKey(), postResponseEntry.getValue().startsWith(AsyncServletResource.CANCELED));
}
assertEquals(MAX_MESSAGES, getResponses.size());
final Collection<Integer> getResponseKeys = getResponses.keySet();
for (int i = 0; i < MAX_MESSAGES; i++) {
assertTrue("Detected a GET message response loss: " + i, getResponseKeys.contains(i));
final String getResponseEntry = getResponses.get(i);
assertTrue("Unexpected canceled GET response status for request " + i, getResponseEntry.startsWith("503: "));
}
}
use of javax.ws.rs.ProcessingException in project ddf by codice.
the class GeoNamesWebService method query.
private Object query(String urlStr) {
final String response;
try {
WebClient client = createWebClient(urlStr);
response = client.acceptEncoding(StandardCharsets.UTF_8.name()).accept("application/json").get(String.class);
} catch (WebApplicationException | ProcessingException e) {
LOGGER.debug("Error while making GeoNames request.", e);
return null;
}
try {
JSONParser parser = new JSONParser(JSONParser.MODE_JSON_SIMPLE);
return parser.parse(response);
} catch (ParseException e) {
LOGGER.debug("Error while parsing JSON message from GeoNames service.", e);
return null;
}
}
Aggregations