Example #1
0
 @Override
 //  public void onBandwidthSample(int elapsedMs, long bytes, long bitrateEstimate) {
 public void onBandwidthSample(
     String label, long startTime, long endTime, int elapsedMs, long bytes, long bitrateEstimate) {
   Log.d(
       TAG,
       label
           + " bandwidth ["
           + startTime
           + ", "
           + endTime
           + ", "
           + getSessionTimeString()
           + ", "
           + bytes
           + ", "
           + getTimeString(elapsedMs)
           + ", "
           + bitrateEstimate
           + ", "
           + bytes * 8 / elapsedMs
           + "kbps]");
   if (label.equals("video")) {
     this.videoGoodput.add(Pair.create(getSessionTimeString(), (double) bytes * 8000 / elapsedMs));
     this.videoGoodputEstimate.add(bitrateEstimate);
   } else if (label.equals("audio")) {
     this.audioGoodput.add(Pair.create(getSessionTimeString(), (double) bytes * 8000 / elapsedMs));
   }
   //    this.goodput.add(Pair.create(getSessionTimeString(), (double)bytes * 8000 / elapsedMs));
 }
Example #2
0
  @Feature({"AndroidWebView", "Downloads"})
  @SmallTest
  public void testDownload() throws Throwable {
    AwTestContainerView testView = createAwTestContainerViewOnMainSync(mContentsClient);
    AwContents awContents = testView.getAwContents();

    final String data = "download data";
    final String contentDisposition = "attachment;filename=\"download.txt\"";
    final String mimeType = "text/plain";

    List<Pair<String, String>> downloadHeaders = new ArrayList<Pair<String, String>>();
    downloadHeaders.add(Pair.create("Content-Disposition", contentDisposition));
    downloadHeaders.add(Pair.create("Content-Type", mimeType));
    downloadHeaders.add(Pair.create("Content-Length", Integer.toString(data.length())));

    TestWebServer webServer = null;
    try {
      webServer = new TestWebServer(false);
      final String pageUrl = webServer.setResponse("/download.txt", data, downloadHeaders);
      final OnDownloadStartHelper downloadStartHelper = mContentsClient.getOnDownloadStartHelper();
      final int callCount = downloadStartHelper.getCallCount();
      loadUrlAsync(awContents, pageUrl);
      downloadStartHelper.waitForCallback(callCount);

      assertEquals(pageUrl, downloadStartHelper.getUrl());
      assertEquals(contentDisposition, downloadStartHelper.getContentDisposition());
      assertEquals(mimeType, downloadStartHelper.getMimeType());
      assertEquals(data.length(), downloadStartHelper.getContentLength());
    } finally {
      if (webServer != null) webServer.shutdown();
    }
  }
Example #3
0
 /**
  * Identifies whether two strings are close enough that they are likely to be intended to be the
  * same string. Fuzzy matching is only performed on strings that are longer than a certain size.
  *
  * @return A pair with two values. First value represents a match: true if the two strings meet
  *     CommCare's fuzzy match definition, false otherwise. Second value is the actual string
  *     distance that was matched, in order to be able to rank or otherwise interpret results.
  */
 public static Pair<Boolean, Integer> fuzzyMatch(String a, String b) {
   // tweakable parameter: Minimum length before edit distance
   // starts being used (this is probably not necessary, and
   // basically only makes sure that "at" doesn't match "or" or similar
   if (b.length() > 3) {
     int distance = StringUtils.LevenshteinDistance(a, b);
     // tweakable parameter: edit distance past string length disparity
     if (distance <= 2) {
       return Pair.create(true, distance);
     }
   }
   return Pair.create(false, -1);
 }
Example #4
0
 protected void reject(String callId, int errorCode, String errorMsg, Pair... params)
     throws IllegalArgumentException {
   Pair[] newparams;
   if (params == null) {
     newparams = new Pair[2];
   } else {
     newparams = new Pair[params.length + 2];
   }
   newparams[0] = Pair.create("code", errorCode);
   newparams[1] = Pair.create("msg", errorMsg);
   if (params != null) {
     System.arraycopy(params, 0, newparams, 2, params.length);
   }
   reject(callId, newparams);
 }
Example #5
0
 public void onClick(View view) {
   StickerFragment.a(a, (StickerObj) view.getTag());
   StickerFragment.a(a, null);
   if (StickerFragment.a(a) != null) {
     if (StickerFragment.b(a).equals(de.a)) {
       int ai[] = new int[2];
       view.getLocationInWindow(ai);
       StickerFragment.a(
           a,
           ai,
           Pair.create(Integer.valueOf(view.getWidth()), Integer.valueOf(view.getHeight())),
           StickerFragment.a(a));
       return;
     }
     if (StickerFragment.c(a) != null) {
       StickerFragment.c(a).a(StickerFragment.d(a));
     }
     view = (f) StickerFragment.e(a).getAdapter();
     if (view != null) {
       view.a(StickerFragment.e(a).getCurrentItem(), StickerFragment.a(a));
     }
     if (StickerFragment.c(a) != null) {
       StickerFragment.c(a).a(StickerFragment.a(a));
       return;
     }
   }
 }
  private static final List<Pair<String, Long>> getInstalledLanguages(Context appContext) {
    final List<Pair<String, Long>> result = new ArrayList<Pair<String, Long>>();
    final File tessDir = Util.getTrainingDataDir(appContext);
    if (!tessDir.exists()) {
      return result;
    }
    final String[] languageFiles =
        tessDir.list(
            new FilenameFilter() {

              @Override
              public boolean accept(File dir, String filename) {
                if (filename.endsWith(".traineddata")) {
                  return true;
                }
                return false;
              }
            });

    for (final String val : languageFiles) {
      final int dotIndex = val.indexOf('.');
      if (dotIndex > -1) {
        File f = new File(tessDir, val);
        result.add(Pair.create(val.substring(0, dotIndex), f.length()));
      }
    }
    return result;
  }
  @Override
  public void onSpinnerItemSelected(Spinner spinner, int position) {
    final MissionItemType selectedType = commandAdapter.getItem(position);

    try {
      if (mSelectedProxies.isEmpty()) return;

      final List<Pair<MissionItemProxy, MissionItemProxy>> updatesList =
          new ArrayList<Pair<MissionItemProxy, MissionItemProxy>>(mSelectedProxies.size());

      for (MissionItemProxy missionItemProxy : mSelectedProxies) {
        final MissionItem oldItem = missionItemProxy.getMissionItem();
        if (oldItem.getType() != selectedType) {
          final MissionItem newItem = selectedType.getNewItem();

          if (oldItem instanceof MissionItem.SpatialItem
              && newItem instanceof MissionItem.SpatialItem) {
            ((MissionItem.SpatialItem) newItem)
                .setCoordinate(((MissionItem.SpatialItem) oldItem).getCoordinate());
          }

          updatesList.add(
              Pair.create(missionItemProxy, new MissionItemProxy(mMissionProxy, newItem)));
        }
      }

      if (!updatesList.isEmpty()) {
        mListener.onWaypointTypeChanged(selectedType, updatesList);
        dismiss();
      }
    } catch (IllegalArgumentException e) {
      e.printStackTrace();
    }
  }
  private void useAppCache() throws Exception {
    final String cachedFilePath = "/foo.js";
    final String cachedFileContents = "1 + 1;";
    mWebServer.setResponse(cachedFilePath, cachedFileContents, null);

    final String manifestPath = "/foo.manifest";
    final String manifestContents = "CACHE MANIFEST\nCACHE:\n" + cachedFilePath;
    List<Pair<String, String>> manifestHeaders = new ArrayList<Pair<String, String>>();
    manifestHeaders.add(Pair.create("Content-Disposition", "text/cache-manifest"));
    mWebServer.setResponse(manifestPath, manifestContents, manifestHeaders);

    final String pagePath = "/appcache.html";
    final String pageContents =
        "<html manifest=\""
            + manifestPath
            + "\">"
            + "<head><script src=\""
            + cachedFilePath
            + "\"></script></head></html>";
    String url = mWebServer.setResponse(pagePath, pageContents, null);

    loadUrlSync(mAwContents, mContentsClient.getOnPageFinishedHelper(), url);
    executeJavaScriptAndWaitForResult(
        mAwContents, mContentsClient, "window.applicationCache.update();");
  }
Example #9
0
  @Override
  protected Pair<Integer, Dictionary> doInBackground(final DictionaryBean... params) {
    // Get properties from bean.
    final DictionaryBean bean = params[0];
    final int id = bean.getId();
    final String path = bean.getPath();
    final String type = bean.getType();

    try {
      // Create callables.
      Dictionary dictionary;
      if (type.equals(ChosenModel.LOCAL_DICTIONARY)) {
        // Create dict info.
        final DictionaryInformation info = DictionaryInformation.create(path);
        // Create necessary files.
        final IndexFile indexFile = IndexFile.makeFile(info.getIndexFile());
        final DictionaryFile dictionaryFile =
            DictionaryFile.makeRandomAccessFile(info.getDataFile());
        dictionary =
            new DICTDictionary.Builder(indexFile, dictionaryFile)
                .enableSplittingIndexFile()
                .build();
      } else {
        dictionary = new WikiDictionary(path);
      }
      return Pair.create(id, dictionary);
    } catch (final FileNotFoundException e) {
      Log.w(TAG, e.getMessage(), e);
      return null;
    }
  }
  @MediumTest
  @Feature({"AndroidWebView", "Privacy"})
  public void testAcceptCookie() throws Throwable {
    TestWebServer webServer = null;
    try {
      webServer = new TestWebServer(false);
      String path = "/cookie_test.html";
      String responseStr = "<html><head><title>TEST!</title></head><body>HELLO!</body></html>";
      String url = webServer.setResponse(path, responseStr, null);

      mCookieManager.setAcceptCookie(false);
      assertFalse(mCookieManager.acceptCookie());

      loadUrlSync(mAwContents, mContentsClient.getOnPageFinishedHelper(), url);
      setCookieWithJavaScript("test1", "value1");
      assertNull(mCookieManager.getCookie(url));

      List<Pair<String, String>> responseHeaders = new ArrayList<Pair<String, String>>();
      responseHeaders.add(Pair.create("Set-Cookie", "header-test1=header-value1; path=" + path));
      url = webServer.setResponse(path, responseStr, responseHeaders);
      loadUrlSync(mAwContents, mContentsClient.getOnPageFinishedHelper(), url);
      assertNull(mCookieManager.getCookie(url));

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

      url = webServer.setResponse(path, responseStr, null);
      loadUrlSync(mAwContents, mContentsClient.getOnPageFinishedHelper(), url);
      setCookieWithJavaScript("test2", "value2");
      waitForCookie(url);
      String cookie = mCookieManager.getCookie(url);
      assertNotNull(cookie);
      validateCookies(cookie, "test2");

      responseHeaders = new ArrayList<Pair<String, String>>();
      responseHeaders.add(Pair.create("Set-Cookie", "header-test2=header-value2 path=" + path));
      url = webServer.setResponse(path, responseStr, responseHeaders);
      loadUrlSync(mAwContents, mContentsClient.getOnPageFinishedHelper(), url);
      waitForCookie(url);
      cookie = mCookieManager.getCookie(url);
      assertNotNull(cookie);
      validateCookies(cookie, "test2", "header-test2");
    } finally {
      if (webServer != null) webServer.shutdown();
    }
  }
Example #11
0
 public void appTransitionStarting(long startTime, long duration) {
   synchronized (mList) {
     mHandler.removeMessages(MSG_APP_TRANSITION_STARTING);
     mHandler
         .obtainMessage(MSG_APP_TRANSITION_STARTING, Pair.create(startTime, duration))
         .sendToTarget();
   }
 }
Example #12
0
  public EventLogger() {
    loadStartTimeMs = new long[DemoPlayer.RENDERER_COUNT];

    this.dropFrameTime = new ArrayList<String>();
    this.videoBitrateVarience = new ArrayList<Pair<String, Integer>>();
    this.audioBitrateVarience = new ArrayList<Pair<String, Integer>>();
    this.rebufferTime = new ArrayList<Double>();
    this.videoGoodput = new ArrayList<Pair<String, Double>>();
    this.videoGoodputEstimate = new ArrayList<Long>();
    this.audioGoodput = new ArrayList<Pair<String, Double>>();
    this.videoBitrateVarience.add(Pair.create("0.00", 0));
    this.previousVideoBitrate = 0;
    this.audioBitrateVarience.add(Pair.create("0.00", 0));
    this.previousAudioBitrate = 0;
    this.switchToSteadyStateTime = -1;
    this.totalBytesDownloaded = 0;
  }
Example #13
0
  @Override
  public void onStateChanged(boolean playWhenReady, int state) {
    Log.d(
        TAG,
        "state ["
            + getSessionTimeString()
            + ", "
            + playWhenReady
            + ", "
            + getStateString(state)
            + "]");
    //    DecimalFormat df = new DecimalFormat("#.##");
    switch (state) {
      case ExoPlayer.STATE_PREPARING:
        //        this.bitrateVarience.add(Pair.create("0.00", currentBitrate));
        this.initialLoadingTime_s = Double.parseDouble(getSessionTimeString());
        break;

      case ExoPlayer.STATE_BUFFERING:
        bufferCounter++;
        bufferTime_s = Double.parseDouble(getSessionTimeString());
        break;
      case ExoPlayer.STATE_READY:
        if (bufferCounter == 1) {
          this.initialLoadingTime =
              Double.parseDouble(
                  String.format(
                      "%.2f",
                      Double.parseDouble(getSessionTimeString()) - this.initialLoadingTime_s));
        } else {
          this.rebufferTime.add(
              Double.parseDouble(
                  String.format(
                      "%.2f", Double.parseDouble(getSessionTimeString()) - bufferTime_s)));
        }
        break;
      case ExoPlayer.STATE_ENDED:
        this.videoBitrateVarience.add(
            Pair.create(getSessionTimeString(), this.previousVideoBitrate));
        this.audioBitrateVarience.add(
            Pair.create(getSessionTimeString(), this.previousAudioBitrate));
        //        printStatInfo();
        break;
    }
  }
 static Pair<Size, Size> parseSizeRange(Object o) {
   try {
     String s = (String) o;
     int ix = s.indexOf('-');
     if (ix >= 0) {
       return Pair.create(Size.parseSize(s.substring(0, ix)), Size.parseSize(s.substring(ix + 1)));
     }
     Size value = Size.parseSize(s);
     return Pair.create(value, value);
   } catch (ClassCastException e) {
   } catch (NumberFormatException e) {
   } catch (NullPointerException e) {
     return null;
   } catch (IllegalArgumentException e) {
   }
   Log.w(TAG, "could not parse size range '" + o + "'");
   return null;
 }
Example #15
0
 @Override
 public void onAudioFormatEnabled(String formatId, int trigger, int mediaTimeMs) {
   int currentBitrate = Id2Bitrate.get(formatId);
   Log.d(
       TAG,
       "audioFormat ["
           + getSessionTimeString()
           + ", "
           + formatId
           + ", "
           + Integer.toString(trigger)
           + ", "
           + currentBitrate / 1000
           + "kbps"
           + "]");
   this.audioBitrateVarience.add(Pair.create(getSessionTimeString(), this.previousAudioBitrate));
   this.audioBitrateVarience.add(Pair.create(getSessionTimeString(), currentBitrate));
   this.previousAudioBitrate = currentBitrate;
 }
Example #16
0
    protected Pair<GroupList, List<ChildrenList>> doInBackground(Void... arg0) {
      Cursor cursor = BrowserDB.getRecentHistory(getContentResolver(), MAX_RESULTS);

      Date now = new Date();
      now.setHours(0);
      now.setMinutes(0);
      now.setSeconds(0);

      long today = now.getTime();

      // Split the list of urls into separate date range groups
      // and show it in an expandable list view.
      List<ChildrenList> childrenLists = new LinkedList<ChildrenList>();
      ChildrenList children = null;
      GroupList groups = new GroupList();
      HistorySection section = null;

      // Move cursor before the first row in preparation
      // for the iteration.
      cursor.moveToPosition(-1);

      // Split the history query results into adapters per time
      // section (today, yesterday, week, older). Queries on content
      // Browser content provider don't support limitting the number
      // of returned rows so we limit it here.
      while (cursor.moveToNext()) {
        long time = cursor.getLong(cursor.getColumnIndexOrThrow(URLColumns.DATE_LAST_VISITED));
        HistorySection itemSection = getSectionForTime(time, today);

        if (section != itemSection) {
          if (section != null) {
            groups.add(createGroupItem(section));
            childrenLists.add(children);
          }

          section = itemSection;
          children = new ChildrenList();
        }

        children.add(createHistoryItem(cursor));
      }

      // Add any remaining section to the list if it hasn't
      // been added to the list after the loop.
      if (section != null && children != null) {
        groups.add(createGroupItem(section));
        childrenLists.add(children);
      }

      // Close the query cursor as we won't use it anymore
      cursor.close();

      // groups and childrenLists will be empty lists if there's no history
      return Pair.<GroupList, List<ChildrenList>>create(groups, childrenLists);
    }
 public static ActivityOptionsCompat21 makeSceneTransitionAnimation(
     Activity paramActivity, View[] paramArrayOfView, String[] paramArrayOfString) {
   Pair[] arrayOfPair = null;
   if (paramArrayOfView != null) {
     arrayOfPair = new Pair[paramArrayOfView.length];
     for (int i = 0; i < arrayOfPair.length; i++)
       arrayOfPair[i] = Pair.create(paramArrayOfView[i], paramArrayOfString[i]);
   }
   return new ActivityOptionsCompat21(
       ActivityOptions.makeSceneTransitionAnimation(paramActivity, arrayOfPair));
 }
Example #18
0
 /**
  * Adds an external subtitle source file (from the provided input stream.)
  *
  * <p>Note that a single external subtitle source may contain multiple or no supported tracks in
  * it. If the source contained at least one track in it, one will receive an {@link
  * MediaPlayer#MEDIA_INFO_METADATA_UPDATE} info message. Otherwise, if reading the source takes
  * excessive time, one will receive a {@link MediaPlayer#MEDIA_INFO_SUBTITLE_TIMED_OUT} message.
  * If the source contained no supported track (including an empty source file or null input
  * stream), one will receive a {@link MediaPlayer#MEDIA_INFO_UNSUPPORTED_SUBTITLE} message. One
  * can find the total number of available tracks using {@link MediaPlayer#getTrackInfo()} to see
  * what additional tracks become available after this method call.
  *
  * @param is input stream containing the subtitle data. It will be closed by the media framework.
  * @param format the format of the subtitle track(s). Must contain at least the mime type ({@link
  *     MediaFormat#KEY_MIME}) and the language ({@link MediaFormat#KEY_LANGUAGE}) of the file. If
  *     the file itself contains the language information, specify "und" for the language.
  */
 public void addSubtitleSource(InputStream is, MediaFormat format) {
   if (mMediaPlayer == null) {
     mPendingSubtitleTracks.add(Pair.create(is, format));
   } else {
     try {
       // mMediaPlayer.addSubtitleSource(is, format);
     } catch (IllegalStateException e) {
       mInfoListener.onInfo(mMediaPlayer, MediaPlayer.MEDIA_INFO_UNSUPPORTED_SUBTITLE, 0);
     }
   }
 }
Example #19
0
  @SmallTest
  @Feature({"AndroidWebView"})
  public void testClearCacheMemoryAndDisk() throws Throwable {
    final AwTestContainerView testContainer = createAwTestContainerViewOnMainSync(mContentsClient);
    final AwContents awContents = testContainer.getAwContents();

    TestWebServer webServer = null;
    try {
      webServer = new TestWebServer(false);
      final String pagePath = "/clear_cache_test.html";
      List<Pair<String, String>> headers = new ArrayList<Pair<String, String>>();
      // Set Cache-Control headers to cache this request. One century should be long enough.
      headers.add(Pair.create("Cache-Control", "max-age=3153600000"));
      headers.add(Pair.create("Last-Modified", "Wed, 3 Oct 2012 00:00:00 GMT"));
      final String pageUrl =
          webServer.setResponse(pagePath, "<html><body>foo</body></html>", headers);

      // First load to populate cache.
      clearCacheOnUiThread(awContents, true);
      loadUrlSync(awContents, mContentsClient.getOnPageFinishedHelper(), pageUrl);
      assertEquals(1, webServer.getRequestCount(pagePath));

      // Load about:blank so next load is not treated as reload by webkit and force
      // revalidate with the server.
      loadUrlSync(awContents, mContentsClient.getOnPageFinishedHelper(), "about:blank");

      // No clearCache call, so should be loaded from cache.
      loadUrlSync(awContents, mContentsClient.getOnPageFinishedHelper(), pageUrl);
      assertEquals(1, webServer.getRequestCount(pagePath));

      // Same as above.
      loadUrlSync(awContents, mContentsClient.getOnPageFinishedHelper(), "about:blank");

      // Clear cache, so should hit server again.
      clearCacheOnUiThread(awContents, true);
      loadUrlSync(awContents, mContentsClient.getOnPageFinishedHelper(), pageUrl);
      assertEquals(2, webServer.getRequestCount(pagePath));
    } finally {
      if (webServer != null) webServer.shutdown();
    }
  }
Example #20
0
 @Override
 protected void onDialogClosed(boolean positiveResult) {
   if (positiveResult) {
     if (isPersistent()) {
       persistString(
           valueToString(
               getContext(),
               Pair.create(timePicker.getCurrentHour(), timePicker.getCurrentMinute())));
     }
     callChangeListener(positiveResult);
   }
 }
  @SuppressLint("NewApi")
  public void onActivityAnim(View view) {
    if (Build.VERSION.SDK_INT >= 21) {
      getWindow().setSharedElementEnterTransition(new Explode());

      Intent intent = new Intent(this, ShareActivityB.class);
      // 一个共有元素
      //			 ActivityOptions options =
      //			 ActivityOptions.makeSceneTransitionAnimation(
      //			 this, mViewImage, "image");

      // 多个共有元素
      Pair[] pairs = new Pair[2];
      pairs[0] = Pair.create(mViewContent, "text");
      pairs[1] = Pair.create(mViewImage, "image");
      ActivityOptions options =
          ActivityOptions.makeSceneTransitionAnimation(ShareActivityA.this, pairs);
      startActivity(intent, options.toBundle());
    } else {
      Toast.makeText(this, "sorry~", Toast.LENGTH_SHORT).show();
    }
  }
    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);

      setListAdapter(
          new PairAdapter(
              getActivity(),
              new Pair[] {
                Pair.create("Regular ProgressDialog", ""),
                Pair.create(
                    "Delayed ProgressDialog",
                    "ProgressDialog that waits a minimum time to be dismissed before showing"),
                Pair.create(
                    "With custom delay",
                    "Basic progress dialog with default 2 seconds delay. (Default it 500ms)"),
                Pair.create(
                    "Min Show Time",
                    "Once visible, the progress bar will be visible for a minimum amount of time to avoid flashes in the UI.\nWhen you click this, the ProgressDialog will be delayed 1 seconds and then dismissed after exactly 100ms. Because of the minShowTime, it will be visible for 500ms."),
                Pair.create(
                    "No Min Show Time",
                    "This does not have minShowTime (and causes flashes in the UI) to see the difference.")
              }));
    }
 /*
  * Finds a system apk which had a broadcast receiver listening to a particular action.
  * @param action intent action used to find the apk
  * @return a pair of apk package name and the resources.
  */
 static Pair<String, Resources> findSystemApk(String action, PackageManager pm) {
   final Intent intent = new Intent(action);
   for (ResolveInfo info : pm.queryBroadcastReceivers(intent, 0)) {
     if (info.activityInfo != null
         && (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
       final String packageName = info.activityInfo.packageName;
       try {
         final Resources res = pm.getResourcesForApplication(packageName);
         return Pair.create(packageName, res);
       } catch (NameNotFoundException e) {
         Log.w(TAG, "Failed to find resources for " + packageName);
       }
     }
   }
   return null;
 }
Example #24
0
  @Test
  public void itShouldReturnOrdinalDayOfMonth() {
    Calendar cal = Calendar.getInstance();
    cal.setTime(new Date());

    Pair<Integer, String>[] ordinalTests =
        new Pair[] {
          Pair.create(1, "1st"),
          Pair.create(2, "2nd"),
          Pair.create(3, "3rd"),
          Pair.create(4, "4th"),
          Pair.create(11, "11th"),
          Pair.create(21, "21st"),
          Pair.create(22, "22nd"),
          Pair.create(23, "23rd"),
          Pair.create(24, "24th")
        };

    for (Pair<Integer, String> ordinalTest : ordinalTests) {
      cal.set(Calendar.DAY_OF_MONTH, ordinalTest.first);
      assertThat(CalendarUtils.getOrdinalDayOfMonth(cal)).isEqualTo(ordinalTest.second);
      assertThat(CalendarUtils.getOrdinalDayOfMonth(cal.getTime())).isEqualTo(ordinalTest.second);
    }
  }
  /**
   * Static method used for activities to show snackbar that notifies user that the bookmark has
   * been added successfully. Note this method also starts fetching salient image in background.
   */
  public static void addBookmarkAndShowSnackbar(
      EnhancedBookmarksModel bookmarkModel,
      Tab tab,
      final SnackbarManager snackbarManager,
      final Activity activity) {
    // TODO(ianwen): remove activity from argument list.
    final BookmarkId enhancedId =
        bookmarkModel.addBookmark(
            bookmarkModel.getDefaultFolder(), 0, tab.getTitle(), tab.getUrl());

    Pair<EnhancedBookmarksModel, BookmarkId> pair = Pair.create(bookmarkModel, enhancedId);

    SnackbarController snackbarController =
        new SnackbarController() {
          @Override
          public void onDismissForEachType(boolean isTimeout) {}

          @Override
          public void onDismissNoAction(Object actionData) {
            // This method will be called only if the snackbar is dismissed by timeout.
            @SuppressWarnings("unchecked")
            Pair<EnhancedBookmarksModel, BookmarkId> pair =
                (Pair<EnhancedBookmarksModel, BookmarkId>) actionData;
            pair.first.destroy();
          }

          @Override
          public void onAction(Object actionData) {
            @SuppressWarnings("unchecked")
            Pair<EnhancedBookmarksModel, BookmarkId> pair =
                (Pair<EnhancedBookmarksModel, BookmarkId>) actionData;
            // Show edit activity with the name of parent folder highlighted.
            startEditActivity(activity, enhancedId);
            pair.first.destroy();
          }
        };
    snackbarManager.showSnackbar(
        null,
        activity.getString(R.string.enhanced_bookmark_page_saved),
        activity.getString(R.string.enhanced_bookmark_item_edit),
        pair,
        snackbarController);
  }
  public static Pair<File, Long> getLastestDump(Context c) {
    long newestDumpTime = 0;
    File newestDumpFile = null;

    if (c.getCacheDir() == null) return null;

    for (File f : c.getCacheDir().listFiles()) {
      if (!f.getName().endsWith(".dmp")) continue;

      if (newestDumpTime < f.lastModified()) {
        newestDumpTime = f.lastModified();
        newestDumpFile = f;
      }
    }
    // Ignore old dumps
    if (System.currentTimeMillis() - 48 * 60 * 1000 > newestDumpTime) return null;

    return Pair.create(newestDumpFile, newestDumpTime);
  }
  @Override
  public void produceResults(final Consumer<T> consumer, final ProducerContext producerContext) {
    final ProducerListener producerListener = producerContext.getListener();
    producerListener.onProducerStart(producerContext.getId(), PRODUCER_NAME);

    boolean delayRequest;
    synchronized (this) {
      if (mNumCurrentRequests >= mMaxSimultaneousRequests) {
        mPendingRequests.add(Pair.create(consumer, producerContext));
        delayRequest = true;
      } else {
        mNumCurrentRequests++;
        delayRequest = false;
      }
    }

    if (!delayRequest) {
      produceResultsInternal(consumer, producerContext);
    }
  }
 private String addPageToTestServer(TestWebServer webServer, String httpPath, String html) {
   List<Pair<String, String>> headers = new ArrayList<Pair<String, String>>();
   headers.add(Pair.create("Content-Type", "text/html"));
   headers.add(Pair.create("Cache-Control", "no-store"));
   return webServer.setResponse(httpPath, html, headers);
 }
 /**
  * Creates a response on the TestWebServer which attempts to set a cookie when fetched.
  *
  * @param webServer the webServer on which to create the response
  * @param path the path component of the url (e.g "/cookie_test.html")
  * @param key the key of the cookie
  * @param value the value of the cookie
  * @return the url which gets the response
  */
 private String makeCookieUrl(TestWebServer webServer, String path, String key, String value) {
   String response = "";
   List<Pair<String, String>> responseHeaders = new ArrayList<Pair<String, String>>();
   responseHeaders.add(Pair.create("Set-Cookie", key + "=" + value + "; path=" + path));
   return webServer.setResponse(path, response, responseHeaders);
 }
Example #30
0
 public Intent endSession() {
   Log.d(TAG, "end [" + getSessionTimeString() + "]");
   this.videoBitrateVarience.add(Pair.create(getSessionTimeString(), this.previousVideoBitrate));
   this.audioBitrateVarience.add(Pair.create(getSessionTimeString(), this.previousAudioBitrate));
   return printStatInfo();
 }