Java Code Examples for javax.ws.rs.core.Response#getMediaType()

The following examples show how to use javax.ws.rs.core.Response#getMediaType() . 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: JsonApiResponseFilterTestBase.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
@Test
public void testNullResponse() {
    // GIVEN
    // mapping of null responses to JSON-API disabled
    Assume.assumeFalse(enableNullResponse);

    // WHEN
    Response response = get("/repositoryActionWithNullResponse", null);

    // THEN
    Assert.assertNotNull(response);
    assertThat(response.getStatus())
            .describedAs("Status code")
            .isEqualTo(Response.Status.NO_CONTENT.getStatusCode());
    MediaType mediaType = response.getMediaType();
    assertThat(mediaType)
            .describedAs("Media-Type")
            .isEqualTo(null);
}
 
Example 2
Source File: JsonApiResponseFilterTestBase.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
@Test
public void testNonInterfaceMethodWithNullResponseJsonApi() {
    // GIVEN
    // mapping of null responses to JSON-API disabled
    Assume.assumeFalse(enableNullResponse);

    // WHEN
    Response response = get("/nonInterfaceMethodWithNullResponseJsonApi", null);

    // THEN
    Assert.assertNotNull(response);
    assertThat(response.getStatus())
            .describedAs("Status code")
            .isEqualTo(Response.Status.NO_CONTENT.getStatusCode());
    MediaType mediaType = response.getMediaType();
    assertThat(mediaType)
            .describedAs("Media-Type")
            .isEqualTo(null);
}
 
Example 3
Source File: JsonApiResponseFilterTestBase.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
@Test
public void testNonInterfaceMethodWithNullResponseJsonApiWrapped() {
    // GIVEN
    // mapping of null responses to JSON-API enabled
    Assume.assumeTrue(enableNullResponse);

    // WHEN
    Response response = get("/nonInterfaceMethodWithNullResponseJsonApi", null);

    // THEN
    Assert.assertNotNull(response);
    assertThat(response.getStatus())
            .describedAs("Status code")
            .isEqualTo(Response.Status.OK.getStatusCode());

    MediaType mediaType = response.getMediaType();
    assertThat(mediaType)
            .describedAs("Media-Type")
            .isEqualTo(JsonApiMediaType.APPLICATION_JSON_API_TYPE);
    String schedule = response.readEntity(String.class);
    assertThat(schedule)
            .describedAs("Response content")
            .isEqualTo("{\"data\":null}");
}
 
Example 4
Source File: JsonApiResponseFilterTestBase.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
@Test
public void testStringResponse() {
    // GIVEN
    Map<String, String> queryParams = new HashMap<>();
    queryParams.put("msg", "msg");

    // WHEN
    Response response = get("/repositoryAction", queryParams);

    // THEN
    Assert.assertNotNull(response);
    assertThat(response.getStatus())
            .describedAs("Status code")
            .isEqualTo(Response.Status.OK.getStatusCode());

    MediaType mediaType = response.getMediaType();
    assertThat(mediaType)
            .describedAs("Media-Type")
            .isEqualTo(MediaType.TEXT_HTML_TYPE);
    String entity = response.readEntity(String.class);
    assertThat(entity)
            .describedAs("Response content")
            .isEqualTo("repository action: msg");
}
 
Example 5
Source File: JsonApiResponseFilterTestBase.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
@Test
public void testStringResponseWrapped() {
    // GIVEN
    Map<String, String> queryParams = new HashMap<>();
    queryParams.put("msg", "msg");

    // WHEN
    Response response = get("/repositoryActionJsonApi", queryParams);

    // THEN
    Assert.assertNotNull(response);
    assertThat(response.getStatus())
            .describedAs("Status code")
            .isEqualTo(Response.Status.OK.getStatusCode());

    MediaType mediaType = response.getMediaType();
    assertThat(mediaType)
            .describedAs("Media-Type")
            .isEqualTo(JsonApiMediaType.APPLICATION_JSON_API_TYPE);
    String entity = response.readEntity(String.class);
    assertThat(entity)
            .describedAs("Response content")
            .isEqualTo("{\"data\":\"repository action: msg\"}");
}
 
Example 6
Source File: JsonApiResponseFilterTestBase.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
@Test
public void testErrorResponse() {
    // GIVEN

    // WHEN
    Response response = get("/repositoryActionWithException", null);

    // THEN
    Assert.assertNotNull(response);
    assertThat(response.getStatus())
            .describedAs("Status code")
            .isEqualTo(Response.Status.FORBIDDEN.getStatusCode());

    MediaType mediaType = response.getMediaType();
    assertThat(mediaType)
            .describedAs("Media-Type")
            .isEqualTo(JsonApiMediaType.APPLICATION_JSON_API_TYPE);
    String error = response.readEntity(String.class);
    assertThat(error)
            .describedAs("Response content")
            .startsWith("{\"errors\":");
}
 
Example 7
Source File: JsonApiResponseFilterTestBase.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
@Test
public void testJsonApiResourceResponse() {
    // GIVEN

    // WHEN
    Response response = get("/repositoryActionWithResourceResult", null);

    // THEN
    Assert.assertNotNull(response);
    assertThat(response.getStatus())
            .describedAs("Status code")
            .isEqualTo(Response.Status.OK.getStatusCode());

    MediaType mediaType = response.getMediaType();
    assertThat(mediaType)
            .describedAs("Media-Type")
            .isEqualTo(JsonApiMediaType.APPLICATION_JSON_API_TYPE);
    String schedule = response.readEntity(String.class);
    assertThat(schedule)
            .describedAs("Response content")
            .startsWith("{\"data\":").contains("\"links\":{");
}
 
Example 8
Source File: MattermostClient.java    From mattermost4j with Apache License 2.0 6 votes vote down vote up
private String detectSuffix(Response response) {
  MediaType mediaType = response.getMediaType();
  if (mediaType.isCompatible(MediaType.valueOf("image/png"))) {
    return ".png";
  } else if (mediaType.isCompatible(MediaType.valueOf("image/jpeg"))) {
    return ".jpg";
  } else if (mediaType.isCompatible(MediaType.valueOf("image/gif"))) {
    return ".gif";
  } else if (mediaType.isCompatible(MediaType.valueOf("image/bmp"))) {
    return ".bmp";
  } else {
    String contentDispositionHeader =
        String.class.cast(response.getHeaders().getFirst("Content-Disposition"));
    try {
      ContentDisposition contentDisposition = new ContentDisposition(contentDispositionHeader);
      String fileName = contentDisposition.getFileName();
      return fileName.substring(fileName.lastIndexOf("."));
    } catch (ParseException e) {
      // If server returns illegal syntax, that is server bug.
      throw new IllegalArgumentException(e);
    }
  }
}
 
Example 9
Source File: JAXRSClientServerBookTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testUseMapperOnBus() {
    String address = "http://localhost:" + PORT + "/bookstore/mapperonbus";
    WebClient wc = WebClient.create(address);
    Response r = wc.post(null);
    assertEquals(500, r.getStatus());
    MediaType mt = r.getMediaType();
    assertEquals("text/plain;charset=utf-8", mt.toString().toLowerCase());
    assertEquals("the-mapper", r.getHeaderString("BusMapper"));
    assertEquals("BusMapperException", r.readEntity(String.class));
}
 
Example 10
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);
}