javax.ws.rs.client.ResponseProcessingException Java Examples

The following examples show how to use javax.ws.rs.client.ResponseProcessingException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: WebClientBuilder.java    From peer-os with Apache License 2.0 6 votes vote down vote up
public static <T> T checkResponse( Response response, Class<T> clazz ) throws PeerException
{

    checkResponse( response, false );

    try
    {
        return response.readEntity( clazz );
    }
    catch ( ResponseProcessingException e )
    {
        throw new PeerException( "Error parsing response", e );
    }
    finally
    {
        close( response );
    }
}
 
Example #2
Source File: WebClientBuilder.java    From peer-os with Apache License 2.0 6 votes vote down vote up
static void checkResponse( Response response, boolean close ) throws PeerException
{
    try
    {
        if ( response == null )
        {
            throw new PeerException( "No response to parse" );
        }
        else if ( response.getStatus() == Response.Status.INTERNAL_SERVER_ERROR.getStatusCode() )
        {
            throw new PeerException( response.readEntity( String.class ) );
        }
    }
    catch ( ResponseProcessingException e )
    {
        throw new PeerException( "Error parsing response", e );
    }
    finally
    {
        if ( close )
        {
            close( response );
        }
    }
}
 
Example #3
Source File: AbstractClient.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected void checkClientException(Message outMessage, Exception ex) throws Exception {
    Throwable actualEx = ex instanceof Fault ? ((Fault)ex).getCause() : ex;

    Exchange exchange = outMessage.getExchange();
    Integer responseCode = getResponseCode(exchange);
    if (actualEx instanceof ResponseProcessingException) {
        throw (ResponseProcessingException)actualEx;
    } else if (responseCode == null
        || responseCode < 300 && !(actualEx instanceof IOException)
        || actualEx instanceof IOException && exchange.get("client.redirect.exception") != null) {
        if (actualEx instanceof ProcessingException) {
            throw (RuntimeException)actualEx;
        } else if (actualEx != null) {
            Object useProcExProp = exchange.get("wrap.in.processing.exception");
            if (actualEx instanceof RuntimeException
                && useProcExProp != null && PropertyUtils.isFalse(useProcExProp)) {
                throw (Exception)actualEx;
            }
            throw new ProcessingException(actualEx);
        } else if (!exchange.isOneWay() || cfg.isResponseExpectedForOneway()) {
            waitForResponseCode(exchange);
        }
    }
}
 
Example #4
Source File: JAXRSAsyncClientTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetBookResponseProcessingException() throws Exception {
    String address = "http://localhost:" + PORT + "/bookstore/books/123";
    List<Object> providers = new ArrayList<>();
    providers.add(new FaultyBookReader());
    WebClient wc = WebClient.create(address, providers);

    Future<Book> future = wc.async().get(Book.class);
    try {
        future.get();
        fail("Exception expected");
    } catch (ExecutionException ex) {
        assertTrue(ex.getCause() instanceof ResponseProcessingException);
    }
    wc.close();
}
 
Example #5
Source File: TenacityContainerExceptionMapperTest.java    From tenacity with Apache License 2.0 5 votes vote down vote up
@Test
public void exceptionsShouldMapTimeouts() throws AuthenticationException {
    Optional<Integer> responseStatus;
    try {
        final TenacityConfiguration timeoutConfiguration = new TenacityConfiguration();
        timeoutConfiguration.setExecutionIsolationThreadTimeoutInMillis(1);
        new TenacityPropertyRegister(
                ImmutableMap.of(DependencyKey.TENACITY_AUTH_TIMEOUT, timeoutConfiguration),
                new BreakerboxConfiguration())
                .register();

        when(mockAuthenticator.authenticate(anyString())).thenAnswer((invocation) -> {
            Thread.sleep(100);
            return Optional.empty();
        });

        final Response response = resources.client()
                .target("/")
                .request()
                .header(HttpHeaders.AUTHORIZATION, "Bearer TEST")
                .get(Response.class);
        responseStatus = Optional.of(response.getStatus());
    } catch (ResponseProcessingException err) {
        responseStatus = Optional.of(err.getResponse().getStatus());
    }
    assertThat(responseStatus).contains(statusCode);
}
 
Example #6
Source File: ClientResponseFilterTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test(expected = ResponseProcessingException.class)
public void testExceptionInClientResponseFilterWhenNotFound() {
    try (Response response = ClientBuilder.newClient()
         .register(FaultyClientResponseFilter.class)
         .target(ADDRESS)
         .request()
         .put(null)) {
        fail("Should not be invoked");
    }
}
 
Example #7
Source File: ClientResponseFilterTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test(expected = ResponseProcessingException.class)
public void testExceptionInClientResponseFilter() {
    try (Response response = ClientBuilder.newClient()
         .register(FaultyClientResponseFilter.class)
         .target(ADDRESS)
         .request()
         .get()) {
        fail("Should raise ResponseProcessingException");
    }
}
 
Example #8
Source File: ClientResponseFilterInterceptor.java    From cxf with Apache License 2.0 5 votes vote down vote up
public void handleMessage(Message inMessage) throws Fault {
    ClientProviderFactory pf = ClientProviderFactory.getInstance(inMessage);
    if (pf == null) {
        return;
    }

    List<ProviderInfo<ClientResponseFilter>> filters = pf.getClientResponseFilters();
    if (!filters.isEmpty()) {
        final ClientRequestContext reqContext = new ClientRequestContextImpl(
            inMessage.getExchange().getOutMessage(), true);
        final ResponseImpl response = (ResponseImpl)getResponse(inMessage);
        final ClientResponseContext respContext = new ClientResponseContextImpl(response, inMessage);
        for (ProviderInfo<ClientResponseFilter> filter : filters) {
            InjectionUtils.injectContexts(filter.getProvider(), filter, inMessage);
            try {
                filter.getProvider().filter(reqContext, respContext);
            } catch (RuntimeException | IOException ex) {
                // Complete the IN chain, if we won't set it, the AbstractClient::preProcessResult
                // would be stuck waiting for the IN chain completion.
                if (!inMessage.getExchange().isOneWay()) {
                    synchronized (inMessage.getExchange()) {
                        inMessage.getExchange().put("IN_CHAIN_COMPLETE", Boolean.TRUE);
                    }
                }
                
                // When a provider method throws an exception, the JAX-RS client runtime will map 
                // it to an instance of ResponseProcessingException if thrown while processing 
                // a response (4.5.2 Client Runtime).
                throw new ResponseProcessingException(response, ex);
            }
        }
    }
}
 
Example #9
Source File: ResponseImpl.java    From cxf with Apache License 2.0 5 votes vote down vote up
public void close() throws ProcessingException {
    if (!entityClosed) {
        if (!entityBufferred && entity instanceof InputStream) {
            try {
                ((InputStream)entity).close();
            } catch (IOException ex) {
                throw new ResponseProcessingException(this, ex);
            }
        }
        entity = null;
        entityClosed = true;
    }

}
 
Example #10
Source File: ResponseImpl.java    From cxf with Apache License 2.0 5 votes vote down vote up
public boolean bufferEntity() throws ProcessingException {
    checkEntityIsClosed();
    if (!entityBufferred && entity instanceof InputStream) {
        try {
            InputStream oldEntity = (InputStream)entity;
            entity = IOUtils.loadIntoBAIS(oldEntity);
            oldEntity.close();
            entityBufferred = true;
        } catch (IOException ex) {
            throw new ResponseProcessingException(this, ex);
        }
    }
    return entityBufferred;
}
 
Example #11
Source File: JAXRS20ClientServerBookTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test(expected = ResponseProcessingException.class)
public void testExceptionInClientResponseFilterWhenNotFound() {
    final String address = "http://localhost:" + PORT + "/bookstore/notFound";
    try (Response response = ClientBuilder.newClient()
         .register(FaultyClientResponseFilter.class)
         .target(address)
         .request("text/plain")
         .put(null)) {
        fail("Should not be invoked");
    }
}
 
Example #12
Source File: JAXRS20ClientServerBookTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test(expected = ResponseProcessingException.class)
public void testExceptionInClientResponseFilter() {
    final String address = "http://localhost:" + PORT + "/bookstore/books/wildcard";
    try (Response response = ClientBuilder.newClient()
         .register(FaultyClientResponseFilter.class)
         .target(address)
         .request("text/plain")
         .get()) {
        fail("Should raise ResponseProcessingException");
    }
}
 
Example #13
Source File: AuthorizationGrantNegativeTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testNonMatchingClientIdIgnored() throws Exception {
    URL busFile = AuthorizationGrantTest.class.getResource("client.xml");

    String address = "https://localhost:" + port + "/services/";
    WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                                        "alice", "security", busFile.toString());
    // Save the Cookie for the second request...
    WebClient.getConfig(client).getRequestContext().put(
        org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);

    // Get Authorization Code
    String code = OAuth2TestUtils.getAuthorizationCode(client);
    assertNotNull(code);

    // Now get the access token using a different client id
    client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                              "consumer-id", "this-is-a-secret", busFile.toString());
    // Save the Cookie for the second request...
    WebClient.getConfig(client).getRequestContext().put(
        org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);

    client.type("application/x-www-form-urlencoded").accept("application/json");
    client.path("token");

    Form form = new Form();
    form.param("grant_type", "authorization_code");
    form.param("code", code);
    form.param("client_id", "consumer-id-aud");

    // Now try to get a token
    Response response = client.post(form);
    try {
        response.readEntity(ClientAccessToken.class);
        fail("Failure expected on trying to get a token");
    } catch (ResponseProcessingException ex) {
        //expected
    }
}
 
Example #14
Source File: AuthorizationGrantNegativeTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testNonMatchingClientIdBasicAuth() throws Exception {
    URL busFile = AuthorizationGrantTest.class.getResource("client.xml");

    String address = "https://localhost:" + port + "/services/";
    WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                                        "alice", "security", busFile.toString());
    // Save the Cookie for the second request...
    WebClient.getConfig(client).getRequestContext().put(
        org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);

    // Get Authorization Code
    String code = OAuth2TestUtils.getAuthorizationCode(client);
    assertNotNull(code);

    // Now get the access token using a different client id
    client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                              "consumer-id-aud", "this-is-a-secret", busFile.toString());
    // Save the Cookie for the second request...
    WebClient.getConfig(client).getRequestContext().put(
        org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);

    client.type("application/x-www-form-urlencoded").accept("application/json");
    client.path("token");

    Form form = new Form();
    form.param("grant_type", "authorization_code");
    form.param("code", code);

    // Now try to get a token
    Response response = client.post(form);
    try {
        response.readEntity(ClientAccessToken.class);
        fail("Failure expected on trying to get a token");
    } catch (ResponseProcessingException ex) {
        //expected
    }
}
 
Example #15
Source File: AuthorizationGrantNegativeTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testNonMatchingClientId() throws Exception {
    URL busFile = AuthorizationGrantTest.class.getResource("client.xml");

    String address = "https://localhost:" + port + "/services/";
    WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                                        "alice", "security", busFile.toString());
    // Save the Cookie for the second request...
    WebClient.getConfig(client).getRequestContext().put(
        org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);

    // Get Authorization Code
    String code = OAuth2TestUtils.getAuthorizationCode(client);
    assertNotNull(code);

    // Now get the access token using a different client id
    client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                              "consumer-id-aud", "this-is-a-secret", busFile.toString());
    // Save the Cookie for the second request...
    WebClient.getConfig(client).getRequestContext().put(
        org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);

    client.type("application/x-www-form-urlencoded").accept("application/json");
    client.path("token");

    Form form = new Form();
    form.param("grant_type", "authorization_code");
    form.param("code", code);
    form.param("client_id", "consumer-id-aud");

    // Now try to get a token
    Response response = client.post(form);
    try {
        response.readEntity(ClientAccessToken.class);
        fail("Failure expected on trying to get a token");
    } catch (ResponseProcessingException ex) {
        //expected
    }
}
 
Example #16
Source File: AuthorizationGrantNegativeTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testNonMatchingClientDifferentClientIds() throws Exception {
    URL busFile = AuthorizationGrantTest.class.getResource("client.xml");

    String address = "https://localhost:" + port + "/services/";
    WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                                        "alice", "security", busFile.toString());
    // Save the Cookie for the second request...
    WebClient.getConfig(client).getRequestContext().put(
        org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);

    // Get Authorization Code
    String code = OAuth2TestUtils.getAuthorizationCode(client);
    assertNotNull(code);

    // Now get the access token using a different client id
    client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                              "consumer-id-aud", "this-is-a-secret", busFile.toString());
    // Save the Cookie for the second request...
    WebClient.getConfig(client).getRequestContext().put(
        org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);

    client.type("application/x-www-form-urlencoded").accept("application/json");
    client.path("token");

    Form form = new Form();
    form.param("grant_type", "authorization_code");
    form.param("code", code);
    form.param("client_id", "consumer-id");

    // Now try to get a token
    Response response = client.post(form);
    try {
        response.readEntity(ClientAccessToken.class);
        fail("Failure expected on trying to get a token");
    } catch (ResponseProcessingException ex) {
        //expected
    }
}
 
Example #17
Source File: WebhooksServlet.java    From jam-collaboration-sample with Apache License 2.0 5 votes vote down vote up
/**
 * This method encapsulates a basic way of making most POST calls to the Jam OData API under the JSON format.
 * 
 * @param oDataPath API end point to call
 * @param payload a JSON request body
 */
private void postToOData(final String oDataPath, final String payload) {
    System.out.printf("Making Jam OData POST call to %s with payload: %n%s", oDataPath, payload);

    httpClient
        .target(JAM_BASE_URL)
        .path("/api/v1/OData/" + oDataPath)
        .queryParam("$format", "json")
        .request(MediaType.APPLICATION_JSON)
        .header("Authorization", "Bearer " + JAM_OAUTH_TOKEN)
        .header("Content-Type", MediaType.APPLICATION_JSON)
        .header("Accept", MediaType.APPLICATION_JSON)
        .async()
        .post(Entity.json(payload), new InvocationCallback<String>() {

            @Override
            public void completed(final String response) {
                System.out.println("Received response: " + response);
            }

            @Override
            public void failed(final Throwable throwable) {
                final ResponseProcessingException exception = (ResponseProcessingException)throwable;
                final String responseString = exception.getResponse().readEntity(String.class);
                System.out.println("Received error response: " + responseString);
                throwable.printStackTrace();
            }
        });
}
 
Example #18
Source File: DefaultDockerClient.java    From docker-client with Apache License 2.0 5 votes vote down vote up
private RuntimeException propagate(final String method, final WebTarget resource,
                                   final Exception ex)
    throws DockerException, InterruptedException {
  Throwable cause = ex.getCause();

  // Sometimes e is a org.glassfish.hk2.api.MultiException
  // which contains the cause we're actually interested in.
  // So we unpack it here.
  if (ex instanceof MultiException) {
    cause = cause.getCause();
  }

  Response response = null;
  if (cause instanceof ResponseProcessingException) {
    response = ((ResponseProcessingException) cause).getResponse();
  } else if (cause instanceof WebApplicationException) {
    response = ((WebApplicationException) cause).getResponse();
  } else if ((cause instanceof ProcessingException) && (cause.getCause() != null)) {
    // For a ProcessingException, The exception message or nested Throwable cause SHOULD contain
    // additional information about the reason of the processing failure.
    cause = cause.getCause();
  }

  if (response != null) {
    throw new DockerRequestException(method, resource.getUri(), response.getStatus(),
                                     message(response), cause);
  } else if ((cause instanceof SocketTimeoutException)
             || (cause instanceof ConnectTimeoutException)) {
    throw new DockerTimeoutException(method, resource.getUri(), ex);
  } else if ((cause instanceof InterruptedIOException)
             || (cause instanceof InterruptedException)) {
    throw new InterruptedException("Interrupted: " + method + " " + resource);
  } else {
    throw new DockerException(ex);
  }
}
 
Example #19
Source File: AuthorizationGrantNegativeTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testNonMatchingRedirectURI() throws Exception {
    URL busFile = AuthorizationGrantTest.class.getResource("client.xml");

    String address = "https://localhost:" + port + "/services/";
    WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                                        "alice", "security", busFile.toString());
    // Save the Cookie for the second request...
    WebClient.getConfig(client).getRequestContext().put(
        org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);

    // Get Authorization Code
    String code = OAuth2TestUtils.getAuthorizationCode(client);
    assertNotNull(code);

    // Now get the access token
    client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                              "consumer-id", "this-is-a-secret", busFile.toString());
    // Save the Cookie for the second request...
    WebClient.getConfig(client).getRequestContext().put(
        org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);

    client.type("application/x-www-form-urlencoded").accept("application/json");
    client.path("token");

    Form form = new Form();
    form.param("grant_type", "authorization_code");
    form.param("code", code);
    form.param("client_id", "consumer-id");
    form.param("redirect_uri", "http://www.bad.blah.apache.org");
    Response response = client.post(form);
    try {
        response.readEntity(ClientAccessToken.class);
        fail("Failure expected on not sending the correct redirect URI");
    } catch (ResponseProcessingException ex) {
        //expected
    }
}
 
Example #20
Source File: SkippableTest.java    From robozonky with Apache License 2.0 4 votes vote down vote up
@Test
void unavailable() {
    final Instant now = Instant.now();
    setClock(Clock.fixed(now, Defaults.ZONE_ID));
    final Runnable r = mock(Runnable.class);
    doThrow(new ClientErrorException(Response.Status.TOO_MANY_REQUESTS)).when(r)
        .run();
    final PowerTenant t = new TenantBuilder()
        .withApi(new ApiProvider(null))
        .withSecrets(SecretProvider.inMemory("[email protected]"))
        .build(false);
    final Skippable s = new Skippable(r, t);
    logger.debug("First run.");
    s.run();
    verify(r, times(1)).run();
    assertThat(t.getAvailability()
        .isAvailable()).isFalse();
    // move one second, make sure it checks again
    final int mandatoryDelay = 60;
    setClock(Clock.fixed(now.plus(Duration.ofSeconds(mandatoryDelay + 1)), Defaults.ZONE_ID));
    logger.debug("Second run.");
    doThrow(ServerErrorException.class).when(r)
        .run();
    s.run();
    verify(r, times(2)).run();
    assertThat(t.getAvailability()
        .isAvailable()).isFalse();
    // but it failed again, exponential backoff in effect
    setClock(Clock.fixed(now.plus(Duration.ofSeconds(mandatoryDelay + 2)), Defaults.ZONE_ID));
    logger.debug("Third run.");
    doThrow(ResponseProcessingException.class).when(r)
        .run();
    s.run();
    verify(r, times(3)).run();
    assertThat(t.getAvailability()
        .isAvailable()).isFalse();
    setClock(Clock.fixed(now.plus(Duration.ofSeconds(mandatoryDelay + 3)), Defaults.ZONE_ID));
    logger.debug("Fourth run.");
    doNothing().when(r)
        .run();
    s.run();
    verify(r, times(3)).run(); // not run as we're in the exponential backoff
    assertThat(t.getAvailability()
        .isAvailable()).isFalse();
    setClock(Clock.fixed(now.plus(Duration.ofSeconds(mandatoryDelay + 4)), Defaults.ZONE_ID));
    logger.debug("Fourth run.");
    s.run();
    verify(r, times(4)).run(); // it was run now
    assertThat(t.getAvailability()
        .isAvailable()).isTrue();
}
 
Example #21
Source File: AvailabilityImplTest.java    From robozonky with Apache License 2.0 4 votes vote down vote up
@Test
void scalingUnavailability() {
    final Availability a = new AvailabilityImpl(s);
    final Instant now = Instant.now();
    setClock(Clock.fixed(now, Defaults.ZONE_ID));
    final Response r = Response.ok()
        .build();
    final boolean reg = a.registerException(new ResponseProcessingException(r, UUID.randomUUID()
        .toString()));
    assertSoftly(softly -> {
        softly.assertThat(reg)
            .isTrue();
        softly.assertThat(a.isAvailable())
            .isFalse();
        softly.assertThat(a.nextAvailabilityCheck())
            .isEqualTo(now.plus(Duration.ofSeconds(MANDATORY_DELAY_IN_SECONDS + 1)));
    });
    final boolean reg2 = a.registerException(new ClientErrorException(429));
    assertSoftly(softly -> {
        softly.assertThat(reg2)
            .isFalse();
        softly.assertThat(a.isAvailable())
            .isFalse();
        softly.assertThat(a.nextAvailabilityCheck())
            .isEqualTo(now.plus(Duration.ofSeconds(MANDATORY_DELAY_IN_SECONDS + 2)));
    });
    final boolean reg3 = a.registerException(new ServerErrorException(503));
    assertSoftly(softly -> {
        softly.assertThat(reg3)
            .isFalse();
        softly.assertThat(a.isAvailable())
            .isFalse();
        softly.assertThat(a.nextAvailabilityCheck())
            .isEqualTo(now.plus(Duration.ofSeconds(MANDATORY_DELAY_IN_SECONDS + 4)));
    });
    final Optional<Instant> success = a.registerSuccess();
    assertSoftly(softly -> {
        softly.assertThat(success)
            .isPresent();
        softly.assertThat(a.isAvailable())
            .isTrue();
        softly.assertThat(a.nextAvailabilityCheck())
            .isEqualTo(now);
    });
}
 
Example #22
Source File: OIDCNegativeTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testJWTRequestNonmatchingResponseType() throws Exception {
    URL busFile = OIDCNegativeTest.class.getResource("client.xml");

    String address = "https://localhost:" + port + "/unsignedjwtservices/";
    WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                                        "alice", "security", busFile.toString());
    // Save the Cookie for the second request...
    WebClient.getConfig(client).getRequestContext().put(
        org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);

    JwtClaims claims = new JwtClaims();
    claims.setIssuer("consumer-id");
    claims.setIssuedAt(Instant.now().getEpochSecond());
    claims.setAudiences(
        Collections.singletonList("https://localhost:" + port + "/unsignedjwtservices/"));
    claims.setProperty("response_type", "token");

    JwsHeaders headers = new JwsHeaders();
    headers.setAlgorithm("none");

    JwtToken token = new JwtToken(headers, claims);

    JwsJwtCompactProducer jws = new JwsJwtCompactProducer(token);
    String request = jws.getSignedEncodedJws();

    AuthorizationCodeParameters parameters = new AuthorizationCodeParameters();
    parameters.setConsumerId("consumer-id");
    parameters.setScope("openid");
    parameters.setResponseType("code");
    parameters.setPath("authorize/");
    parameters.setRequest(request);

    // Get Authorization Code
    try {
        OAuth2TestUtils.getLocation(client, parameters);
        fail("Failure expected on a non-matching response_type");
    } catch (ResponseProcessingException ex) {
        // expected
    }
}
 
Example #23
Source File: OAuthClientUtils.java    From cxf with Apache License 2.0 4 votes vote down vote up
/**
 * Obtains the access token from OAuth AccessToken Service
 * using the initialized web client
 * @param accessTokenService the AccessToken client
 * @param consumer {@link Consumer} representing the registered client.
 * @param grant {@link AccessTokenGrant} grant
 * @param extraParams extra parameters
 * @param defaultTokenType default expected token type - some early
 *        well-known OAuth2 services do not return a required token_type parameter
 * @param setAuthorizationHeader if set to true then HTTP Basic scheme
 *           will be used to pass client id and secret, otherwise they will
 *           be passed in the form payload
 * @return {@link ClientAccessToken} access token
 * @throws OAuthServiceException
 */
public static ClientAccessToken getAccessToken(WebClient accessTokenService,
                                               Consumer consumer,
                                               AccessTokenGrant grant,
                                               Map<String, String> extraParams,
                                               String defaultTokenType,
                                               boolean setAuthorizationHeader)
    throws OAuthServiceException {

    if (accessTokenService == null) {
        throw new OAuthServiceException(OAuthConstants.SERVER_ERROR);
    }

    Form form = new Form(grant.toMap());
    if (extraParams != null) {
        for (Map.Entry<String, String> entry : extraParams.entrySet()) {
            form.param(entry.getKey(), entry.getValue());
        }
    }
    if (consumer != null) {
        boolean secretAvailable = !StringUtils.isEmpty(consumer.getClientSecret());
        if (setAuthorizationHeader && secretAvailable) {
            accessTokenService.replaceHeader(HttpHeaders.AUTHORIZATION,
                DefaultBasicAuthSupplier.getBasicAuthHeader(consumer.getClientId(), consumer.getClientSecret()));
        } else {
            form.param(OAuthConstants.CLIENT_ID, consumer.getClientId());
            if (secretAvailable) {
                form.param(OAuthConstants.CLIENT_SECRET, consumer.getClientSecret());
            }
        }
    } else {
        // in this case the AccessToken service is expected to find a mapping between
        // the authenticated credentials and the client registration id
    }
    Response response = accessTokenService.form(form);
    final Map<String, String> map;
    try {
        map = response.getMediaType() == null
                || response.getMediaType().isCompatible(MediaType.APPLICATION_JSON_TYPE)
                        ? new OAuthJSONProvider().readJSONResponse((InputStream) response.getEntity())
                        : Collections.emptyMap();
    } catch (Exception ex) {
        throw new ResponseProcessingException(response, ex);
    }
    if (200 == response.getStatus()) {
        ClientAccessToken token = fromMapToClientToken(map, defaultTokenType);
        if (token == null) {
            throw new OAuthServiceException(OAuthConstants.SERVER_ERROR);
        }
        return token;
    } else if (response.getStatus() >= 400 && map.containsKey(OAuthConstants.ERROR_KEY)) {
        OAuthError error = new OAuthError(map.get(OAuthConstants.ERROR_KEY),
                                          map.get(OAuthConstants.ERROR_DESCRIPTION_KEY));
        error.setErrorUri(map.get(OAuthConstants.ERROR_URI_KEY));
        throw new OAuthServiceException(error);
    }
    throw new OAuthServiceException(OAuthConstants.SERVER_ERROR);
}
 
Example #24
Source File: OIDCNegativeTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testJWTRequestNonmatchingClientId() throws Exception {
    URL busFile = OIDCNegativeTest.class.getResource("client.xml");

    String address = "https://localhost:" + port + "/unsignedjwtservices/";
    WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                                        "alice", "security", busFile.toString());
    // Save the Cookie for the second request...
    WebClient.getConfig(client).getRequestContext().put(
        org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);

    JwtClaims claims = new JwtClaims();
    claims.setIssuer("consumer-id");
    claims.setIssuedAt(Instant.now().getEpochSecond());
    claims.setAudiences(
        Collections.singletonList("https://localhost:" + port + "/unsignedjwtservices/"));
    claims.setProperty("client_id", "consumer-id2");

    JwsHeaders headers = new JwsHeaders();
    headers.setAlgorithm("none");

    JwtToken token = new JwtToken(headers, claims);

    JwsJwtCompactProducer jws = new JwsJwtCompactProducer(token);
    String request = jws.getSignedEncodedJws();

    AuthorizationCodeParameters parameters = new AuthorizationCodeParameters();
    parameters.setConsumerId("consumer-id");
    parameters.setScope("openid");
    parameters.setResponseType("code");
    parameters.setPath("authorize/");
    parameters.setRequest(request);

    // Get Authorization Code
    try {
        OAuth2TestUtils.getLocation(client, parameters);
        fail("Failure expected on a non-matching client id");
    } catch (ResponseProcessingException ex) {
        // expected
    }
}
 
Example #25
Source File: ResponseImpl.java    From cxf with Apache License 2.0 4 votes vote down vote up
private void reportMessageHandlerProblem(String name, Class<?> cls, MediaType ct, Throwable cause) {
    String errorMessage = JAXRSUtils.logMessageHandlerProblem(name, cls, ct);
    throw new ResponseProcessingException(this, errorMessage, cause);
}
 
Example #26
Source File: JAXRSClientServerBookTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Test(expected = ResponseProcessingException.class)
public void testEmptyResponseProxy() {
    BookStore store = JAXRSClientFactory.create("http://localhost:" + PORT, BookStore.class);
    WebClient.getConfig(store).getInInterceptors().add(new BookServer.ReplaceStatusInterceptor());
    store.getEmptyBook();
}
 
Example #27
Source File: JAXRSClientServerBookTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Test(expected = ResponseProcessingException.class)
public void testEmptyJAXB() {
    doTestEmptyResponse("application/xml");
}
 
Example #28
Source File: JAXRSClientServerBookTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Test(expected = ResponseProcessingException.class)
public void testEmptyJSON() {
    doTestEmptyResponse("application/json");
}
 
Example #29
Source File: AuthorizationGrantNegativeTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testRepeatAuthorizationCode() throws Exception {
    URL busFile = AuthorizationGrantTest.class.getResource("client.xml");

    String address = "https://localhost:" + port + "/services/";
    WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                                        "alice", "security", busFile.toString());
    // Save the Cookie for the second request...
    WebClient.getConfig(client).getRequestContext().put(
        org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);

    // Get Authorization Code
    String code = OAuth2TestUtils.getAuthorizationCode(client);
    assertNotNull(code);

    // Now get the access token
    client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                              "consumer-id", "this-is-a-secret", busFile.toString());
    // Save the Cookie for the second request...
    WebClient.getConfig(client).getRequestContext().put(
        org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);

    client.type("application/x-www-form-urlencoded").accept("application/json");
    client.path("token");

    // First invocation
    Form form = new Form();
    form.param("grant_type", "authorization_code");
    form.param("code", code);
    form.param("client_id", "consumer-id");
    Response response = client.post(form);
    ClientAccessToken token = response.readEntity(ClientAccessToken.class);
    assertNotNull(token.getTokenKey());

    // Now try to get a second token
    response = client.post(form);
    try {
        response.readEntity(ClientAccessToken.class);
        fail("Failure expected on trying to get a second access token");
    } catch (ResponseProcessingException ex) {
        //expected
    }
}
 
Example #30
Source File: AuthorizationGrantNegativeTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testRepeatRefreshCall() throws Exception {
    URL busFile = AuthorizationGrantTest.class.getResource("client.xml");

    String address = "https://localhost:" + port + "/services/";
    WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                                        "alice", "security", busFile.toString());
    // Save the Cookie for the second request...
    WebClient.getConfig(client).getRequestContext().put(
        org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);

    // Get Authorization Code
    String code = OAuth2TestUtils.getAuthorizationCode(client, "read_balance");
    assertNotNull(code);

    // Now get the access token
    client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                              "consumer-id", "this-is-a-secret", busFile.toString());
    // Save the Cookie for the second request...
    WebClient.getConfig(client).getRequestContext().put(
        org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);

    ClientAccessToken accessToken =
        OAuth2TestUtils.getAccessTokenWithAuthorizationCode(client, code);
    assertNotNull(accessToken.getTokenKey());
    assertNotNull(accessToken.getRefreshToken());

    // Refresh the access token
    client.type("application/x-www-form-urlencoded").accept("application/json");

    Form form = new Form();
    form.param("grant_type", "refresh_token");
    form.param("refresh_token", accessToken.getRefreshToken());
    form.param("client_id", "consumer-id");
    form.param("scope", "read_balance");
    Response response = client.post(form);

    accessToken = response.readEntity(ClientAccessToken.class);
    assertNotNull(accessToken.getTokenKey());
    assertNotNull(accessToken.getRefreshToken());

    // Now try to refresh it again
    try {
        response = client.post(form);
        response.readEntity(ClientAccessToken.class);
        fail("Failure expected on trying to reuse a refresh token");
    } catch (ResponseProcessingException ex) {
        //expected
    }
}