Example usage for java.net CookieManager CookieManager

List of usage examples for java.net CookieManager CookieManager

Introduction

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

Prototype

public CookieManager() 

Source Link

Document

Create a new cookie manager.

Usage

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

@Test
public void controllerIdentificationWithAddressAndPhoto() throws Exception {
    // setup/*from  w w  w. j a v a 2s  . 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("IncludeAddress", "true");
    this.servletHolder.setInitParameter("IncludePhoto", "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"));
    Identity identity = (Identity) httpSession.getAttribute("eid.identity");
    assertNotNull(identity);
    assertNotNull(identity.name);
    LOG.debug("name: " + identity.name);
    LOG.debug("nationality: " + identity.getNationality());
    LOG.debug("national number: " + identity.getNationalNumber());
    assertNull(httpSession.getAttribute("eid.identifier"));
    assertNotNull(httpSession.getAttribute("eid.address"));
    assertNotNull(httpSession.getAttribute("eid.photo"));
}

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

@Test
public void controllerKioskMode() throws Exception {
    // setup//www  . ja v  a 2s  .  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("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   w  w  w. j ava 2s . 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");

    // 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:self.philbrown.droidQuery.Ajax.java

protected TaskResponse doInBackground(Void... arg0) {
    if (this.isCancelled)
        return null;

    //if synchronous, block on the background thread until ready. Then call beforeSend, etc, before resuming.
    if (!beforeSendIsAsync) {
        try {/*  w ww.  j a  v a 2s. c om*/
            mutex.acquire();
        } catch (InterruptedException e) {
            Log.w("AjaxTask", "Synchronization Error. Running Task Async");
        }
        final Thread asyncThread = Thread.currentThread();
        isLocked = true;
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                if (options.beforeSend() != null) {
                    if (options.context() != null)
                        options.beforeSend().invoke($.with(options.context()), options);
                    else
                        options.beforeSend().invoke(null, options);
                }

                if (options.isAborted()) {
                    cancel(true);
                    return;
                }

                if (options.global()) {
                    synchronized (globalTasks) {
                        if (globalTasks.isEmpty()) {
                            $.ajaxStart();
                        }
                        globalTasks.add(Ajax.this);
                    }
                    $.ajaxSend();
                } else {
                    synchronized (localTasks) {
                        localTasks.add(Ajax.this);
                    }
                }
                isLocked = false;
                LockSupport.unpark(asyncThread);
            }
        });
        if (isLocked)
            LockSupport.park();
    }

    //here is where to use the mutex

    //handle cached responses
    Object cachedResponse = AjaxCache.sharedCache().getCachedResponse(options);
    //handle ajax caching option
    if (cachedResponse != null && options.cache()) {
        Success s = new Success(cachedResponse);
        s.reason = "cached response";
        s.allHeaders = null;
        return s;

    }

    if (connection == null) {
        try {
            String type = options.type();
            URL url = new URL(options.url());
            if (type == null) {
                type = "GET";
            }
            if (type.equalsIgnoreCase("CUSTOM")) {

                try {
                    connection = options.customConnection();
                } catch (Exception e) {
                    connection = null;
                }

                if (connection == null) {
                    Log.w("droidQuery.ajax",
                            "CUSTOM type set, but AjaxOptions.customRequest is invalid. Defaulting to GET.");
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                }
            } else {
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod(type);
                if (type.equalsIgnoreCase("POST") || type.equalsIgnoreCase("PUT")) {
                    connection.setDoOutput(true);
                }
            }
        } catch (Throwable t) {
            if (options.debug())
                t.printStackTrace();
            Error e = new Error(null);
            AjaxError error = new AjaxError();
            error.connection = connection;
            error.options = options;
            e.status = 0;
            e.reason = "Bad Configuration";
            error.status = e.status;
            error.reason = e.reason;
            error.response = e.response;
            e.allHeaders = new Headers();
            e.error = error;
            return e;
        }

    }

    Map<String, Object> args = new HashMap<String, Object>();
    args.put("options", options);
    args.put("request", null);
    args.put("connection", connection);
    EventCenter.trigger("ajaxPrefilter", args, null);

    if (options.headers() != null) {
        if (options.headers().authorization() != null) {
            options.headers()
                    .authorization(options.headers().authorization() + " " + options.getEncodedCredentials());
        } else if (options.username() != null) {
            //guessing that authentication is basic
            options.headers().authorization("Basic " + options.getEncodedCredentials());
        }

        for (Entry<String, String> entry : options.headers().map().entrySet()) {
            connection.setRequestProperty(entry.getKey(), entry.getValue());
        }
    }

    if (options.data() != null) {
        try {
            OutputStream os = connection.getOutputStream();
            os.write(options.data().toString().getBytes());
            os.close();
        } catch (Throwable t) {
            Log.w("Ajax", "Could not post data");
        }
    }

    if (options.timeout() != 0) {
        connection.setConnectTimeout(options.timeout());
        connection.setReadTimeout(options.timeout());
    }

    if (options.trustedCertificate() != null) {

        Certificate ca = options.trustedCertificate();

        String keyStoreType = KeyStore.getDefaultType();
        KeyStore keyStore = null;
        try {
            keyStore = KeyStore.getInstance(keyStoreType);
            keyStore.load(null, null);
            keyStore.setCertificateEntry("ca", ca);
        } catch (KeyStoreException e) {
            if (options.debug())
                e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            if (options.debug())
                e.printStackTrace();
        } catch (CertificateException e) {
            if (options.debug())
                e.printStackTrace();
        } catch (IOException e) {
            if (options.debug())
                e.printStackTrace();
        }

        if (keyStore == null) {
            Log.w("Ajax", "Could not configure trusted certificate");
        } else {
            try {
                //Create a TrustManager that trusts the CAs in our KeyStore
                String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
                TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
                tmf.init(keyStore);

                //Create an SSLContext that uses our TrustManager
                SSLContext sslContext = SSLContext.getInstance("TLS");
                sslContext.init(null, tmf.getTrustManagers(), null);
                ((HttpsURLConnection) connection).setSSLSocketFactory(sslContext.getSocketFactory());
            } catch (KeyManagementException e) {
                if (options.debug())
                    e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                if (options.debug())
                    e.printStackTrace();
            } catch (KeyStoreException e) {
                if (options.debug())
                    e.printStackTrace();
            }
        }
    }

    try {

        if (options.cookies() != null) {
            CookieManager cm = new CookieManager();
            CookieStore cookies = cm.getCookieStore();
            URI uri = URI.create(options.url());
            for (Entry<String, String> entry : options.cookies().entrySet()) {
                HttpCookie cookie = new HttpCookie(entry.getKey(), entry.getValue());
                cookies.add(uri, cookie);
            }
            connection.setRequestProperty("Cookie", TextUtils.join(",", cookies.getCookies()));
        }

        connection.connect();
        final int statusCode = connection.getResponseCode();
        final String message = connection.getResponseMessage();

        if (options.dataFilter() != null) {
            if (options.context() != null)
                options.dataFilter().invoke($.with(options.context()), connection, options.dataType());
            else
                options.dataFilter().invoke(null, connection, options.dataType());
        }

        final Function function = options.statusCode().get(statusCode);
        if (function != null) {
            mHandler.post(new Runnable() {

                @Override
                public void run() {
                    if (options.context() != null)
                        function.invoke($.with(options.context()), statusCode, options.clone());
                    else
                        function.invoke(null, statusCode, options.clone());
                }

            });

        }

        //handle dataType
        String dataType = options.dataType();
        if (dataType == null)
            dataType = "text";
        if (options.debug())
            Log.i("Ajax", "dataType = " + dataType);
        Object parsedResponse = null;
        InputStream stream = null;
        try {
            if (dataType.equalsIgnoreCase("text") || dataType.equalsIgnoreCase("html")) {
                if (options.debug())
                    Log.i("Ajax", "parsing text");
                stream = AjaxUtil.getInputStream(connection);
                parsedResponse = parseText(stream);
            } else if (dataType.equalsIgnoreCase("xml")) {
                if (options.debug())
                    Log.i("Ajax", "parsing xml");
                if (options.customXMLParser() != null) {
                    stream = AjaxUtil.getInputStream(connection);
                    if (options.SAXContentHandler() != null)
                        options.customXMLParser().parse(stream, options.SAXContentHandler());
                    else
                        options.customXMLParser().parse(stream, new DefaultHandler());
                    parsedResponse = "Response handled by custom SAX parser";
                } else if (options.SAXContentHandler() != null) {
                    stream = AjaxUtil.getInputStream(connection);
                    SAXParserFactory factory = SAXParserFactory.newInstance();

                    factory.setFeature("http://xml.org/sax/features/namespaces", false);
                    factory.setFeature("http://xml.org/sax/features/namespace-prefixes", true);

                    SAXParser parser = factory.newSAXParser();

                    XMLReader reader = parser.getXMLReader();
                    reader.setContentHandler(options.SAXContentHandler());
                    reader.parse(new InputSource(stream));
                    parsedResponse = "Response handled by custom SAX content handler";
                } else {
                    parsedResponse = parseXML(connection);
                }
            } else if (dataType.equalsIgnoreCase("json")) {
                if (options.debug())
                    Log.i("Ajax", "parsing json");
                parsedResponse = parseJSON(connection);
            } else if (dataType.equalsIgnoreCase("script")) {
                if (options.debug())
                    Log.i("Ajax", "parsing script");
                parsedResponse = parseScript(connection);
            } else if (dataType.equalsIgnoreCase("image")) {
                if (options.debug())
                    Log.i("Ajax", "parsing image");
                stream = AjaxUtil.getInputStream(connection);
                parsedResponse = parseImage(stream);
            } else if (dataType.equalsIgnoreCase("raw")) {
                if (options.debug())
                    Log.i("Ajax", "parsing raw data");
                parsedResponse = parseRawContent(connection);
            }
        } catch (ClientProtocolException cpe) {
            if (options.debug())
                cpe.printStackTrace();
            Error e = new Error(parsedResponse);
            AjaxError error = new AjaxError();
            error.connection = connection;
            error.options = options;
            e.status = statusCode;
            e.reason = message;
            error.status = e.status;
            error.reason = e.reason;
            error.response = e.response;
            e.allHeaders = Headers.createHeaders(connection.getHeaderFields());
            e.error = error;
            return e;
        } catch (Exception ioe) {
            if (options.debug())
                ioe.printStackTrace();
            Error e = new Error(parsedResponse);
            AjaxError error = new AjaxError();
            error.connection = connection;
            error.options = options;
            e.status = statusCode;
            e.reason = message;
            error.status = e.status;
            error.reason = e.reason;
            error.response = e.response;
            e.allHeaders = Headers.createHeaders(connection.getHeaderFields());
            e.error = error;
            return e;
        } finally {
            connection.disconnect();
            try {
                if (stream != null) {
                    stream.close();
                }
            } catch (IOException e) {
            }
        }

        if (statusCode >= 300) {
            //an error occurred
            Error e = new Error(parsedResponse);
            Log.e("Ajax Test", parsedResponse.toString());
            //AjaxError error = new AjaxError();
            //error.request = request;
            //error.options = options;
            e.status = e.status;
            e.reason = e.reason;
            //error.status = e.status;
            //error.reason = e.reason;
            //error.response = e.response;
            e.allHeaders = Headers.createHeaders(connection.getHeaderFields());
            //e.error = error;
            if (options.debug())
                Log.i("Ajax", "Error " + e.status + ": " + e.reason);
            return e;
        } else {
            //handle ajax ifModified option
            List<String> lastModifiedHeaders = connection.getHeaderFields().get("last-modified");
            if (lastModifiedHeaders.size() >= 1) {
                try {
                    String h = lastModifiedHeaders.get(0);
                    SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US);
                    Date lastModified = format.parse(h);
                    if (options.ifModified() && lastModified != null) {
                        Date lastModifiedDate;
                        synchronized (lastModifiedUrls) {
                            lastModifiedDate = lastModifiedUrls.get(options.url());
                        }

                        if (lastModifiedDate != null && lastModifiedDate.compareTo(lastModified) == 0) {
                            //request response has not been modified. 
                            //Causes an error instead of a success.
                            Error e = new Error(parsedResponse);
                            AjaxError error = new AjaxError();
                            error.connection = connection;
                            error.options = options;
                            e.status = e.status;
                            e.reason = e.reason;
                            error.status = e.status;
                            error.reason = e.reason;
                            error.response = e.response;
                            e.allHeaders = Headers.createHeaders(connection.getHeaderFields());
                            e.error = error;
                            Function func = options.statusCode().get(304);
                            if (func != null) {
                                if (options.context() != null)
                                    func.invoke($.with(options.context()));
                                else
                                    func.invoke(null);
                            }
                            return e;
                        } else {
                            synchronized (lastModifiedUrls) {
                                lastModifiedUrls.put(options.url(), lastModified);
                            }
                        }
                    }
                } catch (Throwable t) {
                    Log.e("Ajax", "Could not parse Last-Modified Header", t);
                }

            }

            //Now handle a successful request

            Success s = new Success(parsedResponse);
            s.reason = message;
            s.allHeaders = Headers.createHeaders(connection.getHeaderFields());
            return s;
        }

    } catch (Throwable t) {
        if (options.debug())
            t.printStackTrace();
        if (t instanceof java.net.SocketTimeoutException) {
            Error e = new Error(null);
            AjaxError error = new AjaxError();
            error.connection = connection;
            error.options = options;
            error.response = e.response;
            e.status = 0;
            String reason = t.getMessage();
            if (reason == null)
                reason = "Socket Timeout";
            e.reason = reason;
            error.status = e.status;
            error.reason = e.reason;
            if (connection != null)
                e.allHeaders = Headers.createHeaders(connection.getHeaderFields());
            else
                e.allHeaders = new Headers();
            e.error = error;
            return e;
        }
        return null;
    }
}

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

@Test
public void testAuthnSessionIdChannelBinding() throws Exception {
    // setup//from   www.  j av a  2s.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();// ww  w .ja v a  2  s .  co m

    //      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:com.example.android.networkconnect.MainActivity.java

private String httpstestconnect(String urlString) throws IOException {
    CookieManager msCookieManager = new CookieManager();

    URL url = new URL(urlString);

    if (url.getProtocol().toLowerCase().equals("https")) {
        trustAllHosts();//from   w  ww  . j  a  v  a  2 s  .  co m

        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

        try {

            String headerName = null;

            for (int i = 1; (headerName = conn.getHeaderFieldKey(i)) != null; i++) {
                //data=data+"Header Nme : " + headerName;
                //data=data+conn.getHeaderField(i);
                // Log.i (TAG,headerName);
                Log.i(TAG, headerName + ": " + conn.getHeaderField(i));
            }

            //  Map<String, List<String>> headerFields = conn.getHeaderFields();
            //List<String> cookiesHeader = headerFields.get("Set-Cookie");

            //if(cookiesHeader != null)
            //{
            //  for (String cookie : cookiesHeader)
            // {
            //   msCookieManager.getCookieStore().add(null,HttpCookie.parse(cookie).get(0));

            //}
            //}

        } catch (Exception e) {
            Log.i(TAG, "Erreur Cookie" + e);
        }

        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);

        conn.setChunkedStreamingMode(0);

        conn.setRequestProperty("User-Agent", "e-venement-app/");

        //if(msCookieManager.getCookieStore().getCookies().size() > 0)
        //{
        //        conn.setRequestProperty("Cookie",
        //            TextUtils.join(",", msCookieManager.getCookieStore().getCookies()));
        //}

        // conn= (HttpsURLConnection) url.wait(); ;
        //(HttpsURLConnection) url.openConnection();

        final String password = "android2015@";

        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
        writer.getEncoding();
        writer.write("&signin[username]=antoine");
        writer.write("&signin[password]=android2015@");
        //writer.write("&signin[_csrf_token]="+CSRFTOKEN);
        writer.flush();
        //Log.i(TAG,"Writer: "+writer.toString());

        //   conn.connect();

        String data = null;

        //
        if (conn.getInputStream() != null) {
            Log.i(TAG, readIt(conn.getInputStream(), 2500));
            data = readIt(conn.getInputStream(), 7500);
        }

        //  return conn.getResponseCode();
        return data;
        //return readIt(inputStream,1028);
    }

    else {
        return url.getProtocol();
    }

}

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

@Test
public void testAuthnServerCertificateChannelBinding() throws Exception {
    // setup/*from w  w  w  .  java  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");
    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 a2s.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// w ww  . ja  v a 2 s. 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("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);
}