Example usage for java.net CookieHandler setDefault

List of usage examples for java.net CookieHandler setDefault

Introduction

In this page you can find the example usage for java.net CookieHandler setDefault.

Prototype

public static synchronized void setDefault(CookieHandler cHandler) 

Source Link

Document

Sets (or unsets) the system-wide cookie handler.

Usage

From source file:test.be.fedict.eid.applet.ControllerTest.java

@Test
public void controllerKioskMode() throws Exception {
    // setup/*from   ww  w.jav  a  2s .com*/
    Messages messages = new Messages(Locale.getDefault());
    Runtime runtime = new TestRuntime();
    View view = new TestView();
    Controller controller = new Controller(view, runtime, messages);

    // make sure that the session cookies are passed during conversations
    CookieManager cookieManager = new CookieManager();
    cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
    CookieHandler.setDefault(cookieManager);

    this.servletHolder.setInitParameter("Kiosk", "true");

    // operate
    controller.run();

    // verify
    LOG.debug("verify...");
}

From source file:test.be.fedict.eid.applet.ControllerTest.java

@Test
public void controllerAuthentication() throws Exception {
    // setup//from  ww w . ja v a 2  s  .  co m
    Messages messages = new Messages(Locale.getDefault());
    Runtime runtime = new TestRuntime();
    View view = new TestView();
    Controller controller = new Controller(view, runtime, messages);

    // make sure that the session cookies are passed during conversations
    CookieManager cookieManager = new CookieManager();
    cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
    CookieHandler.setDefault(cookieManager);

    this.servletHolder.setInitParameter("AuthenticationServiceClass",
            TestAuthenticationService.class.getName());
    this.servletHolder.setInitParameter("Logoff", "true");

    // operate
    controller.run();

    // verify
    LOG.debug("verify...");
    SessionHandler sessionHandler = this.servletTester.getContext().getSessionHandler();
    SessionManager sessionManager = sessionHandler.getSessionManager();
    LOG.debug("session manager type: " + sessionManager.getClass().getName());
    HashSessionManager hashSessionManager = (HashSessionManager) sessionManager;
    LOG.debug("# sessions: " + hashSessionManager.getSessions());
    assertEquals(1, hashSessionManager.getSessions());
    Map<String, HttpSession> sessionMap = hashSessionManager.getSessionMap();
    LOG.debug("session map: " + sessionMap);
    Entry<String, HttpSession> sessionEntry = sessionMap.entrySet().iterator().next();
    HttpSession httpSession = sessionEntry.getValue();
    assertNotNull(httpSession.getAttribute("eid"));
    assertNull(httpSession.getAttribute("eid.identity"));
    assertNull(httpSession.getAttribute("eid.address"));
    assertNull(httpSession.getAttribute("eid.photo"));
    String identifier = (String) httpSession.getAttribute("eid.identifier");
    assertNotNull(identifier);
    LOG.debug("identifier: " + identifier);
    assertTrue(TestAuthenticationService.called);
}

From source file:test.be.fedict.eid.applet.ControllerTest.java

@Test
public void testAuthnSessionIdChannelBinding() throws Exception {
    // setup/*from   w  w w .  j av a  2  s .  c  o m*/
    Messages messages = new Messages(Locale.getDefault());
    Runtime runtime = new TestRuntime();
    View view = new TestView();
    Controller controller = new Controller(view, runtime, messages);

    // make sure that the session cookies are passed during conversations
    CookieManager cookieManager = new CookieManager();
    cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
    CookieHandler.setDefault(cookieManager);

    this.servletHolder.setInitParameter("AuthenticationServiceClass",
            TestAuthenticationService.class.getName());
    this.servletHolder.setInitParameter("Logoff", "true");
    this.servletHolder.setInitParameter("SessionIdChannelBinding", "true");

    // operate
    controller.run();

    // verify
    LOG.debug("verify...");
    SessionHandler sessionHandler = this.servletTester.getContext().getSessionHandler();
    SessionManager sessionManager = sessionHandler.getSessionManager();
    LOG.debug("session manager type: " + sessionManager.getClass().getName());
    HashSessionManager hashSessionManager = (HashSessionManager) sessionManager;
    LOG.debug("# sessions: " + hashSessionManager.getSessions());
    assertEquals(1, hashSessionManager.getSessions());
    Map<String, HttpSession> sessionMap = hashSessionManager.getSessionMap();
    LOG.debug("session map: " + sessionMap);
    Entry<String, HttpSession> sessionEntry = sessionMap.entrySet().iterator().next();
    HttpSession httpSession = sessionEntry.getValue();
    assertNotNull(httpSession.getAttribute("eid"));
    assertNull(httpSession.getAttribute("eid.identity"));
    assertNull(httpSession.getAttribute("eid.address"));
    assertNull(httpSession.getAttribute("eid.photo"));
    String identifier = (String) httpSession.getAttribute("eid.identifier");
    assertNotNull(identifier);
    LOG.debug("identifier: " + identifier);
    assertTrue(TestAuthenticationService.called);
}

From source file:piuk.blockchain.android.WalletApplication.java

@Override
public void onCreate() {
    super.onCreate();

    PRNGFixes.apply();//w w  w.j  ava 2  s . com

    //      ErrorReporter.getInstance().init(this);

    //blockchainServiceIntent = new Intent(this, BlockchainServiceImpl.class);
    websocketServiceIntent = new Intent(this, WebsocketService.class);

    System.setProperty("device_name", "android");

    try {
        PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);

        System.setProperty("device_version", pInfo.versionName);
    } catch (NameNotFoundException e1) {
        e1.printStackTrace();
    }

    try {
        // Need to save session cookie for kaptcha
        CookieHandler.setDefault(new CookieManager());

        Security.addProvider(new org.spongycastle.jce.provider.BouncyCastleProvider());
    } catch (Throwable e) {
        e.printStackTrace();
    }

    //loadBitcoinJWallet();

    connect();
}

From source file:test.be.fedict.eid.applet.ControllerTest.java

@Test
public void testAuthnServerCertificateChannelBinding() throws Exception {
    // setup/*  w  w  w  .j  a v  a 2 s . co  m*/
    Messages messages = new Messages(Locale.getDefault());
    Runtime runtime = new TestRuntime();
    View view = new TestView();
    Controller controller = new Controller(view, runtime, messages);

    // make sure that the session cookies are passed during conversations
    CookieManager cookieManager = new CookieManager();
    cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
    CookieHandler.setDefault(cookieManager);

    this.servletHolder.setInitParameter("AuthenticationServiceClass",
            TestAuthenticationService.class.getName());
    this.servletHolder.setInitParameter("Logoff", "true");
    File tmpCertFile = File.createTempFile("ssl-server-cert-", ".crt");
    FileUtils.writeByteArrayToFile(tmpCertFile, this.certificate.getEncoded());
    this.servletHolder.setInitParameter("ChannelBindingServerCertificate", tmpCertFile.toString());

    // operate
    controller.run();

    // verify
    LOG.debug("verify...");
    SessionHandler sessionHandler = this.servletTester.getContext().getSessionHandler();
    SessionManager sessionManager = sessionHandler.getSessionManager();
    LOG.debug("session manager type: " + sessionManager.getClass().getName());
    HashSessionManager hashSessionManager = (HashSessionManager) sessionManager;
    LOG.debug("# sessions: " + hashSessionManager.getSessions());
    assertEquals(1, hashSessionManager.getSessions());
    Map<String, HttpSession> sessionMap = hashSessionManager.getSessionMap();
    LOG.debug("session map: " + sessionMap);
    Entry<String, HttpSession> sessionEntry = sessionMap.entrySet().iterator().next();
    HttpSession httpSession = sessionEntry.getValue();
    assertNotNull(httpSession.getAttribute("eid"));
    assertNull(httpSession.getAttribute("eid.identity"));
    assertNull(httpSession.getAttribute("eid.address"));
    assertNull(httpSession.getAttribute("eid.photo"));
    String identifier = (String) httpSession.getAttribute("eid.identifier");
    assertNotNull(identifier);
    LOG.debug("identifier: " + identifier);
    assertTrue(TestAuthenticationService.called);
}

From source file:org.opendatakit.services.sync.service.logic.HttpRestProtocolWrapper.java

public HttpRestProtocolWrapper(SyncExecutionContext sc) throws InvalidAuthTokenException {
    this.sc = sc;
    this.log = WebLogger.getLogger(sc.getAppName());
    log.e(LOGTAG, "AggregateUri:" + sc.getAggregateUri());
    this.baseUri = normalizeUri(sc.getAggregateUri(), "/");
    log.e(LOGTAG, "baseUri:" + baseUri);

    // This is technically not correct, as we should really have a global
    // that we manage for this... If there are two or more service threads
    // running, we could forget other session cookies. But, by creating a 
    // new cookie manager here, we ensure that we don't have any stale 
    // session cookies at the start of each sync.

    cm = new CookieManager();
    CookieHandler.setDefault(cm);

    // HttpClient for auth tokens
    localAuthContext = new BasicHttpContext();

    SocketConfig socketAuthConfig = SocketConfig.copy(SocketConfig.DEFAULT).setSoTimeout(2 * CONNECTION_TIMEOUT)
            .build();//from   w w  w .  j av  a2 s  . c o  m

    RequestConfig requestAuthConfig = RequestConfig.copy(RequestConfig.DEFAULT)
            .setConnectTimeout(CONNECTION_TIMEOUT)
            // support authenticating
            .setAuthenticationEnabled(true)
            // support redirecting to handle http: => https: transition
            .setRedirectsEnabled(true)
            // max redirects is set to 4
            .setMaxRedirects(4).setCircularRedirectsAllowed(true)
            //.setTargetPreferredAuthSchemes(targetPreferredAuthSchemes)
            .setCookieSpec(CookieSpecs.DEFAULT).build();

    httpAuthClient = HttpClientBuilder.create().setDefaultSocketConfig(socketAuthConfig)
            .setDefaultRequestConfig(requestAuthConfig).build();

    // Context
    // context holds authentication state machine, so it cannot be
    // shared across independent activities.
    localContext = new BasicHttpContext();

    cookieStore = new BasicCookieStore();
    credsProvider = new BasicCredentialsProvider();

    String host = this.baseUri.getHost();
    String authenticationType = sc.getAuthenticationType();

    if (sc.getString(R.string.credential_type_google_account).equals(authenticationType)) {

        String accessToken = sc.getAccessToken();
        checkAccessToken(accessToken);
        this.accessToken = accessToken;

    } else if (sc.getString(R.string.credential_type_username_password).equals(authenticationType)) {
        String username = sc.getUsername();
        String password = sc.getPassword();

        List<AuthScope> asList = new ArrayList<AuthScope>();
        {
            AuthScope a;
            // allow digest auth on any port...
            a = new AuthScope(host, -1, null, AuthSchemes.DIGEST);
            asList.add(a);
            // and allow basic auth on the standard TLS/SSL ports...
            a = new AuthScope(host, 443, null, AuthSchemes.BASIC);
            asList.add(a);
            a = new AuthScope(host, 8443, null, AuthSchemes.BASIC);
            asList.add(a);
        }

        // add username
        if (username != null && username.trim().length() != 0) {
            log.i(LOGTAG, "adding credential for host: " + host + " username:" + username);
            Credentials c = new UsernamePasswordCredentials(username, password);

            for (AuthScope a : asList) {
                credsProvider.setCredentials(a, c);
            }
        }
    }

    localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
    localContext.setAttribute(HttpClientContext.CREDS_PROVIDER, credsProvider);

    SocketConfig socketConfig = SocketConfig.copy(SocketConfig.DEFAULT).setSoTimeout(2 * CONNECTION_TIMEOUT)
            .build();

    // if possible, bias toward digest auth (may not be in 4.0 beta 2)
    List<String> targetPreferredAuthSchemes = new ArrayList<String>();
    targetPreferredAuthSchemes.add(AuthSchemes.DIGEST);
    targetPreferredAuthSchemes.add(AuthSchemes.BASIC);

    RequestConfig requestConfig = RequestConfig.copy(RequestConfig.DEFAULT)
            .setConnectTimeout(CONNECTION_TIMEOUT)
            // support authenticating
            .setAuthenticationEnabled(true)
            // support redirecting to handle http: => https: transition
            .setRedirectsEnabled(true)
            // max redirects is set to 4
            .setMaxRedirects(4).setCircularRedirectsAllowed(true)
            .setTargetPreferredAuthSchemes(targetPreferredAuthSchemes).setCookieSpec(CookieSpecs.DEFAULT)
            .build();

    httpClient = HttpClientBuilder.create().setDefaultSocketConfig(socketConfig)
            .setDefaultRequestConfig(requestConfig).build();

}

From source file:test.be.fedict.eid.applet.ControllerTest.java

@Test
public void testAuthnHybridChannelBinding() throws Exception {
    // setup//  www . j a va 2  s .co  m
    Messages messages = new Messages(Locale.getDefault());
    Runtime runtime = new TestRuntime();
    View view = new TestView();
    Controller controller = new Controller(view, runtime, messages);

    // make sure that the session cookies are passed during conversations
    CookieManager cookieManager = new CookieManager();
    cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
    CookieHandler.setDefault(cookieManager);

    this.servletHolder.setInitParameter("AuthenticationServiceClass",
            TestAuthenticationService.class.getName());
    this.servletHolder.setInitParameter("Logoff", "true");
    File tmpCertFile = File.createTempFile("ssl-server-cert-", ".crt");
    FileUtils.writeByteArrayToFile(tmpCertFile, this.certificate.getEncoded());
    this.servletHolder.setInitParameter("ChannelBindingServerCertificate", tmpCertFile.toString());
    this.servletHolder.setInitParameter("SessionIdChannelBinding", "true");

    // operate
    controller.run();

    // verify
    LOG.debug("verify...");
    SessionHandler sessionHandler = this.servletTester.getContext().getSessionHandler();
    SessionManager sessionManager = sessionHandler.getSessionManager();
    LOG.debug("session manager type: " + sessionManager.getClass().getName());
    HashSessionManager hashSessionManager = (HashSessionManager) sessionManager;
    LOG.debug("# sessions: " + hashSessionManager.getSessions());
    assertEquals(1, hashSessionManager.getSessions());
    Map<String, HttpSession> sessionMap = hashSessionManager.getSessionMap();
    LOG.debug("session map: " + sessionMap);
    Entry<String, HttpSession> sessionEntry = sessionMap.entrySet().iterator().next();
    HttpSession httpSession = sessionEntry.getValue();
    assertNotNull(httpSession.getAttribute("eid"));
    assertNull(httpSession.getAttribute("eid.identity"));
    assertNull(httpSession.getAttribute("eid.address"));
    assertNull(httpSession.getAttribute("eid.photo"));
    String identifier = (String) httpSession.getAttribute("eid.identifier");
    assertNotNull(identifier);
    LOG.debug("identifier: " + identifier);
    assertTrue(TestAuthenticationService.called);
}

From source file:microsoft.exchange.webservices.data.ExchangeServiceBase.java

/**
 * Sets the credentials used to authenticate with the Exchange Web Services.
 * Setting the Credentials property automatically sets the
 * UseDefaultCredentials to false.//www  . java2 s. c  o m
 *
 * @param credentials Exchange credentials.
 */
public void setCredentials(ExchangeCredentials credentials) {
    this.credentials = credentials;
    this.useDefaultCredentials = false;
    CookieHandler.setDefault(new CookieManager());
}

From source file:microsoft.exchange.webservices.data.ExchangeServiceBase.java

/**
 * Sets a value indicating whether the credentials of the user currently
 * logged into Windows should be used to authenticate with the Exchange Web
 * Services. Setting UseDefaultCredentials to true automatically sets the
 * Credentials property to null.//from   w  ww  .jav  a 2 s  .co m
 *
 * @param value the new use default credentials
 */
public void setUseDefaultCredentials(boolean value) {
    this.useDefaultCredentials = value;
    if (value) {
        this.credentials = null;
        CookieHandler.setDefault(null);
    }
}

From source file:com.hygenics.parser.GetImages.java

private void getImages() {
    // controls the web process from a removed method
    log.info("Setting Up Pull");
    String[] proxyarr = (proxies == null) ? null : proxies.split(",");
    // cleanup//from  w w w  . j  a  va 2 s.c  o  m
    if (cleanup) {
        cleanupDir(fpath);
    }

    // image grab
    CookieManager cm = new CookieManager();
    cm.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
    CookieHandler.setDefault(cm);
    int numimages = 0;
    InputStream is;
    byte[] bytes;
    int iter = 0;
    int found = 0;

    // set proxy if needed
    if (proxyuser != null) {
        proxy(proxyhost, proxyport, https, proxyuser, proxypass);
    }

    int i = 0;
    ArrayList<String> postImages = new ArrayList<String>();
    ForkJoinPool fjp = new ForkJoinPool(Runtime.getRuntime().availableProcessors());
    Set<Callable<String>> pulls = new HashSet<Callable<String>>();
    Set<Callable<ArrayList<String>>> sqls = new HashSet<Callable<ArrayList<String>>>();
    List<Future<String>> imageFutures;

    ArrayList<String> images;
    int chunksize = (int) Math.ceil(commitsize / numqueries);
    log.info("Chunksize: " + chunksize);
    if (baseurl != null || baseurlcolumn != null) {
        do {
            log.info("Offset: " + offset);
            log.info("Getting Images");
            images = new ArrayList<String>(commitsize);
            log.info("Getting Columns");
            for (int n = 0; n < numqueries; n++) {
                String tempsql = sql + " WHERE " + idString + " >= " + offset + " AND " + idString + " < "
                        + (offset + chunksize);

                if (conditions != null) {
                    tempsql += conditions;
                }

                sqls.add(new QueryDatabase(
                        ((extracondition != null) ? tempsql + " " + extracondition : tempsql)));

                offset += chunksize;
            }

            List<Future<ArrayList<String>>> futures = fjp.invokeAll(sqls);

            int w = 0;
            while (fjp.isQuiescent() && fjp.getActiveThreadCount() > 0) {
                w++;
            }

            for (Future<ArrayList<String>> f : futures) {
                try {
                    ArrayList<String> fjson;
                    fjson = f.get();
                    if (fjson.size() > 0) {
                        images.addAll(fjson);
                    }

                    if (f.isDone() == false) {
                        f.cancel(true);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }
            log.info(Integer.toString(images.size()) + " image links found. Pulling.");

            ArrayList<String> tempproxies = new ArrayList<String>();

            if (proxyarr != null) {
                for (String proxy : proxyarr) {
                    tempproxies.add(proxy.trim());
                }
            }

            if (maxproxies > 0) {
                maxproxies -= 1;// 0 and 1 should be equivalent conditions
                // --num is not like most 0 based still due
                // to >=
            }

            // get images
            for (int num = 0; num < images.size(); num++) {
                String icols = images.get(num);
                int proxnum = (int) Math.random() * (tempproxies.size() - 1);
                String proxy = (tempproxies.size() == 0) ? null : tempproxies.get(proxnum);

                // add grab
                pulls.add(new ImageGrabber(icols, proxy));

                if (proxy != null) {
                    tempproxies.remove(proxy);
                }

                // check for execution
                if (num + 1 == images.size() || pulls.size() >= commitsize || tempproxies.size() == 0) {
                    if (tempproxies.size() == 0 && proxies != null) {
                        tempproxies = new ArrayList<String>(proxyarr.length);

                        for (String p : proxyarr) {
                            tempproxies.add(p.trim());
                        }
                    }

                    imageFutures = fjp.invokeAll(pulls);
                    w = 0;

                    while (fjp.isQuiescent() == false && fjp.getActiveThreadCount() > 0) {
                        w++;
                    }

                    for (Future<String> f : imageFutures) {
                        String add;
                        try {
                            add = f.get();

                            if (add != null) {
                                postImages.add(add);
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        } catch (ExecutionException e) {
                            e.printStackTrace();
                        }
                    }
                    imageFutures = null;// garbage collect elligible
                    pulls = new HashSet<Callable<String>>(commitsize);
                }

                if (postImages.size() >= commitsize && addtoDB == true) {
                    if (addtoDB) {
                        log.info("Posting to Database");
                        log.info("Found " + postImages.size() + " images");
                        numimages += postImages.size();
                        int size = (int) Math.floor(postImages.size() / numqueries);
                        for (int n = 0; n < numqueries; n++) {
                            if (((n + 1) * size) < postImages.size() && (n + 1) < numqueries) {
                                fjp.execute(new ImagePost(postImages.subList(n * size, (n + 1) * size)));
                            } else {
                                fjp.execute(new ImagePost(postImages.subList(n * size, postImages.size() - 1)));
                            }
                        }

                        w = 0;
                        while (fjp.isQuiescent() && fjp.getActiveThreadCount() > 0) {
                            w++;
                        }
                    }
                    found += postImages.size();
                    postImages.clear();
                }

            }

            if (postImages.size() > 0 && addtoDB == true) {
                log.info("Posting to Database");
                numimages += postImages.size();
                int size = (int) Math.floor(postImages.size() / numqueries);
                for (int n = 0; n < numqueries; n++) {
                    if (((n + 1) * size) < postImages.size()) {
                        fjp.execute(new ImagePost(postImages.subList(n * size, (n + 1) * size)));
                    } else {
                        fjp.execute(new ImagePost(postImages.subList(n * size, postImages.size())));
                    }
                }

                w = 0;
                while (fjp.isQuiescent() && fjp.getActiveThreadCount() > 0) {
                    w++;
                }

                found += postImages.size();
                postImages.clear();
            }

            // handle iterations specs
            iter += 1;
            log.info("Iteration: " + iter);
            if ((iter < iterations && found < images.size()) || tillfound == true) {
                log.info("Not All Images Obtained Trying Iteration " + iter + " of " + iterations);
                offset -= commitsize;
            } else if ((iter < iterations && found >= images.size()) && tillfound == false) {
                log.info("Images Obtained in " + iter + " iterations. Continuing.");
                iter = 0;
            } else {
                // precautionary
                log.info("Images Obtained in " + iter + " iterations. Continuing");
                iter = 0;
            }

        } while (images.size() > 0 && iter < iterations);

        if (fjp.isShutdown()) {
            fjp.shutdownNow();
        }
    }

    log.info("Complete. Check for Errors \n " + numimages + " Images Found");
}