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:at.florian_lentsch.expirysync.net.JsonCaller.java

public JsonCaller(String hostStr) throws URISyntaxException {
    setHost(hostStr);//from   www .  j av  a  2 s  .  c  o  m
    this.cookieManager = (CookieManager) CookieHandler.getDefault();

    if (this.cookieManager == null) {
        this.cookieManager = new CookieManager();
        CookieHandler.setDefault(this.cookieManager);
    }
}

From source file:keywhiz.cli.ClientUtils.java

/**
 * Creates a {@link OkHttpClient} to start a TLS connection.
 *
 * @param cookies list of cookies to include in the client.
 * @return new http client./*from   w  ww  .ja  va 2  s. c o  m*/
 */
public static OkHttpClient sslOkHttpClient(List<HttpCookie> cookies) {
    checkNotNull(cookies);

    SSLContext sslContext;
    try {
        sslContext = SSLContext.getInstance("TLSv1.2");

        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init((KeyStore) null);

        sslContext.init(new KeyManager[0], trustManagerFactory.getTrustManagers(), new SecureRandom());
    } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
        throw Throwables.propagate(e);
    }

    SSLSocketFactory socketFactory = sslContext.getSocketFactory();

    OkHttpClient client = new OkHttpClient().setSslSocketFactory(socketFactory)
            .setConnectionSpecs(Arrays.asList(ConnectionSpec.MODERN_TLS)).setFollowSslRedirects(false);

    client.setRetryOnConnectionFailure(false);
    client.networkInterceptors().add(new XsrfTokenInterceptor("XSRF-TOKEN", "X-XSRF-TOKEN"));
    CookieManager cookieManager = new CookieManager();
    cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
    cookies.forEach(c -> cookieManager.getCookieStore().add(null, c));
    client.setCookieHandler(cookieManager);
    return client;
}

From source file:CookieAccessor.java

/**
 * Set cookie in cookie store//  w  ww  .ja va  2  s  . c om
 */
public void setCookieUsingCookieHandler() {
    try {
        // instantiate CookieManager
        CookieManager manager = new CookieManager();
        CookieHandler.setDefault(manager);
        CookieStore cookieJar = manager.getCookieStore();

        // create cookie
        HttpCookie cookie = new HttpCookie("UserName", "John Doe");

        // add cookie to CookieStore for a particular URL
        URL url = new URL("http://host.example.com");
        cookieJar.add(url.toURI(), cookie);
        System.out.println("Added cookie using cookie handler");
    } catch (Exception e) {
        System.out.println("Unable to set cookie using CookieHandler");
        e.printStackTrace();
    }
}

From source file:in.rab.ordboken.Ordboken.java

public void initCookies() {
    if (mCookieSerializer != null) {
        return;/*from   w ww  .  j  a  v  a2  s  .  c o  m*/
    }

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

    mCookieSerializer = new CookieSerializer(cookieManager.getCookieStore(), "www.ne.se");
    mCookieSerializer.loadFromString(mPrefs.getString("cookies", null));
}

From source file:com.urswolfer.gerrit.client.rest.http.GerritRestClient.java

public GerritRestClient(GerritAuthData authData, HttpRequestExecutor httpRequestExecutor,
        HttpClientBuilderExtension... httpClientBuilderExtensions) {
    this.authData = authData;
    this.httpRequestExecutor = httpRequestExecutor;
    this.httpClientBuilderExtensions = Arrays.asList(httpClientBuilderExtensions);

    cookieManager = new CookieManager();
    cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
    cookieStore = cookieManager.getCookieStore();
    loginCache = new LoginCache(authData, cookieStore);
}

From source file:hanulhan.cas.client.CasRestActions.java

public String doLoginCasRest() {

    jsonStatus = new JsonStatus();
    String myUrlParameters = "username=uhansen01&password=Ava030374Lon_";
    CookieHandler.setDefault(new CookieManager());
    StringBuilder myResult;//from  w ww.j av  a2  s .com
    String myServiceTicketUrl = null;
    String myTgt = "";
    String myServiceTicket = "";
    List<NameValuePair> postParams = new ArrayList<>();
    HttpResponse myResponse;

    // GET the TGT
    try {
        myResponse = sendPost(CAS_SERVER_URL + "/v1/tickets?" + myUrlParameters, postParams);
        if (myResponse.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_CREATED) {
            myResult = getHttpResponseResult(myResponse);
            if (myResult != null && myResult.length() > 0) {
                myServiceTicketUrl = getServiceTicketUrl(myResult.toString());
                if (myServiceTicketUrl != null && myServiceTicketUrl.length() > 0) {
                    LOGGER.log(Level.INFO, "ServiceTicketURL: " + myServiceTicketUrl);
                    myTgt = getTGT(myServiceTicketUrl);
                    if (myTgt != null && myTgt.length() > 0) {
                        LOGGER.log(Level.INFO, "TGT: " + myTgt);
                    }
                }
            } else {
                LOGGER.log(Level.ERROR, "Status Code: " + myResponse.getStatusLine().getStatusCode());
            }
        }
    } catch (Exception ex) {
        LOGGER.log(Level.ERROR, ex);
    }

    // Get the ServiceTicket
    try {
        if (myTgt != null && myTgt.length() > 0) {
            postParams.add(new BasicNameValuePair("service", CAS_SERVICE));
            myResponse = sendPost(myServiceTicketUrl, postParams);
            if (myResponse.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {
                myServiceTicket = getHttpResponseResult(myResponse).toString();
                LOGGER.log(Level.INFO, "ServiceTicket: " + myServiceTicket);
                redirectUrl = GET_URL + "?authServiceTicket=" + myServiceTicket + "&authService=" + CAS_SERVICE;
                LOGGER.log(Level.INFO, "ServiceURL: " + redirectUrl);
            }
        }
    } catch (Exception ex) {
        LOGGER.log(Level.ERROR, ex);
    }

    return SUCCESS;

}

From source file:org.oscarehr.integration.excelleris.com.colcamex.www.core.Connect.java

private void _init() {
    CookieManager cookieManager = new CookieManager();
    cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
    CookieHandler.setDefault(cookieManager);
}

From source file:com.hybris.mobile.Hybris.java

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

    // TODO - Delete this too heavy exception process not adapted for Android?
    //      ExceptionHandler.register(this);

    // Saving the application context
    setContext(this);

    // Load preference defaults
    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);

    // Updating the webservices URL from the preferences
    updateWebServicesUrl();//w  ww.j a v a 2s .com

    // Enable / Disable geofencing
    enableGeofencing();

    SDKSettings.setSettingValue(InternalConstants.KEY_PREF_CATALOG,
            StringUtil.replaceIfNull(Hybris.getSharedPreferenceString(InternalConstants.KEY_PREF_CATALOG),
                    SDKSettings.getSettingValue(InternalConstants.KEY_PREF_CATALOG)));

    SDKSettings.setSettingValue(InternalConstants.KEY_PREF_LANGUAGE,
            StringUtil.replaceIfNull(Hybris.getSharedPreferenceString(InternalConstants.KEY_PREF_LANGUAGE),
                    SDKSettings.getSettingValue(InternalConstants.KEY_PREF_LANGUAGE)));

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

    populateCategories();

    setDeviceId();
    setUuid(this);
    startService();

}

From source file:me.skydeveloper.tikona.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //Facebook Analytics Initialization
    FacebookSdk.sdkInitialize(getApplicationContext());
    AppEventsLogger.activateApp(this);

    setContentView(R.layout.activity_main_navigation_drawer);
    //setContentView(R.layout.welcome);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);/*from w ww  .  ja v  a2s . c  o m*/

    CookieHandler.setDefault(new CookieManager());

    drawer = (DrawerLayout) findViewById(R.id.drawer_layout);

    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
            R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    View headerView = navigationView.getHeaderView(0);

    //navigationView.getMenu().clear();

    urlPreferences = getSharedPreferences("url", MODE_PRIVATE);
    sessionPreferences = getSharedPreferences("session", MODE_PRIVATE);
    selfcarePreferences = getSharedPreferences("selfcare", MODE_PRIVATE);

    navigationMenu = navigationView.getMenu();

    //Todo => Uncomment this when selfcare login is fixed
    /*if (!selfcarePreferences.getString("username", "").isEmpty() && !selfcarePreferences.getString("password", "").isEmpty()) {
    MenuItem item = navigationMenu.findItem(R.id.loggedIn);
    item.setVisible(true);
    } else {
    MenuItem item = navigationMenu.findItem(R.id.notLoggedIn);
    item.setVisible(true);
    }*/

    logout = new AlertDialog.Builder(this);
    logout.setMessage("Are you sure you want logout?").setTitle("Confirm Logout");
    logout.setPositiveButton("Logout", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            //Call logout uri
            logout();
        }
    });
    logout.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            //Do nothing
        }
    });

    logout.create();

    userId = (TextView) headerView.findViewById(R.id.userId);
    userName = (TextView) headerView.findViewById(R.id.name);

    userId.setText(selfcarePreferences.getString("username", "11XXXXXXXX"));
    userName.setText(selfcarePreferences.getString("user_name", "Guest User"));

    ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
    if (viewPager != null) {
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                //Log.d("onPageSelected", position + "");
                if (position == 1) {
                    BillingTab.selfcareArray[0].setText(selfcarePreferences.getString("totalOutstanding",
                            "Selfcare login temporarily disabled"));//TODO => Show appropirate message after fixing selfcare bug

                    BillingTab.selfcareArray[1].setText(selfcarePreferences.getString("lastBillAmount", "-"));
                    BillingTab.selfcareArray[2].setText(selfcarePreferences.getString("lastBillDate", "-"));
                    BillingTab.selfcareArray[3].setText(selfcarePreferences.getString("dueDate", "-"));
                    BillingTab.selfcareArray[4]
                            .setText(selfcarePreferences.getString("lastPaymentAmount", "-"));
                    BillingTab.selfcareArray[5].setText(selfcarePreferences.getString("lastPaymentDate", "-"));

                    //BillingTab.selfcareArray[0].setText("test");
                }

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }
    setupViewPager(viewPager);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);

    popupLoader = new ProgressDialog(this);

}