Search in sources :

Example 16 with NewCookie

use of javax.ws.rs.core.NewCookie in project jersey by jersey.

the class AbortResponseClientTest method testRequestAbort.

@Test
public void testRequestAbort() {
    final Date date = getDate();
    ClientRequestFilter outFilter = new ClientRequestFilter() {

        @Override
        public void filter(ClientRequestContext context) throws IOException {
            NewCookie cookie1 = new NewCookie("cookie1", "cookie1");
            NewCookie cookie2 = new NewCookie("cookie2", "cookie2");
            final Response response = Response.ok().cookie(cookie1).cookie(cookie2).header("head1", "head1").header(HttpHeaders.DATE, date).header(HttpHeaders.ETAG, "\"123465\"").header(HttpHeaders.CONTENT_LANGUAGE, "language").header(HttpHeaders.LAST_MODIFIED, date).header(HttpHeaders.CONTENT_LENGTH, 99).type(MediaType.TEXT_HTML_TYPE).location(URI.create("www.oracle.com")).build();
            // abort the request
            context.abortWith(response);
        }
    };
    ClientResponseFilter inFilter = new ClientResponseFilter() {

        @Override
        public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException {
            Map<String, NewCookie> map = responseContext.getCookies();
            assertEquals("cookie1", map.get("cookie1").getValue());
            assertEquals("cookie2", map.get("cookie2").getValue());
            final MultivaluedMap<String, String> headers = responseContext.getHeaders();
            assertEquals("head1", headers.get("head1").get(0));
            assertEquals(date.getTime(), responseContext.getDate().getTime());
        }
    };
    WebTarget target = target().path("test");
    target.register(outFilter).register(inFilter);
    Invocation i = target.request().buildGet();
    Response r = i.invoke();
    assertEquals("head1", r.getHeaderString("head1"));
    assertEquals("cookie1", r.getCookies().get("cookie1").getValue());
    assertEquals("cookie2", r.getCookies().get("cookie2").getValue());
    assertEquals(date.getTime(), r.getDate().getTime());
    assertEquals("123465", r.getEntityTag().getValue());
    assertEquals("language", r.getLanguage().toString());
    assertEquals(date.getTime(), r.getLastModified().getTime());
    // Assert.assertEquals("uri", r.getLink("link")); TODO: not supported yet
    assertEquals("www.oracle.com", r.getLocation().toString());
    assertEquals(MediaType.TEXT_HTML_TYPE, r.getMediaType());
    assertEquals(99, r.getLength());
    assertEquals(200, r.getStatus());
}
Also used : ClientRequestFilter(javax.ws.rs.client.ClientRequestFilter) ClientRequestContext(javax.ws.rs.client.ClientRequestContext) Response(javax.ws.rs.core.Response) Invocation(javax.ws.rs.client.Invocation) ClientResponseFilter(javax.ws.rs.client.ClientResponseFilter) WebTarget(javax.ws.rs.client.WebTarget) ClientResponseContext(javax.ws.rs.client.ClientResponseContext) Date(java.util.Date) NewCookie(javax.ws.rs.core.NewCookie) Test(org.junit.Test) JerseyTest(org.glassfish.jersey.test.JerseyTest)

Example 17 with NewCookie

use of javax.ws.rs.core.NewCookie in project keywhiz by square.

the class SessionLoginResource method cookiesForUser.

public ImmutableList<NewCookie> cookiesForUser(User user) {
    ZonedDateTime expiration = ZonedDateTime.now().plusMinutes(15);
    String session = cookieFactory.getSession(user, expiration);
    NewCookie cookie = cookieFactory.cookieFor(session, expiration);
    NewCookie xsrfCookie = xsrfProtection.generate(session);
    return ImmutableList.of(cookie, xsrfCookie);
}
Also used : ZonedDateTime(java.time.ZonedDateTime) NewCookie(javax.ws.rs.core.NewCookie)

Example 18 with NewCookie

use of javax.ws.rs.core.NewCookie in project keywhiz by square.

the class CookieRenewingFilterTest method setsAllNewCookieWithValidCookie.

@Test
public void setsAllNewCookieWithValidCookie() throws Exception {
    User user = User.named("username");
    when(request.getCookies()).thenReturn(ImmutableMap.of(SESSION_COOKIE, cookie));
    when(authenticator.authenticate(cookie)).thenReturn(Optional.of(user));
    NewCookie newCookie1 = new NewCookie(SESSION_COOKIE, "new session");
    NewCookie newCookie2 = new NewCookie("XSRF", "new xsrf");
    when(sessionLoginResource.cookiesForUser(user)).thenReturn(ImmutableList.of(newCookie1, newCookie2));
    filter.filter(request, response);
    assertThat(getCookieMap(response)).contains(entry(newCookie1.getName(), newCookie1.getValue()), entry(newCookie2.getName(), newCookie2.getValue()));
}
Also used : User(keywhiz.auth.User) NewCookie(javax.ws.rs.core.NewCookie) Test(org.junit.Test)

Example 19 with NewCookie

use of javax.ws.rs.core.NewCookie in project keywhiz by square.

the class SessionLogoutResourceTest method logoutResourceDeletesSessionCookie.

@Test
public void logoutResourceDeletesSessionCookie() throws Exception {
    NewCookie cookie = cookieFactory.getSessionCookie(User.named("Me"), ZonedDateTime.now(clock).plusDays(1));
    Response response = sessionLogoutResource.logout(cookie);
    assertThat(response.getStatus()).isEqualTo(303);
    String resultCookie = response.getMetadata().getFirst("Set-Cookie").toString();
    assertThat(resultCookie).contains("HttpOnly").contains("Secure").contains("Path=/admin;").contains("session=expired;");
}
Also used : Response(javax.ws.rs.core.Response) NewCookie(javax.ws.rs.core.NewCookie) Test(org.junit.Test)

Example 20 with NewCookie

use of javax.ws.rs.core.NewCookie in project apex-core by apache.

the class StramAgent method retrieveWebServicesInfo.

private StramWebServicesInfo retrieveWebServicesInfo(String appId) {
    YarnClient yarnClient = YarnClient.createYarnClient();
    String url;
    try {
        yarnClient.init(conf);
        yarnClient.start();
        ApplicationReport ar = yarnClient.getApplicationReport(ConverterUtils.toApplicationId(appId));
        if (ar == null) {
            LOG.warn("YARN does not have record for this application {}", appId);
            return null;
        } else if (ar.getYarnApplicationState() != YarnApplicationState.RUNNING) {
            LOG.debug("Application {} is not running (state: {})", appId, ar.getYarnApplicationState());
            return null;
        }
        String trackingUrl = ar.getTrackingUrl();
        if (!trackingUrl.startsWith("http://") && !trackingUrl.startsWith("https://")) {
            url = "http://" + trackingUrl;
        } else {
            url = trackingUrl;
        }
        if (StringUtils.isBlank(url)) {
            LOG.error("Cannot get tracking url from YARN");
            return null;
        }
        if (url.endsWith("/")) {
            url = url.substring(0, url.length() - 1);
        }
        url += WebServices.PATH;
    } catch (Exception ex) {
        LOG.error("Cannot retrieve web services info", ex);
        return null;
    } finally {
        yarnClient.stop();
    }
    WebServicesClient webServicesClient = new WebServicesClient();
    try {
        JSONObject response;
        String secToken = null;
        ClientResponse clientResponse;
        int i = 0;
        while (true) {
            LOG.debug("Accessing url {}", url);
            clientResponse = webServicesClient.process(url, ClientResponse.class, new WebServicesClient.GetWebServicesHandler<ClientResponse>());
            String val = clientResponse.getHeaders().getFirst("Refresh");
            if (val == null) {
                break;
            }
            int index = val.indexOf("url=");
            if (index < 0) {
                break;
            }
            url = val.substring(index + 4);
            if (i++ > MAX_REDIRECTS) {
                LOG.error("Cannot get web service info -- exceeded the max number of redirects");
                return null;
            }
        }
        if (!UserGroupInformation.isSecurityEnabled()) {
            response = new JSONObject(clientResponse.getEntity(String.class));
        } else {
            if (UserGroupInformation.isSecurityEnabled()) {
                for (NewCookie nc : clientResponse.getCookies()) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Cookie " + nc.getName() + " " + nc.getValue());
                    }
                    if (nc.getName().equals(StramWSFilter.CLIENT_COOKIE)) {
                        secToken = nc.getValue();
                    }
                }
            }
            response = new JSONObject(clientResponse.getEntity(String.class));
        }
        String version = response.getString("version");
        response = webServicesClient.process(url + "/" + version + "/stram/info", JSONObject.class, new WebServicesClient.GetWebServicesHandler<JSONObject>());
        String appMasterUrl = response.getString("appMasterTrackingUrl");
        String appPath = response.getString("appPath");
        String user = response.getString("user");
        JSONObject permissionsInfo = null;
        try (FSDataInputStream is = fileSystem.open(new Path(appPath, "permissions.json"))) {
            permissionsInfo = new JSONObject(IOUtils.toString(is));
        } catch (FileNotFoundException ex) {
        // ignore if file is not found
        }
        return new StramWebServicesInfo(appMasterUrl, version, appPath, user, secToken, permissionsInfo);
    } catch (Exception ex) {
        LOG.warn("Cannot retrieve web service info for app {}", appId, ex);
        return null;
    }
}
Also used : ClientResponse(com.sun.jersey.api.client.ClientResponse) Path(org.apache.hadoop.fs.Path) FileNotFoundException(java.io.FileNotFoundException) WebServicesClient(com.datatorrent.stram.util.WebServicesClient) YarnClient(org.apache.hadoop.yarn.client.api.YarnClient) IncompatibleVersionException(com.datatorrent.stram.client.WebServicesVersionConversion.IncompatibleVersionException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) JSONException(org.codehaus.jettison.json.JSONException) ClientHandlerException(com.sun.jersey.api.client.ClientHandlerException) ApplicationReport(org.apache.hadoop.yarn.api.records.ApplicationReport) JSONObject(org.codehaus.jettison.json.JSONObject) FSDataInputStream(org.apache.hadoop.fs.FSDataInputStream) NewCookie(javax.ws.rs.core.NewCookie)

Aggregations

NewCookie (javax.ws.rs.core.NewCookie)22 Test (org.junit.Test)11 Response (javax.ws.rs.core.Response)9 IOException (java.io.IOException)3 Date (java.util.Date)3 HashMap (java.util.HashMap)3 Invocation (javax.ws.rs.client.Invocation)3 SimpleSign (ddf.security.samlp.SimpleSign)2 ValidationException (ddf.security.samlp.ValidationException)2 SecurityServiceException (ddf.security.service.SecurityServiceException)2 AbstractJerseyTest (io.dropwizard.jersey.AbstractJerseyTest)2 GET (javax.ws.rs.GET)2 WebTarget (javax.ws.rs.client.WebTarget)2 Cookie (javax.ws.rs.core.Cookie)2 User (keywhiz.auth.User)2 WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)2 AuthnRequest (org.opensaml.saml.saml2.core.AuthnRequest)2 IncompatibleVersionException (com.datatorrent.stram.client.WebServicesVersionConversion.IncompatibleVersionException)1 WebServicesClient (com.datatorrent.stram.util.WebServicesClient)1 ClientHandlerException (com.sun.jersey.api.client.ClientHandlerException)1