Search in sources :

Example 21 with WebTarget

use of javax.ws.rs.client.WebTarget in project jersey by jersey.

the class NoEntityTest method testGetWithClose.

@Test
public void testGetWithClose() {
    WebTarget r = target("test");
    for (int i = 0; i < 5; i++) {
        Response cr = r.request().get();
        cr.close();
    }
}
Also used : Response(javax.ws.rs.core.Response) WebTarget(javax.ws.rs.client.WebTarget) JerseyTest(org.glassfish.jersey.test.JerseyTest) Test(org.junit.Test)

Example 22 with WebTarget

use of javax.ws.rs.client.WebTarget in project jersey by jersey.

the class ParallelTest method testParallel.

@Test
public void testParallel() throws BrokenBarrierException, InterruptedException, TimeoutException {
    final ScheduledExecutorService executor = Executors.newScheduledThreadPool(PARALLEL_CLIENTS);
    try {
        final WebTarget target = target();
        for (int i = 1; i <= PARALLEL_CLIENTS; i++) {
            final int id = i;
            executor.submit(new Runnable() {

                @Override
                public void run() {
                    try {
                        startBarrier.await();
                        Response response;
                        response = target.path(PATH).request().get();
                        assertEquals("GET", response.readEntity(String.class));
                        receivedCounter.incrementAndGet();
                    } catch (InterruptedException ex) {
                        Thread.currentThread().interrupt();
                        LOGGER.log(Level.WARNING, "Client thread " + id + " interrupted.", ex);
                    } catch (BrokenBarrierException ex) {
                        LOGGER.log(Level.INFO, "Client thread " + id + " failed on broken barrier.", ex);
                    } catch (Throwable t) {
                        t.printStackTrace();
                        LOGGER.log(Level.WARNING, "Client thread " + id + " failed on unexpected exception.", t);
                    } finally {
                        doneLatch.countDown();
                    }
                }
            });
        }
        startBarrier.await(1, TimeUnit.SECONDS);
        assertTrue("Waiting for clients to finish has timed out.", doneLatch.await(5 * getAsyncTimeoutMultiplier(), TimeUnit.SECONDS));
        assertEquals("Resource counter", PARALLEL_CLIENTS, resourceCounter.get());
        assertEquals("Received counter", PARALLEL_CLIENTS, receivedCounter.get());
    } finally {
        executor.shutdownNow();
        Assert.assertTrue("Executor termination", executor.awaitTermination(5, TimeUnit.SECONDS));
    }
}
Also used : Response(javax.ws.rs.core.Response) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) BrokenBarrierException(java.util.concurrent.BrokenBarrierException) WebTarget(javax.ws.rs.client.WebTarget) Test(org.junit.Test) JerseyTest(org.glassfish.jersey.test.JerseyTest)

Example 23 with WebTarget

use of javax.ws.rs.client.WebTarget in project jersey by jersey.

the class HttpAuthenticationFilter method repeatRequest.

/**
     * Repeat the {@code request} with provided {@code newAuthorizationHeader}
     * and update the {@code response} with newest response data.
     *
     * @param request                Request context.
     * @param response               Response context (will be updated with the new response data).
     * @param newAuthorizationHeader {@code Authorization} header that should be added to the new request.
     * @return {@code true} is the authentication was successful ({@code true} if 401 response code was not returned;
     * {@code false} otherwise).
     */
static boolean repeatRequest(ClientRequestContext request, ClientResponseContext response, String newAuthorizationHeader) {
    Client client = request.getClient();
    String method = request.getMethod();
    MediaType mediaType = request.getMediaType();
    URI lUri = request.getUri();
    WebTarget resourceTarget = client.target(lUri);
    Invocation.Builder builder = resourceTarget.request(mediaType);
    MultivaluedMap<String, Object> newHeaders = new MultivaluedHashMap<String, Object>();
    for (Map.Entry<String, List<Object>> entry : request.getHeaders().entrySet()) {
        if (HttpHeaders.AUTHORIZATION.equals(entry.getKey())) {
            continue;
        }
        newHeaders.put(entry.getKey(), entry.getValue());
    }
    newHeaders.add(HttpHeaders.AUTHORIZATION, newAuthorizationHeader);
    builder.headers(newHeaders);
    builder.property(REQUEST_PROPERTY_FILTER_REUSED, "true");
    Invocation invocation;
    if (request.getEntity() == null) {
        invocation = builder.build(method);
    } else {
        invocation = builder.build(method, Entity.entity(request.getEntity(), request.getMediaType()));
    }
    Response nextResponse = invocation.invoke();
    if (nextResponse.hasEntity()) {
        response.setEntityStream(nextResponse.readEntity(InputStream.class));
    }
    MultivaluedMap<String, String> headers = response.getHeaders();
    headers.clear();
    headers.putAll(nextResponse.getStringHeaders());
    response.setStatus(nextResponse.getStatus());
    return response.getStatus() != Response.Status.UNAUTHORIZED.getStatusCode();
}
Also used : Invocation(javax.ws.rs.client.Invocation) InputStream(java.io.InputStream) URI(java.net.URI) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) Response(javax.ws.rs.core.Response) MediaType(javax.ws.rs.core.MediaType) List(java.util.List) WebTarget(javax.ws.rs.client.WebTarget) Client(javax.ws.rs.client.Client) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) MultivaluedMap(javax.ws.rs.core.MultivaluedMap)

Example 24 with WebTarget

use of javax.ws.rs.client.WebTarget in project jersey by jersey.

the class CustomConnectorTest method testConnectorProviderPreservedOnClientConfigCopy.

/**
     * Reproducer for JERSEY-2318.
     *
     * The test verifies that the {@link org.glassfish.jersey.client.spi.ConnectorProvider} configured
     * on one client instance is transferred to another client instance when the new client instance is
     * created from the original client instance configuration.
     */
@Test
public void testConnectorProviderPreservedOnClientConfigCopy() {
    final ClientConfig clientConfig = new ClientConfig().connectorProvider(new TestConnectorProvider());
    final Client client = ClientBuilder.newClient(clientConfig);
    try {
        Response response;
        final WebTarget target = client.target("http://wherever.org/");
        response = target.request().get();
        // let's first verify we are using the test loop-back connector.
        assertThat(response.getStatus(), equalTo(TestConnector.TEST_LOOPBACK_CODE));
        assertThat(response.readEntity(String.class), equalTo("http://wherever.org/"));
        // and now with the filter...
        target.register(TestClientFilter.class);
        response = target.request().get();
        // check if the connector provider has been propagated:
        assertThat(response.getStatus(), equalTo(TestConnector.TEST_LOOPBACK_CODE));
        // check if the filter has been invoked:
        assertThat(response.readEntity(String.class), equalTo("http://wherever.org/filtered"));
    } finally {
        client.close();
    }
}
Also used : Response(javax.ws.rs.core.Response) WebTarget(javax.ws.rs.client.WebTarget) Client(javax.ws.rs.client.Client) Test(org.junit.Test)

Example 25 with WebTarget

use of javax.ws.rs.client.WebTarget in project jersey by jersey.

the class JerseyWebTargetTest method testRemoveMatrixParams.

@Test
public void testRemoveMatrixParams() {
    WebTarget wt = target;
    wt = wt.matrixParam("matrix1", "segment1");
    wt = wt.path("path1");
    wt = wt.matrixParam("matrix2", "segment1");
    wt = wt.matrixParam("matrix2", new Object[] { null });
    wt = wt.path("path2");
    wt = wt.matrixParam("matrix1", "segment1");
    wt = wt.matrixParam("matrix1", new Object[] { null });
    wt = wt.path("path3");
    URI uri = wt.getUri();
    assertEquals("/;matrix1=segment1/path1/path2/path3", uri.toString());
}
Also used : WebTarget(javax.ws.rs.client.WebTarget) URI(java.net.URI) Test(org.junit.Test)

Aggregations

WebTarget (javax.ws.rs.client.WebTarget)591 Test (org.junit.Test)489 JerseyTest (org.glassfish.jersey.test.JerseyTest)297 Response (javax.ws.rs.core.Response)278 Client (javax.ws.rs.client.Client)98 ClientConfig (org.glassfish.jersey.client.ClientConfig)45 GenericType (javax.ws.rs.core.GenericType)35 CoreMatchers.containsString (org.hamcrest.CoreMatchers.containsString)25 CountDownLatch (java.util.concurrent.CountDownLatch)24 List (java.util.List)23 InputStream (java.io.InputStream)22 IOException (java.io.IOException)21 ArrayList (java.util.ArrayList)21 ProcessingException (javax.ws.rs.ProcessingException)19 URI (java.net.URI)18 Properties (java.util.Properties)18 TestProperties (org.glassfish.jersey.test.TestProperties)18 MediaType (javax.ws.rs.core.MediaType)15 Invocation (javax.ws.rs.client.Invocation)13 ResourceConfig (org.glassfish.jersey.server.ResourceConfig)13