下面列出了javax.ws.rs.core.Response#getMetadata() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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());
}
}
}
}
}
}
@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();
}
@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());
}
@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);
}
@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);
}
@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);
}
@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);
}
/**
* 認証なしの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.");
}
}
}
@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();
}
@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();
}