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

The following examples show how to use javax.ws.rs.core.Response#getHeaders() . 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: RESTExceptionMapperTest.java    From datawave with Apache License 2.0 6 votes vote down vote up
@Test
public void testToResponse_WrappedQueryException() {
    Exception e = new WebApplicationException(new QueryException("top-level", new QueryException("bottom-level", "567-8"), "123-4"));
    StackTraceElement[] traceArr = new StackTraceElement[1];
    traceArr[0] = new StackTraceElement("dummyClass", "dummyMethod", null, 0);
    
    e.setStackTrace(traceArr);
    
    Response response = rem.toResponse(e);
    MultivaluedMap<String,Object> responseMap = response.getHeaders();
    
    Assert.assertEquals(500, response.getStatus());
    Assert.assertEquals(6, responseMap.size());
    Assert.assertEquals(Lists.newArrayList(true), responseMap.get(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS));
    Assert.assertEquals(Lists.newArrayList("*"), responseMap.get(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
    Assert.assertEquals(Lists.newArrayList(864000), responseMap.get(HttpHeaders.ACCESS_CONTROL_MAX_AGE));
    Assert.assertEquals(Lists.newArrayList("567-8"), responseMap.get(Constants.ERROR_CODE));
    Assert.assertEquals(Lists.newArrayList("null/null"), responseMap.get(Constants.RESPONSE_ORIGIN));
    Assert.assertEquals(Lists.newArrayList("X-SSL-ClientCert-Subject, X-ProxiedEntitiesChain, X-ProxiedIssuersChain, Accept, Accept-Encoding"),
                    responseMap.get(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS));
}
 
Example 2
Source File: CatalogRestTest.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void getCommitChainWithPaginationTest() {
    Response response = target().path("catalogs/" + encode(LOCAL_IRI) + "/records/" + encode(RECORD_IRI)
            + "/branches/" + encode(BRANCH_IRI) + "/commits").queryParam("offset", 0).queryParam("limit", 10)
            .request().get();
    assertEquals(response.getStatus(), 200);
    verify(catalogManager).getCommitChain(vf.createIRI(LOCAL_IRI), vf.createIRI(RECORD_IRI), vf.createIRI(BRANCH_IRI));
    MultivaluedMap<String, Object> headers = response.getHeaders();
    assertEquals(headers.get("X-Total-Count").get(0), "" + COMMIT_IRIS.length);
    assertEquals(response.getLinks().size(), 0);
    try {
        JSONArray array = JSONArray.fromObject(response.readEntity(String.class));
        assertEquals(array.size(), COMMIT_IRIS.length);
        array.forEach(result -> {
            JSONObject commitObj = JSONObject.fromObject(result);
            assertTrue(commitObj.containsKey("id"));
            assertTrue(Arrays.asList(COMMIT_IRIS).contains(commitObj.getString("id")));
        });
    } catch (Exception e) {
        fail("Expected no exception, but got: " + e.getMessage());
    }
}
 
Example 3
Source File: RESTExceptionMapperTest.java    From datawave with Apache License 2.0 6 votes vote down vote up
@Test
public void testToResponse_EJBException3() {
    Exception e = new EJBException(new ArrayStoreException());
    StackTraceElement[] traceArr = new StackTraceElement[1];
    traceArr[0] = new StackTraceElement("dummyClass", "dummyMethod", null, 0);
    
    e.setStackTrace(traceArr);
    
    Response response = rem.toResponse(e);
    MultivaluedMap<String,Object> responseMap = response.getHeaders();
    
    Assert.assertEquals(500, response.getStatus());
    Assert.assertEquals(6, responseMap.size());
    Assert.assertEquals(Lists.newArrayList(true), responseMap.get(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS));
    Assert.assertEquals(Lists.newArrayList("*"), responseMap.get(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
    Assert.assertEquals(Lists.newArrayList(864000), responseMap.get(HttpHeaders.ACCESS_CONTROL_MAX_AGE));
    Assert.assertEquals(Lists.newArrayList("500-1"), responseMap.get(Constants.ERROR_CODE));
    Assert.assertEquals(Lists.newArrayList("null/null"), responseMap.get(Constants.RESPONSE_ORIGIN));
    Assert.assertEquals(Lists.newArrayList("X-SSL-ClientCert-Subject, X-ProxiedEntitiesChain, X-ProxiedIssuersChain, Accept, Accept-Encoding"),
                    responseMap.get(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS));
}
 
Example 4
Source File: DatasetRestTest.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void getDatasetRecordsWithLinksTest() {
    // Setup:
    when(results.getPage()).thenReturn(Collections.singletonList(record2));
    when(results.getPageNumber()).thenReturn(2);
    when(results.getPageSize()).thenReturn(1);

    Response response = target().path("datasets").queryParam("offset", 1).queryParam("limit", 1).request().get();
    assertEquals(response.getStatus(), 200);
    verify(datasetManager).getDatasetRecords(any(DatasetPaginatedSearchParams.class));
    verify(service, atLeastOnce()).skolemize(any(Statement.class));
    MultivaluedMap<String, Object> headers = response.getHeaders();
    assertEquals(headers.get("X-Total-Count").get(0), "3");
    Set<Link> links = response.getLinks();
    assertEquals(links.size(), 2);
    assertTrue(response.hasLink("prev"));
    assertTrue(response.hasLink("next"));
    try {
        JSONArray result = JSONArray.fromObject(response.readEntity(String.class));
        assertEquals(result.size(), 1);
    } catch (Exception e) {
        fail("Expected no exception, but got: " + e.getMessage());
    }
}
 
Example 5
Source File: RESTExceptionMapperTest.java    From datawave with Apache License 2.0 6 votes vote down vote up
@Test
public void testToResponse_GetClassAndCause2() {
    Exception e = new UndeclaredThrowableException(null, "java.lang.IllegalArgumentException: ");
    StackTraceElement[] traceArr = new StackTraceElement[1];
    traceArr[0] = new StackTraceElement("dummyClass", "dummyMethod", null, 0);
    
    e.setStackTrace(traceArr);
    
    Response response = rem.toResponse(e);
    MultivaluedMap<String,Object> responseMap = response.getHeaders();
    
    Assert.assertEquals(400, response.getStatus());
    Assert.assertEquals(6, responseMap.size());
    Assert.assertEquals(Lists.newArrayList(true), responseMap.get(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS));
    Assert.assertEquals(Lists.newArrayList("*"), responseMap.get(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
    Assert.assertEquals(Lists.newArrayList(864000), responseMap.get(HttpHeaders.ACCESS_CONTROL_MAX_AGE));
    Assert.assertEquals(Lists.newArrayList("400-1"), responseMap.get(Constants.ERROR_CODE));
    Assert.assertEquals(Lists.newArrayList("null/null"), responseMap.get(Constants.RESPONSE_ORIGIN));
    Assert.assertEquals(Lists.newArrayList("X-SSL-ClientCert-Subject, X-ProxiedEntitiesChain, X-ProxiedIssuersChain, Accept, Accept-Encoding"),
                    responseMap.get(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS));
}
 
Example 6
Source File: CatalogRestTest.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void getCommitChainTest() {
    Response response = target().path("catalogs/" + encode(LOCAL_IRI) + "/records/" + encode(RECORD_IRI)
            + "/branches/" + encode(BRANCH_IRI) + "/commits")
            .request().get();
    assertEquals(response.getStatus(), 200);
    verify(catalogManager).getCommitChain(vf.createIRI(LOCAL_IRI), vf.createIRI(RECORD_IRI), vf.createIRI(BRANCH_IRI));
    MultivaluedMap<String, Object> headers = response.getHeaders();
    assertEquals(headers.get("X-Total-Count").get(0), "" + COMMIT_IRIS.length);
    assertEquals(response.getLinks().size(), 0);
    try {
        JSONArray array = JSONArray.fromObject(response.readEntity(String.class));
        assertEquals(array.size(), COMMIT_IRIS.length);
        array.forEach(result -> {
            JSONObject commitObj = JSONObject.fromObject(result);
            assertTrue(commitObj.containsKey("id"));
            assertTrue(Arrays.asList(COMMIT_IRIS).contains(commitObj.getString("id")));
        });
    } catch (Exception e) {
        fail("Expected no exception, but got: " + e.getMessage());
    }
}
 
Example 7
Source File: CatalogRestTest.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void getVersionedDistributionsTest() {
    Response response = target().path("catalogs/" + encode(LOCAL_IRI) + "/records/" + encode(RECORD_IRI)
            + "/versions/" + encode(VERSION_IRI) + "/distributions")
            .queryParam("sort", DCTERMS.TITLE.stringValue())
            .queryParam("offset", 0)
            .queryParam("limit", 10)
            .request().get();
    verify(catalogManager).getVersionedDistributions(vf.createIRI(LOCAL_IRI), vf.createIRI(RECORD_IRI), vf.createIRI(VERSION_IRI));
    MultivaluedMap<String, Object> headers = response.getHeaders();
    assertEquals(headers.get("X-Total-Count").get(0), "1");
    assertEquals(response.getLinks().size(), 0);
    try {
        JSONArray result = JSONArray.fromObject(response.readEntity(String.class));
        assertEquals(result.size(), 1);
    } catch (Exception e) {
        fail("Expected no exception, but got: " + e.getMessage());
    }
}
 
Example 8
Source File: RESTExceptionMapperTest.java    From datawave with Apache License 2.0 6 votes vote down vote up
@Test
public void testToResponse_simpleException() {
    
    Exception e = new Exception();
    Response response = rem.toResponse(e);
    MultivaluedMap<String,Object> responseMap = response.getHeaders();
    
    Assert.assertEquals(500, response.getStatus());
    Assert.assertEquals(6, responseMap.size());
    Assert.assertEquals(Lists.newArrayList(true), responseMap.get(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS));
    Assert.assertEquals(Lists.newArrayList("*"), responseMap.get(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
    Assert.assertEquals(Lists.newArrayList(864000), responseMap.get(HttpHeaders.ACCESS_CONTROL_MAX_AGE));
    Assert.assertEquals(Lists.newArrayList("500-1"), responseMap.get(Constants.ERROR_CODE));
    Assert.assertEquals(Lists.newArrayList("null/null"), responseMap.get(Constants.RESPONSE_ORIGIN));
    Assert.assertEquals(Lists.newArrayList("X-SSL-ClientCert-Subject, X-ProxiedEntitiesChain, X-ProxiedIssuersChain, Accept, Accept-Encoding"),
                    responseMap.get(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS));
}
 
Example 9
Source File: CatalogRestTest.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void getBranchesTest() {
    Response response = target().path("catalogs/" + encode(LOCAL_IRI) + "/records/" + encode(RECORD_IRI) + "/branches")
            .queryParam("sort", DCTERMS.TITLE.stringValue())
            .queryParam("offset", 0)
            .queryParam("limit", 10)
            .request().get();
    assertEquals(response.getStatus(), 200);
    verify(catalogManager).getBranches(vf.createIRI(LOCAL_IRI), vf.createIRI(RECORD_IRI));
    MultivaluedMap<String, Object> headers = response.getHeaders();
    assertEquals(headers.get("X-Total-Count").get(0), "2");
    assertEquals(response.getLinks().size(), 0);
    try {
        JSONArray result = JSONArray.fromObject(response.readEntity(String.class));
        assertEquals(result.size(), 2);
    } catch (Exception e) {
        fail("Expected no exception, but got: " + e.getMessage());
    }
}
 
Example 10
Source File: CommitRestTest.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void getCommitHistoryWithPaginationTest() {
    Response response = target().path("commits/" + encode(COMMIT_IRIS[1]) + "/history")
            .queryParam("offset", 0)
            .queryParam("limit", 10)
            .request().get();
    assertEquals(response.getStatus(), 200);
    verify(catalogManager).getCommitChain(vf.createIRI(COMMIT_IRIS[1]));
    MultivaluedMap<String, Object> headers = response.getHeaders();
    assertEquals(headers.get("X-Total-Count").get(0), "" + COMMIT_IRIS.length);
    assertEquals(response.getLinks().size(), 0);
    try {
        JSONArray array = JSONArray.fromObject(response.readEntity(String.class));
        assertEquals(array.size(), COMMIT_IRIS.length);
        array.forEach(result -> {
            JSONObject commitObj = JSONObject.fromObject(result);
            assertTrue(commitObj.containsKey("id"));
            assertTrue(Arrays.asList(COMMIT_IRIS).contains(commitObj.getString("id")));
        });
    } catch (Exception e) {
        fail("Expected no exception, but got: " + e.getMessage());
    }
}
 
Example 11
Source File: CorsFilterIntTest.java    From jrestless with Apache License 2.0 6 votes vote down vote up
@Test
public void testValidCorsPreflightRequest() {
	Response response = target()
			.path("delete")
			.request()
			.header(CorsHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.DELETE)
			.header(CorsHeaders.ORIGIN, DEFAULT_ORIGIN)
			.options();
	assertEquals(200, response.getStatus());
	MultivaluedMap<String, Object> headers = response.getHeaders();
	assertEquals(DEFAULT_ORIGIN, headers.getFirst(CorsHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
	assertEquals(HttpMethod.DELETE, headers.getFirst(CorsHeaders.ACCESS_CONTROL_ALLOW_METHODS));
	assertEquals("true", headers.getFirst(CorsHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS));
	assertEquals("3600", headers.getFirst(CorsHeaders.ACCESS_CONTROL_MAX_AGE));
	assertEquals(CorsHeaders.ORIGIN, headers.getFirst(HttpHeaders.VARY));
}
 
Example 12
Source File: ExceptionFilter.java    From hugegraph with Apache License 2.0 5 votes vote down vote up
@Override
public Response toResponse(WebApplicationException exception) {
    Response response = exception.getResponse();
    if (response.hasEntity()) {
        return response;
    }
    MultivaluedMap<String, Object> headers = response.getHeaders();
    boolean trace = this.trace(response.getStatus());
    response = Response.status(response.getStatus())
                       .type(MediaType.APPLICATION_JSON)
                       .entity(formatException(exception, trace))
                       .build();
    response.getHeaders().putAll(headers);
    return response;
}
 
Example 13
Source File: RedirectionTest.java    From tool.accelerate.core with Apache License 2.0 5 votes vote down vote up
@Test
public void testSlashContextRoot() throws Exception {
    String queryString = "";
    Response response = getResponse(queryString);
    try {
        assertEquals(301, response.getStatus());
        MultivaluedMap<String, Object> headers = response.getHeaders();
        String location = headers.get("Location").toString();
        assertTrue("Location should be /start, instead got " + location, location.equals("[/start/]"));
    } finally {
        response.close();
    }
}
 
Example 14
Source File: CommitRestTest.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void getCommitHistoryWithEntityNoTargetTest() {
    when(catalogManager.getCommitEntityChain(any(Resource.class), any(Resource.class))).thenReturn(entityCommits);
    Response response = target().path("commits/" + encode(COMMIT_IRIS[1]) + "/history")
            .queryParam("entityId", encode(vf.createIRI("http://mobi.com/test/class5")))
            .queryParam("offset", 0)
            .queryParam("limit", 1)
            .request().get();
    assertEquals(response.getStatus(), 200);
    verify(catalogManager).getCommitEntityChain(vf.createIRI(COMMIT_IRIS[1]), vf.createIRI("http://mobi.com/test/class5"));
    MultivaluedMap<String, Object> headers = response.getHeaders();
    assertEquals(headers.get("X-Total-Count").get(0), "" + ENTITY_IRI.length);
    assertEquals(response.getLinks().size(), 0);
    Set<Link> links = response.getLinks();
    assertEquals(links.size(), 0);
    links.forEach(link -> {
        assertTrue(link.getUri().getRawPath().contains("commits/" + encode(COMMIT_IRIS[1]) + "/history"));
        assertTrue(link.getRel().equals("prev") || link.getRel().equals("next"));
    });
    try {
        JSONArray result = JSONArray.fromObject(response.readEntity(String.class));
        assertEquals(result.size(), 1);
        JSONObject commitObj = result.getJSONObject(0);
        assertTrue(commitObj.containsKey("id"));
        assertEquals(commitObj.getString("id"), COMMIT_IRIS[1]);
    } catch (Exception e) {
        fail("Expected no exception, but got: " + e.getMessage());
    }
}
 
Example 15
Source File: TestServer.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Test
public void testHeaders() throws Exception {
  final Response invoke = getBuilder(getPublicAPI(3).path("catalog")).buildGet().invoke();
  final MultivaluedMap<String, Object> headers = invoke.getHeaders();
  assertTrue(headers.containsKey("x-content-type-options"));
  assertTrue(headers.containsKey("x-frame-options"));
  assertTrue(headers.containsKey("x-xss-protection"));

  // no CSP header by default
  assertFalse(headers.containsKey("content-security-policy"));
}
 
Example 16
Source File: ShopifySdk.java    From shopify-sdk with Apache License 2.0 5 votes vote down vote up
private Response handleResponse(final Response response, final Status... expectedStatus) {

		if ((response.getHeaders() != null) && response.getHeaders().containsKey(DEPRECATED_REASON_HEADER)) {
			LOGGER.error(DEPRECATED_SHOPIFY_CALL_ERROR_MESSAGE, response.getLocation(), response.getStatus(),
					response.getStringHeaders());
		}

		final List<Integer> expectedStatusCodes = getExpectedStatusCodes(expectedStatus);
		if (expectedStatusCodes.contains(response.getStatus())) {
			return response;
		}

		throw new ShopifyErrorResponseException(response);
	}
 
Example 17
Source File: ProvRestTest.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void getActivitiesOnePageTest() throws Exception {
    Response response = target().path("provenance-data").request().get();
    assertEquals(response.getStatus(), 200);
    MultivaluedMap<String, Object> headers = response.getHeaders();
    assertEquals(headers.get("X-Total-Count").get(0), "10");
    verify(provService, times(10)).getActivity(any(Resource.class));
    try {
        JSONObject result = JSONObject.fromObject(response.readEntity(String.class));
        assertActivities(result, activityIRIs);
        assertEntities(result, entityIRIs);
    } catch (Exception e) {
        fail("Expected no exception, but got: " + e.getMessage());
    }
}
 
Example 18
Source File: SparqlRestTest.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void getPagedResultsTest() {
    Response response = target().path("sparql/page").queryParam("query", ALL_QUERY).request().get();
    assertEquals(response.getStatus(), 200);
    verify(repositoryManager).getRepository("system");
    MultivaluedMap<String, Object> headers = response.getHeaders();
    assertEquals(headers.get("X-Total-Count").get(0), "" + testModel.size());
    assertEquals(response.getLinks().size(), 0);
    JSONObject result = JSONObject.fromObject(response.readEntity(String.class));
    assertTrue(result.containsKey("bindings"));
    assertTrue(result.containsKey("data"));
    assertEquals(result.getJSONArray("data").size(), testModel.size());
}
 
Example 19
Source File: ApiClient.java    From datacollector with Apache License 2.0 4 votes vote down vote up
/**
 * Invoke API by sending HTTP request with the given options.
 *
 * @param path The sub-path of the HTTP URL
 * @param method The request method, one of "GET", "POST", "PUT", and "DELETE"
 * @param queryParams The query parameters
 * @param body The request body object - if it is not binary, otherwise null
 * @param binaryBody The request body object - if it is binary, otherwise null
 * @param headerParams The header parameters
 * @param formParams The form parameters
 * @param accept The request's Accept header
 * @param contentType The request's Content-Type header
 * @param authNames The authentications to apply
 * @return The response body in type of string
 */
public <T> T invokeAPI(String path, String method, List<Pair> queryParams, Object body, byte[] binaryBody,
                       Map<String, String> headerParams, Map<String, Object> formParams, String accept,
                       String contentType, String[] authNames, TypeRef returnType) throws ApiException {

  Response response = getAPIResponse(path, method, queryParams, body, binaryBody, headerParams, formParams,
      accept, contentType, authNames);

  statusCode = response.getStatusInfo().getStatusCode();
  responseHeaders = response.getHeaders();

  if (statusCode == 401) {
    throw new ApiException(
        response.getStatusInfo().getStatusCode(),
        "HTTP Error 401 - Unauthorized: Access is denied due to invalid credentials.",
        response.getHeaders(),
        null);
  } else if (response.getStatusInfo() == Response.Status.NO_CONTENT) {
    return null;
  } else if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) {
    if (returnType == null)
      return null;
    else
      return deserialize(response, returnType);
  } else {
    String message = "error";
    String respBody = null;
    if (response.hasEntity()) {
      try {
        respBody = response.readEntity(String.class);
        message = respBody;
      } catch (RuntimeException e) {
        // e.printStackTrace();
      }
    }
    throw new ApiException(
        response.getStatusInfo().getStatusCode(),
        message,
        response.getHeaders(),
        respBody);
  }
}
 
Example 20
Source File: OpenApiResourceTest.java    From gravitee-management-rest-api with Apache License 2.0 3 votes vote down vote up
@Test
public void shouldGetOpenApiSpecification() throws IOException {
    
    final Response response = root().path("openapi").request().get();
    assertEquals(OK_200, response.getStatus());

    MultivaluedMap<String, Object> headers = response.getHeaders();
    String contentType = (String) headers.getFirst(HttpHeader.CONTENT_TYPE.asString());

    assertEquals(MediaType.TEXT_PLAIN, contentType);

    String result = response.readEntity(String.class);
    assertEquals("DUMMY OPENAPI", result);
    
}