Пример #1
0
  /**
   * Convert time from milliseconds to hh:mm format.
   *
   * @param milliseconds
   * @return Equal time in hh:mm
   */
  public static String millisecondsToTimeString(long milliseconds) {
    long hours = TimeUnit.MILLISECONDS.toHours(milliseconds);
    long minutes = TimeUnit.MILLISECONDS.toMinutes(milliseconds);
    long hoursInMinutes = TimeUnit.HOURS.toMinutes(hours);

    return pad((int) hours) + ":" + pad((int) (minutes - hoursInMinutes));
  }
Пример #2
0
  @Deprecated
  private void updatePlaytime(int currentTime) {
    StringBuilder playbackStr = new StringBuilder();

    long totalDuration = 0;

    if (getMediaPlayer() != null) {
      try {
        totalDuration = getMediaPlayer().getDuration();
      } catch (Exception e) {
        app2 mapp = (app2) context.getApplicationContext();
        mapp.getInstance().trackException(e);
        e.printStackTrace();
      }
    }

    // set total time as the audio is being played
    if (totalDuration != 0) {
      playbackStr.append(
          String.format(
              "%02d:%02d",
              TimeUnit.MILLISECONDS.toMinutes((long) totalDuration),
              TimeUnit.MILLISECONDS.toSeconds((long) totalDuration)
                  - TimeUnit.MINUTES.toSeconds(
                      TimeUnit.MILLISECONDS.toMinutes((long) totalDuration))));
    } else {
      Log.w(TAG, "Something strage this audio track duration in zero");
    }

    mTotalTime.setText(playbackStr);

    // DebugLog.i(currentTime + " / " + totalDuration);
  }
Пример #3
0
  /*
  Fast but not so readable. From here: http://stackoverflow.com/questions/9027317/how-to-convert-milliseconds-to-hhmmss-format
   */
  public static String msToString(final long millis) {
    long seconds =
        TimeUnit.MILLISECONDS.toSeconds(millis)
            - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis));
    long minutes =
        TimeUnit.MILLISECONDS.toMinutes(millis)
            - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis));
    long hours = TimeUnit.MILLISECONDS.toHours(millis);

    StringBuilder b = new StringBuilder();

    if (hours > 0) {
      b.append(hours < 10 ? String.valueOf("" + hours) : String.valueOf(hours));
      b.append(":");
    }

    b.append(
        minutes == 0
            ? "00"
            : minutes < 10 ? String.valueOf("0" + minutes) : String.valueOf(minutes));
    b.append(":");
    b.append(
        seconds == 0
            ? "00"
            : seconds < 10 ? String.valueOf("0" + seconds) : String.valueOf(seconds));
    return b.toString();
  }
Пример #4
0
  public String getTotalTime() {
    double totalTime = 0;
    String startTimeForDay = getStartTime();
    String endTimeForDay = getLastEndTimeForDay();

    if (endTimeForDay == null || startTimeForDay == null) {
      return "0";
    }
    Calendar cal = Calendar.getInstance();
    String[] endTime = endTimeForDay.split(":");
    cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(endTime[0]));
    cal.set(Calendar.MINUTE, Integer.parseInt(endTime[1]));
    long end = cal.getTimeInMillis();

    String[] startTime = startTimeForDay.split(":");
    cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(startTime[0]));
    cal.set(Calendar.MINUTE, Integer.parseInt(startTime[1]));
    long start = cal.getTimeInMillis();

    long diff = end - start;
    long hours = TimeUnit.MILLISECONDS.toHours(diff);
    long minutes = TimeUnit.MILLISECONDS.toMinutes(diff - (hours * 60 * 60 * 1000));
    double minuteD = (double) minutes / 60;

    // return DecimalFormatUtil.getFormattedData(totalTime);
    return hours + " hours" + minutes + " minutes";
  }
 /**
  * Format the time the current crawl run has taken into a more readable format.
  *
  * @param timeCrawlCalc the time to display
  * @return the formatted time in X min, X sec layout.
  */
 private String formatRunningTime(long timeCrawlCalc) {
   return String.format(
       "%d min, %d sec",
       TimeUnit.MILLISECONDS.toMinutes(timeCrawlCalc),
       TimeUnit.MILLISECONDS.toSeconds(timeCrawlCalc)
           - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(timeCrawlCalc)));
 }
Пример #6
0
  @Test
  public void testBaseMetaChange() throws Exception {
    startEngine();

    m_curator
        .setData()
        .forPath(ZKPathUtils.getBaseMetaVersionZkPath(), ZKSerializeUtils.serialize(100L));

    int retries = 50;
    int i = 0;
    while (m_baseMetaChangeCount.get() != 1 && i++ < retries) {
      TimeUnit.MILLISECONDS.sleep(100);
    }
    assertEquals(1, m_baseMetaChangeCount.get());

    m_curator
        .setData()
        .forPath(ZKPathUtils.getBaseMetaVersionZkPath(), ZKSerializeUtils.serialize(200L));

    i = 0;
    while (m_baseMetaChangeCount.get() != 2 && i++ < retries) {
      TimeUnit.MILLISECONDS.sleep(100);
    }
    assertEquals(2, m_baseMetaChangeCount.get());
  }
  /**
   * Tests {@link Lease#createInstance(long, int, String)}. When the slave timeZone is in Japan and
   * the local server is here.
   */
  @Test
  public void testLeaseCreateInstanceJapan() {
    // Given a time of 10am in Japan, get the server time
    Calendar japanCal = new GregorianCalendar(TimeZone.getTimeZone("Japan"));

    japanCal.set(Calendar.HOUR_OF_DAY, 10); // 0..23
    japanCal.set(Calendar.MINUTE, 0);
    japanCal.set(Calendar.SECOND, 0);

    long japanOffsetMs = japanCal.getTimeZone().getRawOffset();
    if (japanCal.getTimeZone().inDaylightTime(japanCal.getTime())) {
      japanOffsetMs += japanCal.getTimeZone().getDSTSavings();
    }
    int seconds = (int) TimeUnit.MILLISECONDS.toSeconds(japanOffsetMs);

    Lease lease = Lease.createInstance(japanCal.getTimeInMillis(), seconds, "Japan RuleZ");

    Calendar local = new GregorianCalendar();
    long localOffsetMs = local.getTimeZone().getRawOffset();
    if (local.getTimeZone().inDaylightTime(local.getTime())) {
      localOffsetMs += local.getTimeZone().getDSTSavings();
    }
    int localOffset = (int) TimeUnit.MILLISECONDS.toHours(localOffsetMs);
    int japanOffset = (int) TimeUnit.SECONDS.toHours(seconds);

    // "time in zone B" = ("time in zone A" - "UTC offset for zone A" + "UTC offset for zone B") %
    // 24.
    int resultTime = 10 - japanOffset + localOffset;
    if (resultTime < 0) resultTime += 24;
    assertEquals(resultTime, lease.getServerTime().get(Calendar.HOUR_OF_DAY));
  }
Пример #8
0
 public long periodStringToMillis(String p) {
   Matcher m = periodPattern.matcher(p);
   String s;
   int num;
   String unit;
   long millis = 0;
   while (m.find()) {
     s = m.group();
     num = Integer.parseInt(s.substring(0, s.length() - 1), 10);
     unit = s.substring(s.length() - 1).toLowerCase();
     if (unit.equals("d")) {
       millis += TimeUnit.MILLISECONDS.convert(num, TimeUnit.DAYS);
     } else if (unit.equals("h")) {
       millis += TimeUnit.MILLISECONDS.convert(num, TimeUnit.HOURS);
     } else if (unit.equals("m")) {
       millis += TimeUnit.MILLISECONDS.convert(num, TimeUnit.MINUTES);
     } else if (unit.equals("s")) {
       millis += TimeUnit.MILLISECONDS.convert(num, TimeUnit.SECONDS);
     }
   }
   if (millis == 0) {
     millis = Long.MAX_VALUE;
   }
   return millis;
 }
Пример #9
0
  public static void main(String[] args) throws Exception {
    ExecutorService exec = Executors.newCachedThreadPool();
    for (int i = 0; i < 5; i++) exec.execute(new Task());
    exec.execute(new Task2());
    Timer timer = new Timer();
    timer.scheduleAtFixedRate(
        new TimerTask() {
          boolean prod = true;

          public void run() {
            if (prod) {
              System.out.print("\nnotify() ");
              Task.blocker.prod();
              prod = false;
            } else {
              System.out.print("\nnotifyAll() ");
              Task.blocker.prodAll();
              prod = true;
            }
          }
        },
        400,
        400); // Run every .4 second
    TimeUnit.SECONDS.sleep(5); // Run for a while...
    timer.cancel();
    System.out.println("\nTimer canceled");
    TimeUnit.MILLISECONDS.sleep(500);
    System.out.print("Task2.blocker.prodAll() ");
    Task2.blocker.prodAll();
    TimeUnit.MILLISECONDS.sleep(500);
    System.out.println("\nShutting down");
    exec.shutdownNow(); // Interrupt all tasks
  }
        @Override
        public void onReceive(Context context, Intent intent) {
          // Get Bundles
          Bundle extras = intent.getExtras();
          // Unwrap bundle object
          runTemp = extras.getDouble(TempService.TEMPKEY); // Hopfully get the temp.
          double runRoc = extras.getDouble(TempService.ROCKEY); // Hopfully get the RoC.
          long currentTime = extras.getLong(TempService.TIMEKEY); // Hopfully get the time.
          int currentPower = extras.getInt(TempService.POWERKEY); // Hopfully get the Power.
          double wantedRoC = extras.getDouble(TempService.WROCKEY); // Desired RoC

          if (currentPower != tempBar.getProgress()) {
            tempBar.setProgress(currentPower);
            sendMessage("A" + String.format("%04d", currentPower));
          }

          if (runTemp > maxTempValue) {
            maxTempValue = runTemp;
            dispMaxT.setText("Max Temp: " + String.format("%5.2f", runTemp));
          }
          liveGraphXYSeries.add(currentTime / 10000, runTemp);
          mChartView.repaint();

          dispRunTime.setText(
              "Time: "
                  + String.format(
                      "%d:%02d",
                      TimeUnit.MILLISECONDS.toMinutes(currentTime),
                      TimeUnit.MILLISECONDS.toSeconds(currentTime)
                          - TimeUnit.MINUTES.toSeconds(
                              TimeUnit.MILLISECONDS.toMinutes(currentTime))));
          dispTemp.setText("Temp: " + String.format("%5.2f", runTemp));
          dispRoc.setText("Roc: " + String.format("%5.2f", runRoc) + "/min");
          dispWRoC.setText("Target RoC: " + String.format("%5.2f", wantedRoC));
        }
  @Test
  public void testRespectsTime() throws Exception {
    final long startTime = System.nanoTime();
    final AtomicLong currentTime = new AtomicLong(startTime);
    Ticker ticker =
        new Ticker() {
          @Override
          public long read() {
            return currentTime.get();
          }
        };
    ProportionalZoneFailureDetector detector =
        new ProportionalZoneFailureDetector(2, Duration.ONE_HOUR, 0.9, ticker);

    for (int i = 0; i < 2; i++) {
      detector.onStartupFailure(loc1, entity1, new Throwable("simulated failure"));
    }
    assertTrue(detector.hasFailed(loc1));

    currentTime.set(startTime + TimeUnit.MILLISECONDS.toNanos(1000 * 60 * 60 - 1));
    assertTrue(detector.hasFailed(loc1));

    currentTime.set(startTime + TimeUnit.MILLISECONDS.toNanos(1000 * 60 * 60 + 1));
    assertFalse(detector.hasFailed(loc1));
  }
Пример #12
0
  @TargetApi(Build.VERSION_CODES.GINGERBREAD)
  @Override
  public void onTick(long millisUntilFinished) {

    // Change milliseconds into MM:SS
    String timeLeft =
        String.format(
            "%d : %02d",
            TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished),
            TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished)
                - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)));

    // Display the countdown
    countdown.setText(timeLeft);

    // Check to see if it's time to change the sprite
    if (!sprite.omelette) {
      if (((millisUntilFinished <= 0.8 * duration) && sprite.eggStatus == 1)
          || // 80% done
          ((millisUntilFinished <= 0.6 * duration) && sprite.eggStatus == 2)
          || // 60% done
          ((millisUntilFinished <= 0.4 * duration) && sprite.eggStatus == 3)
          || // 40% done
          ((millisUntilFinished <= 0.2 * duration) && sprite.eggStatus == 4)) { // 20% done

        sprite.nextStatus();
      }
    }
  }
Пример #13
0
  @Override
  public void elaborate(Configuration config, Results results, long timeTaken) {
    super.elaborate(config, results, timeTaken);
    // saving results
    System.out.println("Saving results...");
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
    String dateFormatted = sdf.format(new Date());
    String pathOfFile =
        config.getOutputFolder().getAbsolutePath()
            + File.separator
            + "results-"
            + dateFormatted
            + ".json";
    saveToJson(results, pathOfFile);

    String time =
        String.format(
            "%d h, %d m, %d s",
            TimeUnit.MILLISECONDS.toHours(timeTaken),
            TimeUnit.MILLISECONDS.toMinutes(timeTaken)
                - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(timeTaken)),
            TimeUnit.MILLISECONDS.toSeconds(timeTaken)
                - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(timeTaken)));
    System.out.println("Time taken: " + time);
  }
  @Test(timeout = 60000)
  public void testNotIdledWhenInUse() throws Exception {
    pooledFactory.setIdleTimeout(10);
    PooledConnection connection = (PooledConnection) pooledFactory.createConnection();
    Session s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

    // let connection to get idle
    TimeUnit.MILLISECONDS.sleep(500);

    // get a connection from pool again, it should be the same underlying connection
    // as before and should not be idled out since an open session exists.
    PooledConnection connection2 = (PooledConnection) pooledFactory.createConnection();
    assertSame(connection.getConnection(), connection2.getConnection());

    // now the session is closed even when it should not be
    try {
      // any operation on session first checks whether session is closed
      s.getTransacted();
    } catch (javax.jms.IllegalStateException e) {
      assertTrue("Session should be fine, instead: " + e.getMessage(), false);
    }

    Connection original = connection.getConnection();

    connection.close();
    connection2.close();

    // let connection to get idle
    TimeUnit.MILLISECONDS.sleep(500);

    // get a connection from pool again, it should be a new Connection instance as the
    // old one should have been inactive and idled out.
    PooledConnection connection3 = (PooledConnection) pooledFactory.createConnection();
    assertNotSame(original, connection3.getConnection());
  }
Пример #15
0
  /**
   * Convert time from milliseconds to hh:mm format.
   *
   * @param milliseconds
   * @return Equal time in xx hours xx minutes
   */
  public static int[] millisecondsToTime(long milliseconds) {
    long hours = TimeUnit.MILLISECONDS.toHours(milliseconds);
    long minutes = TimeUnit.MILLISECONDS.toMinutes(milliseconds);
    long hoursInMinutes = TimeUnit.HOURS.toMinutes(hours);

    return new int[] {(int) hours, (int) (minutes - hoursInMinutes)};
  }
Пример #16
0
  private void updateRuntime(int currentTime) {

    if (mRunTime == null) {
      // this view can be null if the user
      // does not want to use it. Don't throw
      // an exception.
      return;
    }

    if (currentTime < 0) {
      throw new IllegalArgumentException(ERROR_PLAYTIME_CURRENT_NEGATIVE);
    }

    StringBuilder playbackStr = new StringBuilder();

    // set the current time
    // its ok to show 00:00 in the UI
    playbackStr.append(
        String.format(
            "%02d:%02d",
            TimeUnit.MILLISECONDS.toMinutes((long) currentTime),
            TimeUnit.MILLISECONDS.toSeconds((long) currentTime)
                - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) currentTime))));

    mRunTime.setText(playbackStr);

    // DebugLog.i(currentTime + " / " + totalDuration);
  }
 public void testNonStopTimer() throws Exception {
   long startTime = System.nanoTime();
   int loopTmes = 4;
   long timeout = 500;
   for (int i = 0; i < loopTmes; i++) {
     System.out.println("executing loop count" + i);
     nonStopManager.begin(timeout);
     try {
       blockUntilAborted();
     } finally {
       Assert.assertTrue(abortableOperationManager.isAborted());
       Thread.currentThread().interrupt();
       nonStopManager.finish();
       // check that aborted status is cleared.
       Assert.assertFalse(abortableOperationManager.isAborted());
       // check that interrupted flag is cleared.
       Assert.assertFalse(Thread.interrupted());
     }
   }
   long timeTaken = System.nanoTime() - startTime;
   System.out.println("time taken to execute operations " + timeTaken);
   Assert.assertTrue(
       (timeTaken >= loopTmes * TimeUnit.MILLISECONDS.toNanos(timeout)
           && timeTaken
               < (loopTmes * TimeUnit.MILLISECONDS.toNanos(timeout)
                   + TimeUnit.SECONDS.toNanos(2))));
 }
Пример #18
0
  @Test
  public void testWaitForQuiescenceQuietPeriodAlreadySatisfied()
      throws IOException, InterruptedException {
    mockServer
        .when(request().withMethod("GET").withPath("/quiescencesatisfied"), Times.exactly(1))
        .respond(response().withStatusCode(200));

    try (CloseableHttpClient client = NewProxyServerTestUtil.getNewHttpClient(proxy.getPort())) {
      HttpResponse response =
          client.execute(
              new HttpGet("http://127.0.0.1:" + mockServerPort + "/quiescencesatisfied"));
      EntityUtils.consumeQuietly(response.getEntity());

      assertEquals(
          "Expected successful response from server",
          200,
          response.getStatusLine().getStatusCode());
    }

    // wait for 2s, then wait for 1s of quiescence, which should already be satisfied
    Thread.sleep(2000);

    long start = System.nanoTime();
    boolean waitSuccessful = proxy.waitForQuiescence(1, 5, TimeUnit.SECONDS);
    long finish = System.nanoTime();

    assertTrue("Expected to successfully wait for quiescence", waitSuccessful);

    assertTrue(
        "Expected wait for quiescence to return immediately. Actual wait time was: "
            + TimeUnit.MILLISECONDS.convert(finish - start, TimeUnit.NANOSECONDS)
            + "ms",
        TimeUnit.MILLISECONDS.convert(finish - start, TimeUnit.NANOSECONDS) <= 1);
  }
Пример #19
0
  @Test
  public void testWaitForQuiescenceAfterRequestCompleted() throws IOException {
    mockServer
        .when(request().withMethod("GET").withPath("/quiescencecompleted"), Times.exactly(1))
        .respond(response().withStatusCode(200));

    try (CloseableHttpClient client = NewProxyServerTestUtil.getNewHttpClient(proxy.getPort())) {
      HttpResponse response =
          client.execute(
              new HttpGet("http://127.0.0.1:" + mockServerPort + "/quiescencecompleted"));
      EntityUtils.consumeQuietly(response.getEntity());

      assertEquals(
          "Expected successful response from server",
          200,
          response.getStatusLine().getStatusCode());
    }

    // wait for 2s of quiescence, now that the call has already completed
    long start = System.nanoTime();
    boolean waitSuccessful = proxy.waitForQuiescence(2, 5, TimeUnit.SECONDS);
    long finish = System.nanoTime();

    assertTrue("Expected to successfully wait for quiescence", waitSuccessful);

    assertTrue(
        "Expected to wait for quiescence for approximately 2s. Actual wait time was: "
            + TimeUnit.MILLISECONDS.convert(finish - start, TimeUnit.NANOSECONDS)
            + "ms",
        TimeUnit.MILLISECONDS.convert(finish - start, TimeUnit.NANOSECONDS) >= 1500
            && TimeUnit.MILLISECONDS.convert(finish - start, TimeUnit.NANOSECONDS) <= 2500);
  }
  @Test
  public void testMultipleCellsInOneFamilyAreConverted() {
    byte[] row = dataHelper.randomData("rk-");
    byte[] family = dataHelper.randomData("f1");
    byte[] qualifier1 = dataHelper.randomData("qual1");
    byte[] qualifier2 = dataHelper.randomData("qual2");
    byte[] value1 = dataHelper.randomData("v1");
    byte[] value2 = dataHelper.randomData("v2");
    long timestamp1 = 1L;
    long timestamp2 = 2L;

    Put hbasePut = new Put(row);
    hbasePut.addColumn(family, qualifier1, timestamp1, value1);
    hbasePut.addColumn(family, qualifier2, timestamp2, value2);

    MutateRowRequest.Builder rowMutationBuilder = adapter.adapt(hbasePut);
    Assert.assertArrayEquals(row, rowMutationBuilder.getRowKey().toByteArray());

    Assert.assertEquals(2, rowMutationBuilder.getMutationsCount());
    Mutation mutation = rowMutationBuilder.getMutations(0);

    Assert.assertEquals(MutationCase.SET_CELL, mutation.getMutationCase());
    SetCell setCell = mutation.getSetCell();
    Assert.assertArrayEquals(family, setCell.getFamilyNameBytes().toByteArray());
    Assert.assertArrayEquals(qualifier1, setCell.getColumnQualifier().toByteArray());
    Assert.assertEquals(TimeUnit.MILLISECONDS.toMicros(timestamp1), setCell.getTimestampMicros());
    Assert.assertArrayEquals(value1, setCell.getValue().toByteArray());

    Mutation mod2 = rowMutationBuilder.getMutations(1);
    SetCell setCell2 = mod2.getSetCell();
    Assert.assertArrayEquals(family, setCell2.getFamilyNameBytes().toByteArray());
    Assert.assertArrayEquals(qualifier2, setCell2.getColumnQualifier().toByteArray());
    Assert.assertEquals(TimeUnit.MILLISECONDS.toMicros(timestamp2), setCell2.getTimestampMicros());
    Assert.assertArrayEquals(value2, setCell2.getValue().toByteArray());
  }
Пример #21
0
  /*
   * (non-Javadoc)
   *
   * @see java.lang.Thread#run()
   */
  public void run() {
    try {
      while (true) {
        if (Manager.instance().canDump()) {
          Manager.instance().setProfileFlag(true);
          TimeUnit.SECONDS.sleep(eachProfUseTime);
          Manager.instance().setProfileFlag(false);
          // 等待已开始的End方法执行完成
          TimeUnit.MILLISECONDS.sleep(500L);

          dumpProfileData();
        }
        TimeUnit.SECONDS.sleep(eachProfIntervalTime);
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      Manager.instance().setProfileFlag(false);
      if (fileWriter != null) {
        fileWriter.closeFile();
      }
      // 等待已开始的End方法执行完成
      try {
        TimeUnit.MILLISECONDS.sleep(500L);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      Profiler.clearData();
    }
  }
Пример #22
0
 /* Translates milliseconds into minutes and seconds */
 private String getReadableTime(long remainingTime) {
   return String.format(
       Locale.getDefault(),
       "%02d:%02d",
       TimeUnit.MILLISECONDS.toMinutes(remainingTime),
       TimeUnit.MILLISECONDS.toSeconds(remainingTime)
           - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(remainingTime)));
 }
Пример #23
0
 @Override
 public void printSetup(PrintWriter pw) {
   pw.append("rh set timeout ").println(TimeUnit.MILLISECONDS.toSeconds(stageTimeout));
   pw.append("st set timeout ").println(TimeUnit.MILLISECONDS.toSeconds(flushTimeout));
   pw.append("rm set timeout ").println(TimeUnit.MILLISECONDS.toSeconds(removeTimeout));
   synchronized (suppressedStoreErrors) {
     suppressedStoreErrors.forEach(rc -> pw.append("st suppress rc ").println(rc));
   }
 }
Пример #24
0
 private String formatMilliseconds(int millis) {
   String formated =
       String.format(
           "%02d:%02d",
           TimeUnit.MILLISECONDS.toMinutes(millis),
           TimeUnit.MILLISECONDS.toSeconds(millis)
               - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
   return formated;
 }
Пример #25
0
 private String getParsedTime(long millis) {
   return String.format(
       "%d h %d min %d sec",
       TimeUnit.MILLISECONDS.toHours(millis),
       TimeUnit.MILLISECONDS.toMinutes(millis)
           - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
       TimeUnit.MILLISECONDS.toSeconds(millis)
           - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
 }
Пример #26
0
 public void onTick(long paramLong) {
   Object[] arrayOfObject = new Object[1];
   arrayOfObject[0] =
       Long.valueOf(
           TimeUnit.MILLISECONDS.toSeconds(paramLong)
               - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(paramLong)));
   String str = String.format("%02d", arrayOfObject);
   Paiment.this.textViewTime.setText(str);
 }
Пример #27
0
 @Override
 public String toString() {
   return String.format(
       "Time statistic[%s]: total time: %s secs, total count: %s, average time: %s secs",
       name,
       TimeUnit.MILLISECONDS.toSeconds(totalTime),
       count,
       TimeUnit.MILLISECONDS.toSeconds(averageTime));
 }
 public AuctionDataPersistedCache(String name, String root) {
   super(
       PersistedCacheType.ASYNCHRONIZED,
       name,
       TimeUnit.MILLISECONDS.convert(5, TimeUnit.MINUTES),
       TimeUnit.MILLISECONDS.convert(365, TimeUnit.DAYS),
       TimeUnit.MILLISECONDS.convert(5, TimeUnit.MINUTES),
       TimeUnit.MILLISECONDS.convert(5, TimeUnit.MINUTES));
   this.root = root;
 }
Пример #29
0
 private static String formatDate(long millis) {
   long hours = TimeUnit.MILLISECONDS.toHours(millis);
   millis -= TimeUnit.HOURS.toMillis(hours);
   long minutes = TimeUnit.MILLISECONDS.toMinutes(millis);
   millis -= TimeUnit.MINUTES.toMillis(minutes);
   long seconds = TimeUnit.MILLISECONDS.toSeconds(millis);
   String formatted = String.format("%02d:%02d:%02d", hours, minutes, seconds);
   // replace heading 00: as it's not accepted by the schema validation
   return (formatted.replaceFirst("^(00:)+", ""));
 }
Пример #30
0
 /**
  * This alternative constructor takes time in milliseconds. It has the timeout parameters in order
  * to create a unique method signature.
  *
  * @param ticketGrantingTicketTimeOut TGT timeout in milliseconds.
  * @param serviceTicketTimeOut ST timeout in milliseconds.
  * @param hostnames Array of memcached hosts where each element is of the form host:port.
  * @see MemCacheTicketRegistry#MemCacheTicketRegistry(String[], int, int)
  * @deprecated This has been deprecated
  */
 @Deprecated
 public MemCacheTicketRegistry(
     final long ticketGrantingTicketTimeOut,
     final long serviceTicketTimeOut,
     final String[] hostnames) {
   this(
       hostnames,
       (int) TimeUnit.MILLISECONDS.toSeconds(ticketGrantingTicketTimeOut),
       (int) TimeUnit.MILLISECONDS.toSeconds(serviceTicketTimeOut));
 }