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

The following examples show how to use javax.ws.rs.core.Response#getMetadata() . 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: JaxResponseWriter.java    From rest.vertx with Apache License 2.0 5 votes vote down vote up
private static void addHeaders(Response jaxrsResponse, HttpServerResponse response) {

		if (jaxrsResponse.getMetadata() != null) {

			List<Object> cookies = jaxrsResponse.getMetadata().get(HttpHeaders.SET_COOKIE.toString());
			if (cookies != null) {

				Iterator<Object> it = cookies.iterator();
				while (it.hasNext()) {
					Object next = it.next();
					if (next instanceof NewCookie) {
						NewCookie cookie = (NewCookie) next;
						response.putHeader(HttpHeaders.SET_COOKIE, cookie.toString());
					}
				}

				if (cookies.size() < 1) {
					jaxrsResponse.getMetadata().remove(HttpHeaders.SET_COOKIE.toString());
				}
			}
		}

		if (jaxrsResponse.getMetadata() != null && jaxrsResponse.getMetadata().size() > 0) {

			for (String name : jaxrsResponse.getMetadata().keySet()) {
				List<Object> meta = jaxrsResponse.getMetadata().get(name);

				if (meta != null && meta.size() > 0) {
					for (Object item : meta) {
						if (item != null) {
							response.putHeader(name, item.toString());
						}
					}
				}
			}
		}
	}
 
Example 2
Source File: JAXRSClientServerBookTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testCaching() throws Exception {

    String endpointAddress =
        "http://localhost:" + PORT + "/bookstore/books/response/123";

    // Add the CacheControlFeature to cache books returned by the service on the client side
    CacheControlFeature cacheControlFeature = new CacheControlFeature();
    cacheControlFeature.setCacheResponseInputStream(true);
    Client client = ClientBuilder.newBuilder()
        .register(cacheControlFeature)
        .build();
    WebTarget target = client.target(endpointAddress);

    // First call
    Response response = target.request().get();
    assertEquals(200, response.getStatus());
    Book book = response.readEntity(Book.class);
    assertEquals(123L, book.getId());

    MultivaluedMap<String, Object> headers = response.getMetadata();
    assertFalse(headers.isEmpty());
    Object etag = headers.getFirst("ETag");
    assertNotNull(etag);
    assertTrue(etag.toString().startsWith("\""));
    assertTrue(etag.toString().endsWith("\""));

    Object cacheControl = headers.getFirst("Cache-Control");
    assertNotNull(cacheControl);
    assertTrue(cacheControl.toString().contains("private"));
    assertTrue(cacheControl.toString().contains("max-age=100000"));

    // Now make a second call. This should be retrieved from the client's cache
    target.request().get();
    assertEquals(200, response.getStatus());
    book = response.readEntity(Book.class);
    assertEquals(123L, book.getId());

    cacheControlFeature.close();
}
 
Example 3
Source File: JAXRSClientServerBookTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testTempRedirectWebClient() throws Exception {
    WebClient client = WebClient.create("http://localhost:" + PORT + "/bookstore/tempredirect");
    Response r = client.type("*/*").get();
    assertEquals(307, r.getStatus());
    MultivaluedMap<String, Object> map = r.getMetadata();
    assertEquals("http://localhost:" + PORT + "/whatever/redirection?css1=http%3A//bar",
                 map.getFirst("Location").toString());
    List<Object> cookies = r.getMetadata().get("Set-Cookie");
    assertNotNull(cookies);
    assertEquals(2, cookies.size());
}
 
Example 4
Source File: BulkExtractTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetExtractResponse() throws Exception {
    injector.setOauthAuthenticationWithEducationRole();
    mockApplicationEntity();
    mockBulkExtractEntity(null);

    HttpRequestContext context = new HttpRequestContextAdapter() {
        @Override
        public String getMethod() {
            return "GET";
        }
    };

    Response res = bulkExtract.getEdOrgExtractResponse(context, null, null);
    assertEquals(200, res.getStatus());
    MultivaluedMap<String, Object> headers = res.getMetadata();
    assertNotNull(headers);
    assertTrue(headers.containsKey("content-disposition"));
    assertTrue(headers.containsKey("last-modified"));
    String header = (String) headers.getFirst("content-disposition");
    assertNotNull(header);
    assertTrue(header.startsWith("attachment"));
    assertTrue(header.indexOf(INPUT_FILE_NAME) > 0);

    Object entity = res.getEntity();
    assertNotNull(entity);

    StreamingOutput out = (StreamingOutput) entity;
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    out.write(os);
    os.flush();
    byte[] responseData = os.toByteArray();
    String s = new String(responseData);

    assertEquals(BULK_DATA, s);
}
 
Example 5
Source File: BulkExtractTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Test
public void testHeadTenant() throws Exception {
    injector.setOauthAuthenticationWithEducationRole();
    mockApplicationEntity();
    mockBulkExtractEntity(null);

    HttpRequestContext context = new HttpRequestContextAdapter() {
        @Override
        public String getMethod() {
            return "HEAD";
        }
    };

    Response res = bulkExtract.getEdOrgExtractResponse(context, null, null);
    assertEquals(200, res.getStatus());
    MultivaluedMap<String, Object> headers = res.getMetadata();
    assertNotNull(headers);
    assertTrue(headers.containsKey("content-disposition"));
    assertTrue(headers.containsKey("last-modified"));
    String header = (String) headers.getFirst("content-disposition");
    assertNotNull(header);
    assertTrue(header.startsWith("attachment"));
    assertTrue(header.indexOf(INPUT_FILE_NAME) > 0);

    Object entity = res.getEntity();
    assertNull(entity);
}
 
Example 6
Source File: BulkExtractTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Test
public void testEdOrgFullExtract() throws IOException, ParseException {
    injector.setOauthAuthenticationWithEducationRole();
    mockApplicationEntity();
    Entity mockedEntity = mockBulkExtractEntity(null);
    Mockito.when(edOrgHelper.byId(eq("ONE"))).thenReturn(mockedEntity);

    Map<String, Object> authBody = new HashMap<String, Object>();
    authBody.put("applicationId", "App1");
    authBody.put(ApplicationAuthorizationResource.EDORG_IDS, ApplicationAuthorizationResourceTest.getAuthList("ONE"));
    Entity mockAppAuth = Mockito.mock(Entity.class);
    Mockito.when(mockAppAuth.getBody()).thenReturn(authBody);
    Mockito.when(mockMongoEntityRepository.findOne(eq("applicationAuthorization"), Mockito.any(NeutralQuery.class)))
            .thenReturn(mockAppAuth);

    Response res = bulkExtract.getEdOrgExtract(CONTEXT, req, "ONE");

    assertEquals(200, res.getStatus());
    MultivaluedMap<String, Object> headers = res.getMetadata();
    assertNotNull(headers);
    assertTrue(headers.containsKey("content-disposition"));
    assertTrue(headers.containsKey("last-modified"));
    String header = (String) headers.getFirst("content-disposition");
    assertNotNull(header);
    assertTrue(header.startsWith("attachment"));
    assertTrue(header.indexOf(INPUT_FILE_NAME) > 0);

    Object entity = res.getEntity();
    assertNotNull(entity);

    StreamingOutput out = (StreamingOutput) entity;
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    out.write(os);
    os.flush();
    byte[] responseData = os.toByteArray();
    String s = new String(responseData);

    assertEquals(BULK_DATA, s);
}
 
Example 7
Source File: BulkExtractTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Test
public void testPublicExtract() throws IOException, ParseException {
    injector.setOauthAuthenticationWithEducationRole();
    mockApplicationEntity();
    Entity mockedEntity = mockBulkExtractEntity(null);
    Mockito.when(edOrgHelper.byId(eq("ONE"))).thenReturn(mockedEntity);

    Response res = bulkExtract.getPublicExtract(CONTEXT, req);

    assertEquals(200, res.getStatus());
    MultivaluedMap<String, Object> headers = res.getMetadata();
    assertNotNull(headers);
    assertTrue(headers.containsKey("content-disposition"));
    assertTrue(headers.containsKey("last-modified"));
    String header = (String) headers.getFirst("content-disposition");
    assertNotNull(header);
    assertTrue(header.startsWith("attachment"));
    assertTrue(header.indexOf(INPUT_FILE_NAME) > 0);

    Object entity = res.getEntity();
    assertNotNull(entity);

    StreamingOutput out = (StreamingOutput) entity;
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    out.write(os);
    os.flush();
    byte[] responseData = os.toByteArray();
    String s = new String(responseData);

    assertEquals(BULK_DATA, s);
}
 
Example 8
Source File: OptionsMethodTest.java    From io with Apache License 2.0 4 votes vote down vote up
/**
 * 認証なしのOPTIONSメソッドがリクエストされた場合にpersoniumで受け付けている全メソッドが返却されること.
 * @throws URISyntaxException URISyntaxException
 */
@Test
public void 認証なしのOPTIONSメソッドがリクエストされた場合にpersoniumで受け付けている全メソッドが返却されること() throws URISyntaxException {
    // 被テストオブジェクトを準備
    DcCoreContainerFilter containerFilter = new DcCoreContainerFilter();
    // ContainerRequiestを準備
    WebApplication wa = mock(WebApplication.class);
    InBoundHeaders headers = new InBoundHeaders();
    // X-FORWARDED-* 系のヘッダ設定
    String scheme = "https";
    String host = "example.org";
    headers.add(DcCoreUtils.HttpHeaders.X_FORWARDED_PROTO, scheme);
    headers.add(DcCoreUtils.HttpHeaders.X_FORWARDED_HOST, host);
    ContainerRequest request = new ContainerRequest(wa, HttpMethod.OPTIONS,
            new URI("http://dc1.example.com/hoge"),
            new URI("http://dc1.example.com/hoge/hoho"),
            headers, null);
    // HttpServletRequestのmockを準備
    HttpServletRequest mockServletRequest = mock(HttpServletRequest.class);
    when(mockServletRequest.getRequestURL()).thenReturn(new StringBuffer("http://dc1.example.com"));
    ServletContext mockServletContext = mock(ServletContext.class);
    when(mockServletContext.getContextPath()).thenReturn("");
    when(mockServletRequest.getServletContext()).thenReturn(mockServletContext);
    containerFilter.setHttpServletRequest(mockServletRequest);
    try {
        containerFilter.filter(request);
    } catch (WebApplicationException e) {
        Response response = e.getResponse();
        assertEquals(response.getStatus(), HttpStatus.SC_OK);
        MultivaluedMap<String, Object> meta = response.getMetadata();
        List<Object> values = meta.get("Access-Control-Allow-Methods");
        assertEquals(values.size(), 1);
        String value = (String) values.get(0);
        String[] methods = value.split(",");
        Map<String, String> masterMethods = new HashMap<String, String>();
        masterMethods.put(HttpMethod.OPTIONS, "");
        masterMethods.put(HttpMethod.GET, "");
        masterMethods.put(HttpMethod.POST, "");
        masterMethods.put(HttpMethod.PUT, "");
        masterMethods.put(HttpMethod.DELETE, "");
        masterMethods.put(HttpMethod.HEAD, "");
        masterMethods.put(com.fujitsu.dc.common.utils.DcCoreUtils.HttpMethod.MERGE, "");
        masterMethods.put(com.fujitsu.dc.common.utils.DcCoreUtils.HttpMethod.MKCOL, "");
        masterMethods.put(com.fujitsu.dc.common.utils.DcCoreUtils.HttpMethod.MOVE, "");
        masterMethods.put(com.fujitsu.dc.common.utils.DcCoreUtils.HttpMethod.PROPFIND, "");
        masterMethods.put(com.fujitsu.dc.common.utils.DcCoreUtils.HttpMethod.PROPPATCH, "");
        masterMethods.put(com.fujitsu.dc.common.utils.DcCoreUtils.HttpMethod.ACL, "");
        for (String method : methods) {
            if (method.trim() == "") {
                continue;
            }
            String m = masterMethods.remove(method.trim());
            if (m == null) {
                fail("Method " + method + " is not defined.");
            }
        }
        if (!masterMethods.isEmpty()) {
            fail("UnExcpected Error.");
        }
    }
}
 
Example 9
Source File: JAXRSClientServerBookTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Test
public void testCachingExpires() throws Exception {

    String endpointAddress =
        "http://localhost:" + PORT + "/bookstore/books/response2/123";

    // Add the CacheControlFeature to cache books returned by the service on the client side
    CacheControlFeature cacheControlFeature = new CacheControlFeature();
    cacheControlFeature.setCacheResponseInputStream(true);
    Client client = ClientBuilder.newBuilder()
        .register(cacheControlFeature)
        .build();
    WebTarget target = client.target(endpointAddress);

    // First call
    Response response = target.request().get();
    assertEquals(200, response.getStatus());
    Book book = response.readEntity(Book.class);
    assertEquals(123L, book.getId());

    MultivaluedMap<String, Object> headers = response.getMetadata();
    assertFalse(headers.isEmpty());
    Object etag = headers.getFirst("ETag");
    assertNotNull(etag);
    assertTrue(etag.toString().startsWith("\""));
    assertTrue(etag.toString().endsWith("\""));

    Object cacheControl = headers.getFirst("Cache-Control");
    assertNotNull(cacheControl);
    assertTrue(cacheControl.toString().contains("private"));
    assertTrue(cacheControl.toString().contains("max-age=1"));

    // Now make a second call. The value in the cache will have expired, so
    // it should call the service again
    Thread.sleep(1500L);
    target.request().get();
    assertEquals(200, response.getStatus());
    book = response.readEntity(Book.class);
    assertEquals(123L, book.getId());

    cacheControlFeature.close();
}
 
Example 10
Source File: JAXRSClientServerBookTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Test
public void testCachingExpiresUsingETag() throws Exception {

    String endpointAddress =
        "http://localhost:" + PORT + "/bookstore/books/response3/123";

    // Add the CacheControlFeature to cache books returned by the service on the client side
    CacheControlFeature cacheControlFeature = new CacheControlFeature();
    cacheControlFeature.setCacheResponseInputStream(true);
    Client client = ClientBuilder.newBuilder()
        .register(cacheControlFeature)
        .build();
    WebTarget target = client.target(endpointAddress);

    // First call
    Response response = target.request().get();
    assertEquals(200, response.getStatus());
    Book book = response.readEntity(Book.class);
    assertEquals(123L, book.getId());

    MultivaluedMap<String, Object> headers = response.getMetadata();
    assertFalse(headers.isEmpty());
    Object etag = headers.getFirst("ETag");
    assertNotNull(etag);
    assertTrue(etag.toString().startsWith("\""));
    assertTrue(etag.toString().endsWith("\""));

    Object cacheControl = headers.getFirst("Cache-Control");
    assertNotNull(cacheControl);
    assertTrue(cacheControl.toString().contains("private"));
    assertTrue(cacheControl.toString().contains("max-age=1"));

    // Now make a second call. The value in the clients cache will have expired, so it should call
    // out to the service, which will return 304, and the client will re-use the cached payload
    Thread.sleep(1500L);
    target.request().get();
    assertEquals(200, response.getStatus());
    book = response.readEntity(Book.class);
    assertEquals(123L, book.getId());

    cacheControlFeature.close();
}