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:in.rab.ordboken.Ordboken.java

public void initCookies() {
    if (mCookieSerializer != null) {
        return;//  w  w  w  . j a v  a 2 s.c  om
    }

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

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

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  w  w.j  av a 2s . c  o  m
    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();//from w w w.j av a 2 s  . co  m

    // 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:test.integ.be.fedict.eid.idp.OpenIDTest.java

@Test
public void testOpenID() throws Exception {
    LOG.debug("OpenID integration test");

    // make sure that the session cookies are passed during conversations
    // required to be able to run the Controller here
    MyCookieManager cookieManager = new MyCookieManager();
    cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
    CookieHandler.setDefault(cookieManager);

    // setup/*from w  ww. j av a2s  .  c  om*/
    this.servletTester = new ServletTester();
    ServletHolder reqServletHolder = this.servletTester.addServlet(AuthenticationRequestServlet.class,
            "/openid-request");
    reqServletHolder.setInitParameter("ParametersFromRequest", "true");
    reqServletHolder.setInitParameter("SPDestination", "http://localhost/openid-response");
    reqServletHolder.setInitParameter("UserIdentifier", "https://localhost/eid-idp/endpoints/openid-identity");
    reqServletHolder.setInitParameter("TrustServer", "true");

    ServletHolder responseServletHolder = this.servletTester.addServlet(AuthenticationResponseServlet.class,
            "/openid-response");
    responseServletHolder.setInitParameter("RedirectPage", "/target");
    responseServletHolder.setInitParameter("IdentifierSessionAttribute", "identifier");

    this.servletTester.start();
    String location = this.servletTester.createSocketConnector(true);
    LOG.debug("location: " + location);

    HttpState httpState = new HttpState();
    HttpClient httpClient = new HttpClient();
    httpClient.setState(httpState);
    httpClient.getParams()
            .setCookiePolicy(org.apache.commons.httpclient.cookie.CookiePolicy.BROWSER_COMPATIBILITY);
    httpClient.getParams().setParameter("http.protocol.allow-circular-redirects", Boolean.TRUE);

    GetMethod getMethod = new GetMethod(location + "/openid-request?SPDestination=" + location
            + "/openid-response&UserIdentifier=https://localhost/eid-idp/endpoints/openid-identity");
    getMethod.setFollowRedirects(false);

    ProtocolSocketFactory protocolSocketFactory = new MyProtocolSocketFactory();
    Protocol myProtocol = new Protocol("https", protocolSocketFactory, 443);
    Protocol.registerProtocol("https", myProtocol);

    // operate
    int statusCode = httpClient.executeMethod(getMethod);

    // verify
    LOG.debug("status code: " + statusCode);
    assertEquals(HttpServletResponse.SC_MOVED_TEMPORARILY, statusCode);
    LOG.debug("response body: " + getMethod.getResponseBodyAsString());
    Header jettySetCookieHeader = getMethod.getResponseHeader("Set-Cookie");
    String jettySessionCookieValue = jettySetCookieHeader.getValue();
    LOG.debug("jetty session cookie value: " + jettySessionCookieValue);

    String idpLocation = getMethod.getResponseHeader("Location").getValue();
    LOG.debug("IdP location: " + idpLocation);
    getMethod = new GetMethod(idpLocation);
    getMethod.setFollowRedirects(false);
    statusCode = httpClient.executeMethod(getMethod);
    assertEquals(HttpServletResponse.SC_MOVED_TEMPORARILY, statusCode);
    LOG.debug("response body: " + getMethod.getResponseBodyAsString());

    String idpSessionCookieValue = getMethod.getResponseHeader("Set-Cookie").getValue();
    LOG.debug("IdP session cookie value: " + idpSessionCookieValue);
    String idpSeamLocation = getMethod.getResponseHeader("Location").getValue();
    getMethod = new GetMethod(idpSeamLocation);
    getMethod.setFollowRedirects(false);
    getMethod.addRequestHeader("Cookie", idpSessionCookieValue);
    statusCode = httpClient.executeMethod(getMethod);
    assertEquals(HttpServletResponse.SC_OK, statusCode);
    cookieManager.setSessionCookieValue(idpSessionCookieValue);

    Messages messages = new Messages(Locale.getDefault());
    Runtime runtime = new TestRuntime();
    View view = new TestView();
    Controller controller = new Controller(view, runtime, messages);

    /*
     * Context jettyContext = this.servletTester.getContext();
     * SessionHandler jettySessionHandler =
     * jettyContext.getSessionHandler(); SessionManager jettySessionManager
     * = jettySessionHandler .getSessionManager(); HashSessionManager
     * hashSessionManager = (HashSessionManager) jettySessionManager;
     * LOG.debug("# sessions: " + hashSessionManager.getSessions());
     * assertEquals(1, hashSessionManager.getSessions()); Map<String,
     * HttpSession> sessionMap = hashSessionManager .getSessionMap();
     * LOG.debug("session map: " + sessionMap); HttpSession jettyHttpSession
     * = sessionMap.values().iterator().next(); String jettySessionId =
     * jettyHttpSession.getId(); LOG.debug("jetty HTTP session id: " +
     * jettySessionId);
     */

    // operate
    controller.run();

    // httpState.addCookie(new Cookie("localhost", "JSESSIONID",
    // sessionCookie, "/eid-idp", -1, false));
    // httpClient.setState(httpState);
    LOG.debug("continue to eID IdP exit page...");
    getMethod = new GetMethod("https://localhost/eid-idp/protocol-exit");
    getMethod.addRequestHeader("Cookie", idpSessionCookieValue);
    getMethod.setFollowRedirects(false);
    statusCode = httpClient.executeMethod(getMethod);
    LOG.debug("status code: " + statusCode);
    assertEquals(HttpServletResponse.SC_MOVED_TEMPORARILY, statusCode);
    String jettyResponseLocation = getMethod.getResponseHeader("Location").getValue();

    getMethod = new GetMethod(jettyResponseLocation);
    getMethod.setFollowRedirects(false);
    statusCode = httpClient.executeMethod(getMethod);
    LOG.debug("status code: " + statusCode);
    assertEquals(HttpServletResponse.SC_MOVED_TEMPORARILY, statusCode);

    LOG.debug("response body: " + getMethod.getResponseBodyAsString());
}

From source file:org.esupportail.nfctagdroid.NfcTacDroidActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ESUP_NFC_TAG_SERVER_URL = getEsupNfcTagServerUrl(getApplicationContext());
    //To keep session for desfire async requests
    CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
    LocalStorage.getInstance(getApplicationContext());
    Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(getApplicationContext()));
    setContentView(R.layout.activity_main);
    mAdapter = NfcAdapter.getDefaultAdapter(this);
    checkHardware(mAdapter);/*from  ww  w .jav  a2  s.  c o m*/
    localStorageDBHelper = LocalStorage.getInstance(this.getApplicationContext());
    String numeroId = localStorageDBHelper.getValue("numeroId");
    TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    String imei = telephonyManager.getDeviceId();
    url = ESUP_NFC_TAG_SERVER_URL + "/nfc-index?numeroId=" + numeroId + "&imei=" + imei + "&macAddress="
            + getMacAddr() + "&apkVersion=" + getApkVersion();
    view = (WebView) this.findViewById(R.id.webView);
    view.clearCache(true);
    view.addJavascriptInterface(new LocalStorageJavaScriptInterface(this.getApplicationContext()),
            "AndroidLocalStorage");
    view.addJavascriptInterface(new AndroidJavaScriptInterface(this.getApplicationContext()), "Android");

    view.setWebChromeClient(new WebChromeClient() {

        @Override
        public void onProgressChanged(WebView view, int progress) {
            if (progress == 100) {
                AUTH_TYPE = localStorageDBHelper.getValue("authType");
            }
        }

        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
            log.info("Webview console message : " + consoleMessage.message());
            return false;
        }

    });

    view.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            view.reload();
            return true;
        }
    });
    view.getSettings().setAllowContentAccess(true);
    WebSettings webSettings = view.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setDomStorageEnabled(true);
    webSettings.setDatabaseEnabled(true);
    webSettings.setDatabasePath(this.getFilesDir().getParentFile().getPath() + "/databases/");

    view.setDownloadListener(new DownloadListener() {
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,
                long contentLength) {
            Intent i = new Intent(Intent.ACTION_VIEW);
            i.setData(Uri.parse(url));
            startActivity(i);
        }

    });

    view.setWebViewClient(new WebViewClient() {
        public void onPageFinished(WebView view, String url) {
        }
    });

    view.loadUrl(url);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}

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  w  w.  ja  va 2s  .co 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);

}

From source file:org.apache.nutch.protocol.httpclient.HttpFormAuthentication.java

public void login() throws Exception {
    // make sure cookies are turned on
    CookieHandler.setDefault(new CookieManager());
    String pageContent = httpGetPageContent(authConfigurer.getLoginUrl());
    List<NameValuePair> params = getLoginFormParams(pageContent);
    sendPost(authConfigurer.getLoginUrl(), params);
}

From source file:org.broad.igv.util.HttpUtils.java

private HttpUtils() {

    org.broad.tribble.util.ParsingUtils.registerHelperClass(IGVUrlHelper.class);

    disableCertificateValidation();/*  w  ww  .  j  a v a2s .c om*/
    CookieHandler.setDefault(new IGVCookieManager());
    Authenticator.setDefault(new IGVAuthenticator());

    try {
        System.setProperty("java.net.useSystemProxies", "true");
    } catch (Exception e) {
        log.info("Couldn't set useSystemProxies=true");
    }

    byteRangeTestMap = Collections.synchronizedMap(new HashMap());
}

From source file:jmc.util.UtlFbComents.java

public static String getJSONComentarios(String url, Long numComents) throws JMCException {
    String linea = "";
    String buf = "";

    try {//ww  w .j a v a2s.co  m
        Properties props = ConfigPropiedades.getProperties("props_config.properties");
        CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
        URL ur = new URL(
                "http://graph.facebook.com/comments?id=" + url + "&limit=" + numComents + "&filter=stream");
        HttpURLConnection cn = (HttpURLConnection) ur.openConnection();

        cn.setRequestProperty("user-agent", props.getProperty("navegador"));
        cn.setInstanceFollowRedirects(false);
        cn.setUseCaches(false);
        cn.connect();

        BufferedReader br = new BufferedReader(new InputStreamReader(cn.getInputStream()));

        while ((linea = br.readLine()) != null) {
            buf.concat(linea);
        }
        cn.disconnect();

    } catch (IOException e) {
        throw new JMCException(e);
    }
    return buf;
}