@TestTargets({
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        method = "hasCookies",
        args = {}),
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        method = "removeAllCookie",
        args = {})
  })
  @ToBeFixed(explanation = "CookieManager.hasCookies() should also count cookies in RAM cache")
  public void testCookieManager() {
    // enable cookie
    mCookieManager.setAcceptCookie(true);
    assertTrue(mCookieManager.acceptCookie());

    // first there should be no cookie stored
    assertFalse(mCookieManager.hasCookies());

    String url = "http://www.example.com";
    String cookie = "name=test";
    mCookieManager.setCookie(url, cookie);
    assertEquals(cookie, mCookieManager.getCookie(url));

    // sync cookie from RAM to FLASH, because hasCookies() only counts FLASH cookies
    CookieSyncManager.getInstance().sync();
    new DelayedCheck(TEST_DELAY) {
      @Override
      protected boolean check() {
        return mCookieManager.hasCookies();
      }
    }.run();

    // clean up all cookies
    mCookieManager.removeAllCookie();
    new DelayedCheck(TEST_DELAY) {
      @Override
      protected boolean check() {
        return !mCookieManager.hasCookies();
      }
    }.run();
  }
Beispiel #2
0
 protected void onPostExecute(String result) {
   CookieSyncManager.createInstance(getApplicationContext());
   CookieSyncManager.getInstance().resetSync();
   CookieSyncManager.getInstance().startSync();
   CookieManager manager = CookieManager.getInstance();
   manager.acceptCookie();
   manager.setAcceptCookie(true);
   manager.setCookie("https://login.gatech.edu/cas/login", "Set-Cookie");
   manager.setCookie("https://t-square.gatech.edu/portal/pda", "Set-Cookie");
   manager.setCookie("https://t-square.gatech.edu/sakai-login-tool/container", "Set-Cookie");
   wv.clearHistory();
   manager.removeAllCookie();
   manager.setCookie(
       contentLink, getSharedPreferences(TsquareMain.MENU_LIST, 0).getString("TsquareJS", null));
   manager.setCookie(
       contentLink, getSharedPreferences(TsquareMain.MENU_LIST, 0).getString("Bigip", null));
   wv.loadUrl(contentLink);
   wv.setVisibility(View.VISIBLE);
   if (menuItem != null) {
     menuItem.collapseActionView();
     menuItem.setActionView(null);
   }
 }
  @TestTargets({
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        method = "setAcceptCookie",
        args = {boolean.class}),
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        method = "acceptCookie",
        args = {}),
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        method = "setCookie",
        args = {String.class, String.class}),
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        method = "getCookie",
        args = {String.class}),
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        method = "removeAllCookie",
        args = {})
  })
  public void testAcceptCookie() throws Exception {
    mCookieManager.removeAllCookie();
    mCookieManager.setAcceptCookie(false);
    assertFalse(mCookieManager.acceptCookie());
    assertFalse(mCookieManager.hasCookies());

    CtsTestServer server = new CtsTestServer(getActivity(), false);
    String url = server.getCookieUrl("conquest.html");
    loadUrl(url);
    assertEquals(null, mWebView.getTitle()); // no cookies passed
    Thread.sleep(TEST_DELAY);
    assertNull(mCookieManager.getCookie(url));

    mCookieManager.setAcceptCookie(true);
    assertTrue(mCookieManager.acceptCookie());

    url = server.getCookieUrl("war.html");
    loadUrl(url);
    assertEquals(null, mWebView.getTitle()); // no cookies passed
    waitForCookie(url);
    String cookie = mCookieManager.getCookie(url);
    assertNotNull(cookie);
    // 'count' value of the returned cookie is 0
    final Pattern pat = Pattern.compile("count=(\\d+)");
    Matcher m = pat.matcher(cookie);
    assertTrue(m.matches());
    assertEquals("0", m.group(1));

    url = server.getCookieUrl("famine.html");
    loadUrl(url);
    assertEquals("count=0", mWebView.getTitle()); // outgoing cookie
    waitForCookie(url);
    cookie = mCookieManager.getCookie(url);
    assertNotNull(cookie);
    m = pat.matcher(cookie);
    assertTrue(m.matches());
    assertEquals("1", m.group(1)); // value got incremented

    url = server.getCookieUrl("death.html");
    mCookieManager.setCookie(url, "count=41");
    loadUrl(url);
    assertEquals("count=41", mWebView.getTitle()); // outgoing cookie
    waitForCookie(url);
    cookie = mCookieManager.getCookie(url);
    assertNotNull(cookie);
    m = pat.matcher(cookie);
    assertTrue(m.matches());
    assertEquals("42", m.group(1)); // value got incremented

    // clean up all cookies
    mCookieManager.removeAllCookie();
  }
  @TestTargets({
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        method = "removeSessionCookie",
        args = {}),
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        method = "removeExpiredCookie",
        args = {})
  })
  @SuppressWarnings("deprecation")
  public void testRemoveCookies() throws InterruptedException {
    // enable cookie
    mCookieManager.setAcceptCookie(true);
    assertTrue(mCookieManager.acceptCookie());
    assertFalse(mCookieManager.hasCookies());

    final String url = "http://www.example.com";
    final String cookie1 = "cookie1=peter";
    final String cookie2 = "cookie2=sue";
    final String cookie3 = "cookie3=marc";

    mCookieManager.setCookie(url, cookie1); // session cookie

    Date date = new Date();
    date.setTime(date.getTime() + 1000 * 600);
    String value2 = cookie2 + "; expires=" + date.toGMTString();
    mCookieManager.setCookie(url, value2); // expires in 10min

    long expiration = 3000;
    date = new Date();
    date.setTime(date.getTime() + expiration);
    String value3 = cookie3 + "; expires=" + date.toGMTString();
    mCookieManager.setCookie(url, value3); // expires in 3s

    String allCookies = mCookieManager.getCookie(url);
    assertTrue(allCookies.contains(cookie1));
    assertTrue(allCookies.contains(cookie2));
    assertTrue(allCookies.contains(cookie3));

    mCookieManager.removeSessionCookie();
    new DelayedCheck(TEST_DELAY) {
      protected boolean check() {
        String c = mCookieManager.getCookie(url);
        return !c.contains(cookie1) && c.contains(cookie2) && c.contains(cookie3);
      }
    }.run();

    Thread.sleep(expiration + 1000); // wait for cookie to expire
    mCookieManager.removeExpiredCookie();
    new DelayedCheck(TEST_DELAY) {
      protected boolean check() {
        String c = mCookieManager.getCookie(url);
        return !c.contains(cookie1) && c.contains(cookie2) && !c.contains(cookie3);
      }
    }.run();

    mCookieManager.removeAllCookie();
    new DelayedCheck(TEST_DELAY) {
      protected boolean check() {
        return mCookieManager.getCookie(url) == null;
      }
    }.run();
  }
Beispiel #5
0
  @Override
  protected void onResume() {
    super.onResume();
    subjectName = getIntent().getExtras().getString("subjectName");
    boardName = getIntent().getExtras().getString("boardName");
    contentName = getIntent().getExtras().getString("contentName");
    contentLink = getIntent().getExtras().getString("contentLink");
    setTitle(contentName);

    if (isNetworkConnected()) {
      CookieSyncManager.createInstance(getApplicationContext());
      CookieSyncManager.getInstance().startSync();
      manager = CookieManager.getInstance();
      manager.acceptCookie();
      manager.setAcceptCookie(true);
      manager.removeAllCookie();
      SharedPreferences menuSp = getSharedPreferences(TsquareMain.MENU_LIST, 0);
      manager.setCookie(contentLink, menuSp.getString("TsquareJS", null));
      manager.setCookie(contentLink, menuSp.getString("Bigip", null));
      CookieSyncManager.getInstance().sync();

      wv = (WebView) findViewById(R.id.webView);
      wv.setWebViewClient(
          new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
              super.onPageFinished(view, url);
              if (menuItem != null) {
                menuItem.collapseActionView();
                menuItem.setActionView(null);
                new ToastRun("Done :)").run();
              }
            }
          });
      wv.setPadding(5, 0, 5, 0);
      try {
        Log.d("cookie is ", manager.getCookie(contentLink));
        if (new LoginCheck(this, new URL(contentLink), manager.getCookie(contentLink))
                .execute()
                .get()
            == 0) wv.loadUrl(contentLink);
        else {
          wv.setVisibility(View.INVISIBLE);
          new TestTask(this).execute();
        }
      } catch (InterruptedException e) {
        e.printStackTrace();
      } catch (ExecutionException e) {
        e.printStackTrace();
      } catch (MalformedURLException e) {
        e.printStackTrace();
      }
    } else if (!((WifiManager) getSystemService(Context.WIFI_SERVICE)).isWifiEnabled()) {
      new AlertDialog.Builder(this)
          .setTitle("Network status alert")
          .setMessage("Network is not connected.\nWould you like to enable the WI-FI?")
          .setPositiveButton(
              "Yes",
              new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                  finish();
                  WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
                  wifiManager.setWifiEnabled(true);
                }
              })
          .setNegativeButton(
              "No",
              new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                  finish();
                }
              })
          .show();
    } else { // WIFI is on and network is not connected
      new AlertDialog.Builder(this)
          .setTitle("Network status alert")
          .setMessage("Network is not connected with WI-FI.\nPlease check your network.")
          .setPositiveButton(
              "Ok",
              new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                  finish();
                }
              })
          .show();
    }
  }
  /*
   * the doInBackground function does the actual background processing
   *
   * @see android.os.AsyncTask#doInBackground(Params[])
   */
  @Override
  protected JSONObject doInBackground(Void... params) {
    JSONObject errorResponse = null;

    Log.d(TAG, "Started logo request via " + serviceUri);

    Log.d(TAG, "Using MCC=" + mcc);
    Log.d(TAG, "Using MNC=" + mnc);

    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.setAcceptCookie(enableCookies != null ? enableCookies.booleanValue() : false);
    Log.d(TAG, "Allowing cookies = " + cookieManager.acceptCookie());

    /*
     * sets up the HTTP request with a redirect_uri parameter - in practice
     * we're looking for mcc/mnc added to the redirect_uri if this step is necessary
     */
    String requestUri = serviceUri;

    requestUri = HttpUtils.addUriParameter(requestUri, "logosize", logosize);

    /*
     * if there are Mobile Country Code and Mobile Network Code values add
     * as HTTP headers
     */
    if (mcc != null && mnc != null) {
      requestUri = requestUri + "&mcc_mnc=" + mcc + "_" + mnc;
    } else {
      requestUri = requestUri + "&mcc_mnc=_";
    }

    HttpGet httpRequest = new HttpGet(requestUri);

    httpRequest.addHeader("Accept", "application/json");

    if (sourceIP != null) {
      httpRequest.addHeader("x-source-ip", sourceIP);
    }

    try {

      // TODO -workaround SSL errors

      HostnameVerifier hostnameVerifier =
          org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
      SchemeRegistry registry = new SchemeRegistry();
      SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
      socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
      registry.register(new Scheme("https", socketFactory, 443));
      HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);

      /*
       * get an instance of an HttpClient, the helper makes sure HTTP
       * Basic Authorization uses the consumer Key
       */
      HttpClient httpClient = HttpUtils.getHttpClient();
      HttpParams httpParams = httpRequest.getParams();
      httpParams.setParameter(ClientPNames.HANDLE_REDIRECTS, Boolean.TRUE);
      httpRequest.setParams(httpParams);

      /*
       * send the HTTP POST request and get the response
       */
      Log.d(TAG, "Making " + httpRequest.getMethod() + " request to " + httpRequest.getURI());
      HttpResponse httpResponse = httpClient.execute(httpRequest);

      Log.d(TAG, "Request completed with status=" + httpResponse.getStatusLine().getStatusCode());

      /*
       * obtain the headers from the httpResponse. Content-Type and
       * Location are particularly required
       */
      HashMap<String, String> headerMap = HttpUtils.getHeaders(httpResponse);

      Log.d(TAG, "headerMap =" + headerMap);

      String contentType = headerMap.get("content-type");
      String location = headerMap.get("location");

      /*
       * the status code from the HTTP response is also needed in
       * processing
       */
      int statusCode = httpResponse.getStatusLine().getStatusCode();

      Log.d(
          TAG,
          "status="
              + statusCode
              + " CT="
              + contentType
              + " Loc="
              + location
              + " JSON?"
              + HttpUtils.isJSON(contentType)
              + " HTML?"
              + HttpUtils.isHTML(contentType));

      /*
       * process a HTTP 200 (OK) response
       */
      if (statusCode == HttpStatus.SC_OK) {
        /*
         * if the response content type is json this will contain the
         * endpoint information
         */
        if (HttpUtils.isJSON(contentType)) {

          String logoResponse = HttpUtils.getContentsFromHttpResponse(httpResponse);

          Log.d(TAG, "Converting logo data " + logoResponse);

          Object json = JsonUtils.convertContent(logoResponse, contentType);
          LogoResponseArray logos = new LogoResponseArray(json);

          Log.d(
              TAG,
              "Have logo information "
                  + logos
                  + " # elemenst = "
                  + ((logos != null && logos.getLogos() != null) ? logos.getLogos().length : 0));

          if (logos != null && logos.getLogos() != null) {
            for (int i = 0; i < logos.getLogos().length; i++) {
              Log.d(TAG, "URL[" + i + "] = " + logos.getLogos()[i].getUrl());

              LogoCache.addLogoResponse(logos.getLogos()[i]);
            }
          }
        }

        /*
         * HTTP status code 302 is a redirect - there should also be a
         * location header
         */
        /*
         * any HTTP status code 400 or above is an error
         */
      } else if (statusCode >= HttpStatus.SC_BAD_REQUEST) {
        /*
         * read the contents of the response body
         */
        HttpEntity httpEntity = httpResponse.getEntity();
        InputStream is = httpEntity.getContent();
        String contents = HttpUtils.getContentsFromInputStream(is);

        /*
         * if the response content type is JSON return as the error
         */
        if (HttpUtils.isJSON(contentType)) {
          Object rawJSON = JsonUtils.convertContent(contents, contentType);
          if (rawJSON != null && rawJSON instanceof JSONObject) {
            errorResponse = (JSONObject) rawJSON;
          }
        } else {
          /*
           * non JSON data - just return the HTTP status code
           */
          errorResponse = JsonUtils.simpleError("HTTP " + statusCode, "HTTP " + statusCode);
        }
      } // is this request a redirection?

      /*
       * convert the various internal error types to displayable errors
       */
    } catch (UnsupportedEncodingException e) {
      errorResponse =
          JsonUtils.simpleError(
              "UnsupportedEncodingException", "UnsupportedEncodingException - " + e.getMessage());
    } catch (ClientProtocolException e) {
      Log.d(TAG, "ClientProtocolException=" + e.getMessage());
      errorResponse =
          JsonUtils.simpleError(
              "ClientProtocolException", "ClientProtocolException - " + e.getMessage());
    } catch (IOException e) {
      Log.d(TAG, "IOException=" + e.getMessage());
      errorResponse = JsonUtils.simpleError("IOException", "IOException - " + e.getMessage());
    } catch (JSONException e) {
      Log.d(TAG, "JSONException=" + e.getMessage());
      errorResponse = JsonUtils.simpleError("JSONException", "JSONException - " + e.getMessage());
    }

    return errorResponse;
  }