java.net.CookieManager Java Examples

The following examples show how to use java.net.CookieManager. 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: HttpClientUnitTest.java    From tutorials with MIT License 7 votes vote down vote up
@Test
public void shouldStoreCookieWhenPolicyAcceptAll() throws URISyntaxException, IOException, InterruptedException {
    HttpRequest request = HttpRequest.newBuilder()
        .uri(new URI("https://postman-echo.com/get"))
        .GET()
        .build();

    HttpClient httpClient = HttpClient.newBuilder()
        .cookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_ALL))
        .build();

    httpClient.send(request, HttpResponse.BodyHandlers.ofString());

    assertTrue(httpClient.cookieHandler()
        .isPresent());
}
 
Example #2
Source File: HttpUtils.java    From commerce-gradle-plugin with Apache License 2.0 6 votes vote down vote up
public static HttpURLConnection open(URI uri, CookieManager cookieManager) throws Exception {
    HttpURLConnection connection = (HttpURLConnection) uri.toURL().openConnection();
    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.setUseCaches(false);
    connection.setInstanceFollowRedirects(false);

    connection.setConnectTimeout(5000);
    connection.setReadTimeout(5000);

    List<HttpCookie> cookies = cookieManager.getCookieStore().get(uri);
    String param = cookies.stream().map(HttpCookie::toString).collect(Collectors.joining("; "));
    connection.addRequestProperty("Cookie", param);

    return connection;
}
 
Example #3
Source File: CookieHttpClientTest.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
CookieHttpClientTest() throws Exception {
    /* start the server */
    ss = new ServerSocket(0);
    (new Thread(this)).start();

    URL url = new URL("http://localhost:" + ss.getLocalPort() +"/");

    // Run without a CookieHandler first
    InputStream in = url.openConnection().getInputStream();
    while (in.read() != -1);  // read response body so connection can be reused

    // Set a CookeHandler and retest using the HttpClient from the KAC
    CookieManager manager = new CookieManager(null, CookiePolicy.ACCEPT_ALL);
    CookieHandler.setDefault(manager);

    in = url.openConnection().getInputStream();
    while (in.read() != -1);

    if (manager.getCookieStore().getCookies().isEmpty()) {
        throw new RuntimeException("Failed: No cookies in the cookie Handler.");
    }
}
 
Example #4
Source File: AuthCookie.java    From utexas-utilities with Apache License 2.0 6 votes vote down vote up
protected void setAuthCookieVal(String authCookie, String domain) {
    this.authCookie = authCookie;
    settings.edit().putString(prefKey, authCookie).apply();

    /*
    this is technically unnecessary if OkHttp handled the authentication, because it will
    have already set the cookies in the CookieHandler. It doesn't seem to cause any issues
    just to re-add the cookies, though
     */
    HttpCookie httpCookie = new HttpCookie(authCookieKey, authCookie);
    httpCookie.setDomain(domain);
    try {
        CookieStore cookies = ((CookieManager) CookieHandler.getDefault()).getCookieStore();
        cookies.add(URI.create(domain), httpCookie);
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    }
    cookieHasBeenSet = true;
    android.webkit.CookieManager.getInstance().setCookie(domain, httpCookie.getName() + "=" + httpCookie.getValue());
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
        android.webkit.CookieManager.getInstance().flush();
    } else {
        CookieSyncManager.getInstance().sync();
    }
}
 
Example #5
Source File: AbstractCookiesTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
public void testSendingCookiesFromStore() throws Exception {
    server.enqueue(new MockResponse());
    server.play();

    CookieManager cookieManager = new CookieManager(createCookieStore(),
            ACCEPT_ORIGINAL_SERVER);
    HttpCookie cookieA = createCookie("a", "android", server.getCookieDomain(), "/");
    cookieManager.getCookieStore().add(server.getUrl("/").toURI(), cookieA);
    HttpCookie cookieB = createCookie("b", "banana", server.getCookieDomain(), "/");
    cookieManager.getCookieStore().add(server.getUrl("/").toURI(), cookieB);
    CookieHandler.setDefault(cookieManager);

    get(server, "/");
    RecordedRequest request = server.takeRequest();

    List<String> receivedHeaders = request.getHeaders();
    assertContains(receivedHeaders, "Cookie: $Version=\"1\"; "
            + "a=\"android\";$Path=\"/\";$Domain=\"" + server.getCookieDomain() + "\"; "
            + "b=\"banana\";$Path=\"/\";$Domain=\"" + server.getCookieDomain() + "\"");
}
 
Example #6
Source File: OkHttpClientManager.java    From BlueBoard with Apache License 2.0 6 votes vote down vote up
public static OkHttpClient getsInstance() {
    if (sInstance == null) {
        synchronized (OkHttpClientManager.class) {
            if (sInstance == null) {
                sInstance = new com.squareup.okhttp.OkHttpClient();
                // cookie enabled
                sInstance.setCookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_ORIGINAL_SERVER));
                // timeout reading data from the host
                sInstance.setReadTimeout(15, TimeUnit.SECONDS);
                // timeout connection host
                sInstance.setConnectTimeout(20, TimeUnit.SECONDS);
            }
        }
    }
    return sInstance;
}
 
Example #7
Source File: AbstractCookiesTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
private static void assertManagerCookiesMatch(CookieManager cookieManager, String url,
    String expectedCookieRequestHeader) throws Exception {

    Map<String, List<String>> cookieHeaders =
            cookieManager.get(new URI(url), EMPTY_COOKIES_MAP);
    if (expectedCookieRequestHeader == null) {
        assertTrue(cookieHeaders.isEmpty());
        return;
    }

    assertEquals(1, cookieHeaders.size());
    List<String> actualCookieHeaderStrings = cookieHeaders.get("Cookie");

    // For simplicity, we concatenate the cookie header strings if there are multiple ones.
    String actualCookieRequestHeader = actualCookieHeaderStrings.get(0);
    for (int i = 1; i < actualCookieHeaderStrings.size(); i++) {
        actualCookieRequestHeader += "; " + actualCookieHeaderStrings.get(i);
    }
    assertEquals(expectedCookieRequestHeader, actualCookieRequestHeader);
}
 
Example #8
Source File: OkHttpUtils.java    From NewsMe with Apache License 2.0 6 votes vote down vote up
private OkHttpUtils()
{
    mOkHttpClient = new OkHttpClient();
    //cookie enabled
    mOkHttpClient.setCookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_ORIGINAL_SERVER));
    mDelivery = new Handler(Looper.getMainLooper());


    if (true)
    {
        mOkHttpClient.setHostnameVerifier(new HostnameVerifier()
        {
            @Override
            public boolean verify(String hostname, SSLSession session)
            {
                return true;
            }
        });
    }


}
 
Example #9
Source File: OsioKeycloakTestAuthServiceClient.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
private String loginAndGetFormPostURL()
    throws IOException, MalformedURLException, ProtocolException {
  CookieManager cookieManager = new CookieManager();
  CookieHandler.setDefault(cookieManager);
  HttpURLConnection conn =
      (HttpURLConnection)
          new URL(osioAuthEndpoint + "/api/login?redirect=https://che.openshift.io")
              .openConnection();
  conn.setRequestMethod("GET");

  String htmlOutput = IOUtils.toString(conn.getInputStream());
  Pattern p = Pattern.compile("action=\"(.*?)\"");
  Matcher m = p.matcher(htmlOutput);
  if (m.find()) {
    String formPostURL = StringEscapeUtils.unescapeHtml(m.group(1));
    return formPostURL;
  } else {
    LOG.error("Unable to login - didn't find URL to send login form to.");
    throw new RuntimeException("Unable to login - didn't find URL to send login form to.");
  }
}
 
Example #10
Source File: AbstractCookiesTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
public void testCookieStoreNullUris() {
    CookieStore cookieStore = new CookieManager(createCookieStore(), null).getCookieStore();
    HttpCookie cookieA = createCookie("a", "android", ".android.com", "/source");
    HttpCookie cookieB = createCookie("b", "banana", "code.google.com", "/p/android");

    cookieStore.add(null, cookieA);
    assertEquals(Arrays.asList(cookieA), cookieStore.getCookies());
    cookieStore.add(null, cookieB);
    assertEquals(Arrays.asList(cookieA, cookieB), cookieStore.getCookies());

    try {
        cookieStore.get(null);
        fail();
    } catch (NullPointerException expected) {
    }

    assertEquals(Collections.<URI>emptyList(), cookieStore.getURIs());
    assertTrue(cookieStore.remove(null, cookieA));
    assertEquals(Arrays.asList(cookieB), cookieStore.getCookies());

    assertTrue(cookieStore.removeAll());
    assertEquals(Collections.<URI>emptyList(), cookieStore.getURIs());
    assertEquals(Collections.<HttpCookie>emptyList(), cookieStore.getCookies());
}
 
Example #11
Source File: CookieHttpClientTest.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
CookieHttpClientTest() throws Exception {
    /* start the server */
    ss = new ServerSocket(0);
    (new Thread(this)).start();

    URL url = new URL("http://localhost:" + ss.getLocalPort() +"/");

    // Run without a CookieHandler first
    InputStream in = url.openConnection().getInputStream();
    while (in.read() != -1);  // read response body so connection can be reused

    // Set a CookeHandler and retest using the HttpClient from the KAC
    CookieManager manager = new CookieManager(null, CookiePolicy.ACCEPT_ALL);
    CookieHandler.setDefault(manager);

    in = url.openConnection().getInputStream();
    while (in.read() != -1);

    if (manager.getCookieStore().getCookies().isEmpty()) {
        throw new RuntimeException("Failed: No cookies in the cookie Handler.");
    }
}
 
Example #12
Source File: ApiClient.java    From director-sdk with Apache License 2.0 6 votes vote down vote up
public ApiClient() {
    httpClient = new OkHttpClient();
    httpClient.setCookieHandler(new CookieManager());


    verifyingSsl = true;

    json = new JSON();

    // Set default User-Agent.
    setUserAgent("Swagger-Codegen/6.3.0/java");

    // Setup authentications (key: authentication name, value: authentication).
    authentications = new HashMap<String, Authentication>();
    authentications.put("basic", new HttpBasicAuth());
    // Prevent the authentications from being modified.
    authentications = Collections.unmodifiableMap(authentications);

    addDefaultHeader(CLIENT_HEADER, "SDK-Java");
}
 
Example #13
Source File: AuthCookie.java    From utexas-utilities with Apache License 2.0 6 votes vote down vote up
private void resetCookie() {
    settings.edit().remove(prefKey).apply();
    authCookie = "";
    try {
        /*
        This step is *required* for PNA, and nicety for other services. PNA won't let you
        log in if you're still holding on to a valid authcookie, so we clear them out.
         */
        URI loginURI = URI.create(url.getHost());
        CookieStore cookies = ((CookieManager) CookieHandler.getDefault()).getCookieStore();
        for (HttpCookie cookie : cookies.get(loginURI)) {
            cookies.remove(loginURI, cookie);
        }
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    }
    cookieHasBeenSet = false;
}
 
Example #14
Source File: RestClient.java    From botbuilder-java with MIT License 6 votes vote down vote up
/**
 * Creates an instance of the builder with a base URL and 2 custom builders.
 *
 * @param httpClientBuilder the builder to build an {@link OkHttpClient}.
 * @param retrofitBuilder the builder to build a {@link Retrofit}.
 */
public Builder(OkHttpClient.Builder httpClientBuilder, Retrofit.Builder retrofitBuilder) {
    if (httpClientBuilder == null) {
        throw new IllegalArgumentException("httpClientBuilder == null");
    }
    if (retrofitBuilder == null) {
        throw new IllegalArgumentException("retrofitBuilder == null");
    }
    CookieManager cookieManager = new CookieManager();
    cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
    customHeadersInterceptor = new CustomHeadersInterceptor();
    // Set up OkHttp client
    this.httpClientBuilder = httpClientBuilder
            .cookieJar(new JavaNetCookieJar(cookieManager))
            .readTimeout(120, TimeUnit.SECONDS)
            .connectTimeout(60, TimeUnit.SECONDS)
            .addInterceptor(new RequestIdHeaderInterceptor())
            .addInterceptor(new BaseUrlHandler());
    this.retrofitBuilder = retrofitBuilder;
    this.loggingInterceptor = new LoggingInterceptor(LogLevel.NONE);
    this.useHttpClientThreadPool = false;
}
 
Example #15
Source File: CookieHttpClientTest.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
CookieHttpClientTest() throws Exception {
    /* start the server */
    ss = new ServerSocket(0);
    (new Thread(this)).start();

    URL url = new URL("http://localhost:" + ss.getLocalPort() +"/");

    // Run without a CookieHandler first
    InputStream in = url.openConnection().getInputStream();
    while (in.read() != -1);  // read response body so connection can be reused

    // Set a CookeHandler and retest using the HttpClient from the KAC
    CookieManager manager = new CookieManager(null, CookiePolicy.ACCEPT_ALL);
    CookieHandler.setDefault(manager);

    in = url.openConnection().getInputStream();
    while (in.read() != -1);

    if (manager.getCookieStore().getCookies().isEmpty()) {
        throw new RuntimeException("Failed: No cookies in the cookie Handler.");
    }
}
 
Example #16
Source File: CookieHttpClientTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
CookieHttpClientTest() throws Exception {
    /* start the server */
    ss = new ServerSocket(0);
    (new Thread(this)).start();

    URL url = new URL("http://localhost:" + ss.getLocalPort() +"/");

    // Run without a CookieHandler first
    InputStream in = url.openConnection().getInputStream();
    while (in.read() != -1);  // read response body so connection can be reused

    // Set a CookeHandler and retest using the HttpClient from the KAC
    CookieManager manager = new CookieManager(null, CookiePolicy.ACCEPT_ALL);
    CookieHandler.setDefault(manager);

    in = url.openConnection().getInputStream();
    while (in.read() != -1);

    if (manager.getCookieStore().getCookies().isEmpty()) {
        throw new RuntimeException("Failed: No cookies in the cookie Handler.");
    }
}
 
Example #17
Source File: AbstractCookiesTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
public void testClearingWithMaxAge0() throws Exception {
    CookieManager cm = new CookieManager(createCookieStore(), null);

    URI uri = URI.create("https://test.com");
    Map<String, List<String>> header = new HashMap<>();
    List<String> value = new ArrayList<>();

    value.add("cookie=1234567890test; domain=.test.com; path=/; " +
              "expires=Fri, 31 Dec 9999 04:01:25 GMT-0000");
    header.put("Set-Cookie", value);
    cm.put(uri, header);

    List<HttpCookie> cookies = cm.getCookieStore().getCookies();
    assertEquals(1, cookies.size());

    value.clear();
    header.clear();
    value.add("cookie=1234567890test; domain=.test.com; path=/; " +
              "max-age=0");
    header.put("Set-Cookie", value);
    cm.put(uri, header);

    cookies = cm.getCookieStore().getCookies();
    assertEquals(0, cookies.size());
}
 
Example #18
Source File: CookieFilter.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Override
public HttpRequestImpl response(Response r) throws IOException {
    HttpHeaders hdrs = r.headers();
    HttpRequestImpl request = r.request();
    Exchange<?> e = r.exchange;
    Log.logTrace("Response: processing cookies for {0}", request.uri());
    Optional<CookieManager> cookieManOpt = e.client().cookieManager();
    if (cookieManOpt.isPresent()) {
        CookieManager cookieMan = cookieManOpt.get();
        Log.logTrace("Response: parsing cookies from {0}", hdrs.map());
        cookieMan.put(request.uri(), hdrs.map());
    } else {
        Log.logTrace("Response: No cookie manager found for {0}",
                     request.uri());
    }
    return null;
}
 
Example #19
Source File: HttpClientUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void shouldNotStoreCookieWhenPolicyAcceptNone() throws URISyntaxException, IOException, InterruptedException {
    HttpRequest request = HttpRequest.newBuilder()
        .uri(new URI("https://postman-echo.com/get"))
        .GET()
        .build();

    HttpClient httpClient = HttpClient.newBuilder()
        .cookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_NONE))
        .build();

    httpClient.send(request, HttpResponse.BodyHandlers.ofString());

    assertTrue(httpClient.cookieHandler()
        .isPresent());
}
 
Example #20
Source File: NullUriCookieTest.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
static void checkCookieNullUri() throws Exception {
    //get a cookie store implementation and add a cookie to the store with null URI
    CookieStore cookieStore = (new CookieManager()).getCookieStore();
    //Check if removeAll() retrurns false on an empty CookieStore
    if (cookieStore.removeAll()) {
        fail = true;
    }
    checkFail("removeAll on empty store should return false");
    HttpCookie cookie = new HttpCookie("MY_COOKIE", "MY_COOKIE_VALUE");
    cookie.setDomain("foo.com");
    cookieStore.add(null, cookie);

    //Retrieve added cookie
    URI uri = new URI("http://foo.com");
    List<HttpCookie> addedCookieList = cookieStore.get(uri);

    //Verify CookieStore behaves well
    if (addedCookieList.size() != 1) {
       fail = true;
    }
    checkFail("Abnormal size of cookie jar");

    for (HttpCookie chip : addedCookieList) {
        if (!chip.equals(cookie)) {
             fail = true;
        }
    }
    checkFail("Cookie not retrieved from Cookie Jar");
    boolean ret = cookieStore.remove(null,cookie);
    if (!ret) {
        fail = true;
    }
    checkFail("Abnormal removal behaviour from Cookie Jar");
}
 
Example #21
Source File: LibrariesTest.java    From appengine-plugins-core with Apache License 2.0 5 votes vote down vote up
@Before
public void parseJson() {
  oldCookieHandler = CookieHandler.getDefault();
  // https://github.com/GoogleCloudPlatform/appengine-plugins-core/issues/822
  CookieHandler.setDefault(new CookieManager());

  JsonReaderFactory factory = Json.createReaderFactory(null);
  InputStream in = LibrariesTest.class.getResourceAsStream("libraries.json");
  JsonReader reader = factory.createReader(in);
  apis = reader.readArray().toArray(new JsonObject[0]);
}
 
Example #22
Source File: NullUriCookieTest.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
static void checkCookieNullUri() throws Exception {
    //get a cookie store implementation and add a cookie to the store with null URI
    CookieStore cookieStore = (new CookieManager()).getCookieStore();
    //Check if removeAll() retrurns false on an empty CookieStore
    if (cookieStore.removeAll()) {
        fail = true;
    }
    checkFail("removeAll on empty store should return false");
    HttpCookie cookie = new HttpCookie("MY_COOKIE", "MY_COOKIE_VALUE");
    cookie.setDomain("foo.com");
    cookieStore.add(null, cookie);

    //Retrieve added cookie
    URI uri = new URI("http://foo.com");
    List<HttpCookie> addedCookieList = cookieStore.get(uri);

    //Verify CookieStore behaves well
    if (addedCookieList.size() != 1) {
       fail = true;
    }
    checkFail("Abnormal size of cookie jar");

    for (HttpCookie chip : addedCookieList) {
        if (!chip.equals(cookie)) {
             fail = true;
        }
    }
    checkFail("Cookie not retrieved from Cookie Jar");
    boolean ret = cookieStore.remove(null,cookie);
    if (!ret) {
        fail = true;
    }
    checkFail("Abnormal removal behaviour from Cookie Jar");
}
 
Example #23
Source File: AbstractCookiesTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void testCookieStoreGet() throws Exception {
    CookieStore cookieStore = new CookieManager(createCookieStore(), null).getCookieStore();
    HttpCookie cookiePort1 = createCookie("a1", "android", "a.com", "/path1");
    HttpCookie cookiePort2 = createCookie("a2", "android", "a.com", "/path2");
    HttpCookie secureCookie = createCookie("a3", "android", "a.com", "/path3");
    secureCookie.setSecure(true);
    HttpCookie notSecureCookie = createCookie("a4", "android", "a.com", "/path4");

    HttpCookie bCookie = createCookie("b1", "android", "b.com", "/path5");

    cookieStore.add(new URI("http://a.com:443/path1"), cookiePort1);
    cookieStore.add(new URI("http://a.com:8080/path2"), cookiePort2);
    cookieStore.add(new URI("https://a.com:443/path3"), secureCookie);
    cookieStore.add(new URI("https://a.com:443/path4"), notSecureCookie);
    cookieStore.add(new URI("https://b.com:8080/path5"), bCookie);

    List<HttpCookie> expectedStoreCookies = new ArrayList<>();
    expectedStoreCookies.add(cookiePort1);
    expectedStoreCookies.add(cookiePort2);
    expectedStoreCookies.add(secureCookie);
    expectedStoreCookies.add(notSecureCookie);

    // The default CookieStore implementation on Android is currently responsible for matching
    // the host/domain but not handling other cookie rules: it ignores the scheme (e.g. "secure"
    // checks), port and path.
    // The tests below fail on the RI. It looks like in the RI it is CookieStoreImpl that is
    // enforcing "secure" checks.
    assertEquals(expectedStoreCookies, cookieStore.get(new URI("http://a.com:443/anypath")));
    assertEquals(expectedStoreCookies, cookieStore.get(new URI("http://a.com:8080/anypath")));
    assertEquals(expectedStoreCookies, cookieStore.get(new URI("https://a.com/anypath")));
    assertEquals(expectedStoreCookies, cookieStore.get(new URI("http://a.com/anypath")));
}
 
Example #24
Source File: NullUriCookieTest.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
static void checkCookieNullUri() throws Exception {
    //get a cookie store implementation and add a cookie to the store with null URI
    CookieStore cookieStore = (new CookieManager()).getCookieStore();
    //Check if removeAll() retrurns false on an empty CookieStore
    if (cookieStore.removeAll()) {
        fail = true;
    }
    checkFail("removeAll on empty store should return false");
    HttpCookie cookie = new HttpCookie("MY_COOKIE", "MY_COOKIE_VALUE");
    cookie.setDomain("foo.com");
    cookieStore.add(null, cookie);

    //Retrieve added cookie
    URI uri = new URI("http://foo.com");
    List<HttpCookie> addedCookieList = cookieStore.get(uri);

    //Verify CookieStore behaves well
    if (addedCookieList.size() != 1) {
       fail = true;
    }
    checkFail("Abnormal size of cookie jar");

    for (HttpCookie chip : addedCookieList) {
        if (!chip.equals(cookie)) {
             fail = true;
        }
    }
    checkFail("Cookie not retrieved from Cookie Jar");
    boolean ret = cookieStore.remove(null,cookie);
    if (!ret) {
        fail = true;
    }
    checkFail("Abnormal removal behaviour from Cookie Jar");
}
 
Example #25
Source File: AbstractCookiesTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@Override public void setUp() throws Exception {
    super.setUp();
    server = new MockWebServer();
    defaultHandler = CookieHandler.getDefault();
    cookieManager = new CookieManager(createCookieStore(), null);
    cookieStore = cookieManager.getCookieStore();
}
 
Example #26
Source File: HttpOnly.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
void populateCookieStore(URI uri)
        throws IOException {

    CookieManager cm = new CookieManager(null, CookiePolicy.ACCEPT_ALL);
    CookieHandler.setDefault(cm);
    Map<String,List<String>> header = new HashMap<>();
    List<String> values = new ArrayList<>();
    values.add("JSESSIONID=" + SESSION_ID + "; version=1; Path="
               + URI_PATH +"; HttpOnly");
    values.add("CUSTOMER=WILE_E_COYOTE; version=1; Path=" + URI_PATH);
    header.put("Set-Cookie", values);
    cm.put(uri, header);
}
 
Example #27
Source File: CookieHttpsClientTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
void doClientSide() throws Exception {
    // Wait for server to get started.
    while (!serverReady) {
        Thread.sleep(50);
    }

    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }});

    URL url = new URL("https://localhost:" + serverPort +"/");

    // Run without a CookieHandler first
    InputStream in = url.openConnection().getInputStream();
    while (in.read() != -1);  // read response body so connection can be reused

    // Set a CookeHandler and retest using the HttpClient from the KAC
    CookieManager manager = new CookieManager(null, CookiePolicy.ACCEPT_ALL);
    CookieHandler.setDefault(manager);

    in = url.openConnection().getInputStream();
    while (in.read() != -1);

    if (manager.getCookieStore().getCookies().isEmpty()) {
        throw new RuntimeException("Failed: No cookies in the cookie Handler.");
    }
}
 
Example #28
Source File: CookieHttpClientTest.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
CookieHttpClientTest() throws Exception {
    /* start the server */
    ss = new ServerSocket(0);
    (new Thread(this)).start();

    URL url = new URL("http://localhost:" + ss.getLocalPort() +"/");

    // Run without a CookieHandler first
    InputStream in = url.openConnection().getInputStream();
    while (in.read() != -1);  // read response body so connection can be reused

    // Set a CookeHandler and retest using the HttpClient from the KAC
    CookieManager manager = new CookieManager(null, CookiePolicy.ACCEPT_ALL);
    CookieHandler.setDefault(manager);

    in = url.openConnection().getInputStream();
    while (in.read() != -1);

    if (manager.getCookieStore().getCookies().isEmpty()) {
        throw new RuntimeException("Failed: No cookies in the cookie Handler.");
    }
}
 
Example #29
Source File: AbstractCookiesTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private void checkValidParams4Put(URI uri,
                                         Map<String, List<String>> map) throws IOException {
    CookieManager manager = new CookieManager(createCookieStore(), null);
    try {
        manager.put(uri, map);
        fail("Should throw IllegalArgumentException");
    } catch (IllegalArgumentException e) {
        // expected
    }

}
 
Example #30
Source File: TestWebUi.java    From presto with Apache License 2.0 5 votes vote down vote up
private void testLogIn(URI baseUri, boolean sendPassword)
        throws Exception
{
    CookieManager cookieManager = new CookieManager();
    OkHttpClient client = this.client.newBuilder()
            .cookieJar(new JavaNetCookieJar(cookieManager))
            .build();

    String body = assertOk(client, getLoginHtmlLocation(baseUri))
            .orElseThrow(() -> new AssertionError("No response body"));
    assertThat(body).contains("action=\"/ui/login\"");
    assertThat(body).contains("method=\"post\"");

    assertThat(body).doesNotContain("// This value will be replaced");
    if (sendPassword) {
        assertThat(body).contains("var hidePassword = false;");
    }
    else {
        assertThat(body).contains("var hidePassword = true;");
    }

    logIn(baseUri, client, sendPassword);
    HttpCookie cookie = getOnlyElement(cookieManager.getCookieStore().getCookies());
    assertEquals(cookie.getPath(), "/ui");
    assertEquals(cookie.getDomain(), baseUri.getHost());
    assertEquals(cookie.getMaxAge(), -1);
    assertTrue(cookie.isHttpOnly());

    assertOk(client, getUiLocation(baseUri));

    assertOk(client, getValidApiLocation(baseUri));

    assertResponseCode(client, getLocation(baseUri, "/ui/unknown"), SC_NOT_FOUND);

    assertResponseCode(client, getLocation(baseUri, "/ui/api/unknown"), SC_NOT_FOUND);
    assertRedirect(client, getLogoutLocation(baseUri), getLoginHtmlLocation(baseUri), false);
    assertThat(cookieManager.getCookieStore().getCookies()).isEmpty();
}