Search in sources :

Example 86 with ProcessingException

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);
    }
}
Also used : Response(javax.ws.rs.core.Response) WebTarget(javax.ws.rs.client.WebTarget) IOException(java.io.IOException) ProcessingException(javax.ws.rs.ProcessingException) JerseyTest(org.glassfish.jersey.test.JerseyTest) Test(org.junit.Test)

Example 87 with ProcessingException

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: "));
    }
}
Also used : JerseyProcessingUncaughtExceptionHandler(org.glassfish.jersey.process.JerseyProcessingUncaughtExceptionHandler) WebApplicationException(javax.ws.rs.WebApplicationException) CountDownLatch(java.util.concurrent.CountDownLatch) Response(javax.ws.rs.core.Response) ExecutorService(java.util.concurrent.ExecutorService) ThreadFactoryBuilder(org.glassfish.jersey.internal.guava.ThreadFactoryBuilder) WebTarget(javax.ws.rs.client.WebTarget) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Map(java.util.Map) ProcessingException(javax.ws.rs.ProcessingException) Test(org.junit.Test) JerseyTest(org.glassfish.jersey.test.JerseyTest)

Example 88 with ProcessingException

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++;
    }
}
Also used : ArrayList(java.util.ArrayList) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) CountDownLatch(java.util.concurrent.CountDownLatch) EventSource(org.glassfish.jersey.media.sse.EventSource) InboundEvent(org.glassfish.jersey.media.sse.InboundEvent) WebTarget(javax.ws.rs.client.WebTarget) EventListener(org.glassfish.jersey.media.sse.EventListener) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) Queue(java.util.Queue) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) ProcessingException(javax.ws.rs.ProcessingException) JerseyTest(org.glassfish.jersey.test.JerseyTest) Test(org.junit.Test)

Example 89 with ProcessingException

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: "));
    }
}
Also used : JerseyProcessingUncaughtExceptionHandler(org.glassfish.jersey.process.JerseyProcessingUncaughtExceptionHandler) WebApplicationException(javax.ws.rs.WebApplicationException) CountDownLatch(java.util.concurrent.CountDownLatch) Response(javax.ws.rs.core.Response) ExecutorService(java.util.concurrent.ExecutorService) ThreadFactoryBuilder(org.glassfish.jersey.internal.guava.ThreadFactoryBuilder) WebTarget(javax.ws.rs.client.WebTarget) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ProcessingException(javax.ws.rs.ProcessingException) JerseyTest(org.glassfish.jersey.test.JerseyTest) Test(org.junit.Test)

Example 90 with ProcessingException

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;
    }
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) JSONParser(net.minidev.json.parser.JSONParser) ParseException(net.minidev.json.parser.ParseException) WebClient(org.apache.cxf.jaxrs.client.WebClient) ProcessingException(javax.ws.rs.ProcessingException)

Aggregations

ProcessingException (javax.ws.rs.ProcessingException)91 Test (org.junit.Test)32 IOException (java.io.IOException)26 Response (javax.ws.rs.core.Response)20 WebTarget (javax.ws.rs.client.WebTarget)19 JerseyTest (org.glassfish.jersey.test.JerseyTest)16 WebApplicationException (javax.ws.rs.WebApplicationException)11 CountDownLatch (java.util.concurrent.CountDownLatch)9 Client (javax.ws.rs.client.Client)9 ResponseProcessingException (javax.ws.rs.client.ResponseProcessingException)9 ByteArrayOutputStream (java.io.ByteArrayOutputStream)8 ClientRequest (org.glassfish.jersey.client.ClientRequest)8 ClientResponse (org.glassfish.jersey.client.ClientResponse)8 ByteArrayInputStream (java.io.ByteArrayInputStream)6 URI (java.net.URI)6 NoContentException (javax.ws.rs.core.NoContentException)6 OutputStream (java.io.OutputStream)5 Map (java.util.Map)5 CompletableFuture (java.util.concurrent.CompletableFuture)5 EventSource (org.glassfish.jersey.media.sse.EventSource)5