Example usage for java.util.concurrent TimeUnit DAYS

List of usage examples for java.util.concurrent TimeUnit DAYS

Introduction

In this page you can find the example usage for java.util.concurrent TimeUnit DAYS.

Prototype

TimeUnit DAYS

To view the source code for java.util.concurrent TimeUnit DAYS.

Click Source Link

Document

Time unit representing twenty four hours.

Usage

From source file:org.jvnet.hudson.update_center.ConfluencePluginList.java

/**
 * Loads the page from Wiki after consulting with the cache.
 *///  w  ww .  ja v a  2s  .c o m
private WikiPage loadPage(String title) throws IOException {
    File cache = new File(cacheDir, title + ".page");
    if (cache.exists() && cache.lastModified() >= System.currentTimeMillis() - TimeUnit.DAYS.toMillis(1)) {
        // load from cache
        try {
            FileInputStream f = new FileInputStream(cache);
            try {
                Object o = new ObjectInputStream(f).readObject();
                if (o == null)
                    return null;
                if (o instanceof WikiPage) {
                    return (WikiPage) o;
                }
                // cache invalid. fall through to retrieve the page.
            } finally {
                f.close();
            }
        } catch (ClassNotFoundException e) {
            throw (IOException) new IOException("Failed to retrieve from cache: " + cache).initCause(e);
        }
    }

    try {
        RemotePage page = service.getPage("", "JENKINS", title);
        RemoteLabel[] labels = service.getLabelsById("", page.getId());
        WikiPage p = new WikiPage(page, labels);
        writeToCache(cache, p);
        return p;
    } catch (RemoteException e) {
        writeToCache(cache, null);
        throw e;
    }
}

From source file:com.linkedin.pinot.segments.v1.creator.BitmapInvertedIndexTest.java

@BeforeClass
public void setup() throws Exception {
    final String filePath = TestUtils
            .getFileFromResourceUrl(getClass().getClassLoader().getResource(AVRO_DATA));

    if (INDEX_DIR.exists()) {
        FileUtils.deleteQuietly(INDEX_DIR);
    }/*from w  ww  .  j  a v  a  2 s  .  c  o m*/

    final SegmentGeneratorConfig config = SegmentTestUtils.getSegmentGenSpecWithSchemAndProjectedColumns(
            new File(filePath), INDEX_DIR, "time_day", TimeUnit.DAYS, "test");

    final SegmentIndexCreationDriver driver = SegmentCreationDriverFactory.get(null);
    driver.init(config);
    driver.build();
    System.out.println("built at : " + INDEX_DIR.getAbsolutePath());
}

From source file:io.gomint.server.network.packet.PacketLogin.java

private void decodeBase64JSON(String data) throws ParseException {
    try {//from  w  w w.j a  v a  2s . c  o m
        // Get validation key
        Key key = getPublicKey(Base64.getDecoder().decode(this.validationKey));
        if (key == null) {
            return;
        }

        // Check JWT
        Claims claims = Jwts.parser().setSigningKey(key).parseClaimsJws(data).getBody();

        // Only certification authory is allowed to set new validation keys
        Boolean certificateAuthority = (Boolean) claims.get("certificateAuthority");
        if (certificateAuthority != null && certificateAuthority) {
            this.validationKey = (String) claims.get("identityPublicKey");

            // We have to blindy trust this auth when its the first (they send the root cert in 0.15.4+)
            if (this.firstCertAuth && this.validationKey.equals(MOJANG_PUBLIC)) {
                this.firstCertAuth = false;
                return;
            }
        }

        // Invalid duration frame ?
        if (claims.getExpiration().getTime() - claims.getIssuedAt().getTime() != TimeUnit.DAYS.toMillis(1)) {
            System.out.println("Certification lifetime is not 1 day.");
            this.valid = false;
        }

        // Invalid Issuer ?
        if (!"RealmsAuthorization".equals(claims.getIssuer())) {
            System.out.println("Certification issuer is wrong.");
            this.valid = false;
        }

        // Check for extra data
        Map<String, Object> extraData = (Map<String, Object>) claims.get("extraData");
        if (extraData != null) {
            // For a valid user we need a XUID (xbox live id)
            String xboxId = (String) extraData.get("XUID");
            if (xboxId == null) {
                System.out.println("Did not find any xbox live id");
                this.valid = false;
            } else {
                this.xboxId = Long.parseLong(xboxId);
            }

            this.userName = (String) extraData.get("displayName");
            this.uuid = UUID.fromString((String) extraData.get("identity"));
        }
    } catch (Exception e) {
        // This normally comes when the user is not logged in into xbox live since the payload only sends
        // the self signed cert without a certifaction authory
        this.valid = false;

        // Be able to "parse" the payload
        String[] tempBase64 = data.split("\\.");

        String payload = new String(Base64.getDecoder().decode(tempBase64[1]));
        JSONObject chainData = (JSONObject) new JSONParser().parse(payload);
        if (chainData.containsKey("extraData")) {
            JSONObject extraData = (JSONObject) chainData.get("extraData");
            this.userName = (String) extraData.get("displayName");
            this.uuid = UUID.fromString((String) extraData.get("identity"));
        }
    }
}

From source file:com.markupartist.sthlmtraveling.utils.DateTimeUtil.java

/**
 * Format duration without rounding. Seconds are still rounded though.
 *
 * @param resources a resource//from w w w  .  jav a  2 s. c om
 * @param millis    duration in millis
 * @return A string representing the duration
 */
public static CharSequence formatDetailedDuration(@NonNull final Resources resources, long millis) {
    int days = 0, hours = 0, minutes = 0;
    if (millis > 0) {
        days = (int) TimeUnit.MILLISECONDS.toDays(millis);
        millis -= TimeUnit.DAYS.toMillis(days);
        hours = (int) TimeUnit.MILLISECONDS.toHours(millis);
        millis -= TimeUnit.HOURS.toMillis(hours);
        minutes = (int) TimeUnit.MILLISECONDS.toMinutes(millis);
    }
    if (days > 0) {
        return resources.getQuantityString(R.plurals.duration_days, days, days);
    }
    if (hours > 0) {
        if (minutes == 0) {
            return resources.getQuantityString(R.plurals.duration_short_hours, hours, hours);
        }
        return resources.getString(R.string.duration_short_hours_minutes, hours, minutes);
    }
    return resources.getQuantityString(R.plurals.duration_short_minutes, minutes, minutes);
}

From source file:org.dcache.util.histograms.HistogramModelTest.java

@Test
public void binUnitShouldBe3ForMaxValue101Days() throws NoSuchMethodException, InstantiationException,
        IllegalAccessException, InvocationTargetException {
    givenCountingHistogram();/*from  w ww . j ava2  s .c o  m*/
    givenFilelifetimeValuesFor(101);
    givenBinCountOf(51);
    givenBinUnitOf((double) TimeUnit.DAYS.toMillis(1));
    givenBinLabelOf(TimeUnit.DAYS.name());
    givenDataLabelOf("COUNT");
    givenHistogramTypeOf("File Lifetime Count");
    whenConfigureIsCalled();
    assertThatBuildSucceeded();
    assertThatBinWidthIs(3);
}

From source file:com.linkedin.pinot.query.executor.DefaultReduceServiceTest.java

private void setupSegmentList(int numberOfSegments) throws Exception {
    final String filePath = TestUtils
            .getFileFromResourceUrl(getClass().getClassLoader().getResource(SMALL_AVRO_DATA));
    _indexSegmentList.clear();/*from w ww.  ja va  2 s.c  o  m*/
    if (INDEXES_DIR.exists()) {
        FileUtils.deleteQuietly(INDEXES_DIR);
    }
    INDEXES_DIR.mkdir();

    for (int i = 0; i < numberOfSegments; ++i) {
        final File segmentDir = new File(INDEXES_DIR, "segment_" + i);

        final SegmentGeneratorConfig config = SegmentTestUtils.getSegmentGenSpecWithSchemAndProjectedColumns(
                new File(filePath), segmentDir, "dim" + i, TimeUnit.DAYS, "midas");
        config.setSegmentNamePostfix(String.valueOf(i));
        final SegmentIndexCreationDriver driver = SegmentCreationDriverFactory.get(null);
        driver.init(config);
        driver.build();
        File parent = new File(INDEXES_DIR, "segment_" + String.valueOf(i));
        String segmentName = parent.list()[0];
        _indexSegmentList.add(ColumnarSegmentLoader.load(new File(parent, segmentName), ReadMode.mmap));
        System.out.println("built at : " + segmentDir.getAbsolutePath());
    }

}

From source file:org.apache.carbondata.processing.loading.sort.impl.UnsafeParallelReadMergeSorterWithColumnRangeImpl.java

@Override
public Iterator<CarbonRowBatch>[] sort(Iterator<CarbonRowBatch>[] iterators) throws CarbonDataLoadingException {
    UnsafeSortDataRows[] sortDataRows = new UnsafeSortDataRows[columnRangeInfo.getNumOfRanges()];
    intermediateFileMergers = new UnsafeIntermediateMerger[columnRangeInfo.getNumOfRanges()];
    SortParameters[] sortParameterArray = new SortParameters[columnRangeInfo.getNumOfRanges()];
    try {/*w  ww  .j a  va2s  .  c  o  m*/
        for (int i = 0; i < columnRangeInfo.getNumOfRanges(); i++) {
            SortParameters parameters = originSortParameters.getCopy();
            parameters.setPartitionID(i + "");
            parameters.setRangeId(i);
            sortParameterArray[i] = parameters;
            setTempLocation(parameters);
            intermediateFileMergers[i] = new UnsafeIntermediateMerger(parameters);
            sortDataRows[i] = new UnsafeSortDataRows(parameters, intermediateFileMergers[i],
                    inMemoryChunkSizeInMB);
            sortDataRows[i].initialize();
        }
    } catch (Exception e) {
        throw new CarbonDataLoadingException(e);
    }
    ExecutorService executorService = Executors.newFixedThreadPool(iterators.length);
    this.threadStatusObserver = new ThreadStatusObserver(executorService);
    final int batchSize = CarbonProperties.getInstance().getBatchSize();
    try {
        for (int i = 0; i < iterators.length; i++) {
            executorService.execute(new SortIteratorThread(iterators[i], sortDataRows, rowCounter,
                    this.insideRowCounterList, this.threadStatusObserver));
        }
        executorService.shutdown();
        executorService.awaitTermination(2, TimeUnit.DAYS);
        processRowToNextStep(sortDataRows, originSortParameters);
    } catch (Exception e) {
        checkError();
        throw new CarbonDataLoadingException("Problem while shutdown the server ", e);
    }
    checkError();
    try {
        for (int i = 0; i < intermediateFileMergers.length; i++) {
            intermediateFileMergers[i].finish();
        }
    } catch (Exception e) {
        throw new CarbonDataLoadingException(e);
    }

    Iterator<CarbonRowBatch>[] batchIterator = new Iterator[columnRangeInfo.getNumOfRanges()];
    for (int i = 0; i < sortDataRows.length; i++) {
        batchIterator[i] = new MergedDataIterator(sortParameterArray[i], batchSize, intermediateFileMergers[i]);
    }

    return batchIterator;
}

From source file:com.hpcloud.util.Duration.java

public long toDays() {
    return TimeUnit.DAYS.convert(length, timeUnit);
}

From source file:com.codebullets.sagalib.timeout.InMemoryTimeoutManagerTest.java

/**
 * <pre>/*from   w w  w  .  ja  v  a2 s.c  o m*/
 * Given => Multiple timeouts are added
 * When  => timeout is canceled afterwards
 * Then  => does not throw
 * </pre>
 */
@Test
public void timeoutCanceled_multipleTimeoutAdded_doesNotThrowConcurrencyException() {
    // given
    ScheduledFuture future = mock(ScheduledFuture.class);
    when(executor.schedule(any(Runnable.class), anyLong(), any(TimeUnit.class))).thenReturn(future);
    TimeoutId timeoutId = sut.requestTimeout(null, "saga1", 1, TimeUnit.DAYS, null, null);
    sut.requestTimeout(null, "saga2", 2, TimeUnit.DAYS, null, null);

    // when
    sut.cancelTimeout(timeoutId);

    // then
}

From source file:net.pterodactylus.sone.web.ajax.GetTimesAjaxPage.java

/**
 * Returns the formatted relative time for a given time.
 *
 * @param webInterface/*from w ww .ja v  a2  s .com*/
 *            The Sone web interface (for l10n access)
 * @param time
 *            The time to format the difference from (in milliseconds)
 * @return The formatted age
 */
public static Time getTime(WebInterface webInterface, long time) {
    if (time == 0) {
        return new Time(webInterface.getL10n().getString("View.Sone.Text.UnknownDate"),
                TimeUnit.HOURS.toMillis(12));
    }
    long age = System.currentTimeMillis() - time;
    String text;
    long refresh;
    if (age < 0) {
        text = webInterface.getL10n().getDefaultString("View.Time.InTheFuture");
        refresh = TimeUnit.MINUTES.toMillis(5);
    } else if (age < TimeUnit.SECONDS.toMillis(20)) {
        text = webInterface.getL10n().getDefaultString("View.Time.AFewSecondsAgo");
        refresh = TimeUnit.SECONDS.toMillis(10);
    } else if (age < TimeUnit.SECONDS.toMillis(45)) {
        text = webInterface.getL10n().getString("View.Time.HalfAMinuteAgo");
        refresh = TimeUnit.SECONDS.toMillis(20);
    } else if (age < TimeUnit.SECONDS.toMillis(90)) {
        text = webInterface.getL10n().getString("View.Time.AMinuteAgo");
        refresh = TimeUnit.MINUTES.toMillis(1);
    } else if (age < TimeUnit.MINUTES.toMillis(30)) {
        text = webInterface.getL10n().getString("View.Time.XMinutesAgo", "min",
                String.valueOf(TimeUnit.MILLISECONDS.toMinutes(age + TimeUnit.SECONDS.toMillis(30))));
        refresh = TimeUnit.MINUTES.toMillis(1);
    } else if (age < TimeUnit.MINUTES.toMillis(45)) {
        text = webInterface.getL10n().getString("View.Time.HalfAnHourAgo");
        refresh = TimeUnit.MINUTES.toMillis(10);
    } else if (age < TimeUnit.MINUTES.toMillis(90)) {
        text = webInterface.getL10n().getString("View.Time.AnHourAgo");
        refresh = TimeUnit.HOURS.toMillis(1);
    } else if (age < TimeUnit.HOURS.toMillis(21)) {
        text = webInterface.getL10n().getString("View.Time.XHoursAgo", "hour",
                String.valueOf(TimeUnit.MILLISECONDS.toHours(age + TimeUnit.MINUTES.toMillis(30))));
        refresh = TimeUnit.HOURS.toMillis(1);
    } else if (age < TimeUnit.HOURS.toMillis(42)) {
        text = webInterface.getL10n().getString("View.Time.ADayAgo");
        refresh = TimeUnit.DAYS.toMillis(1);
    } else if (age < TimeUnit.DAYS.toMillis(6)) {
        text = webInterface.getL10n().getString("View.Time.XDaysAgo", "day",
                String.valueOf(TimeUnit.MILLISECONDS.toDays(age + TimeUnit.HOURS.toMillis(12))));
        refresh = TimeUnit.DAYS.toMillis(1);
    } else if (age < TimeUnit.DAYS.toMillis(11)) {
        text = webInterface.getL10n().getString("View.Time.AWeekAgo");
        refresh = TimeUnit.DAYS.toMillis(1);
    } else if (age < TimeUnit.DAYS.toMillis(28)) {
        text = webInterface.getL10n().getString("View.Time.XWeeksAgo", "week",
                String.valueOf((TimeUnit.MILLISECONDS.toHours(age) + 84) / (7 * 24)));
        refresh = TimeUnit.DAYS.toMillis(1);
    } else if (age < TimeUnit.DAYS.toMillis(42)) {
        text = webInterface.getL10n().getString("View.Time.AMonthAgo");
        refresh = TimeUnit.DAYS.toMillis(1);
    } else if (age < TimeUnit.DAYS.toMillis(330)) {
        text = webInterface.getL10n().getString("View.Time.XMonthsAgo", "month",
                String.valueOf((TimeUnit.MILLISECONDS.toDays(age) + 15) / 30));
        refresh = TimeUnit.DAYS.toMillis(1);
    } else if (age < TimeUnit.DAYS.toMillis(540)) {
        text = webInterface.getL10n().getString("View.Time.AYearAgo");
        refresh = TimeUnit.DAYS.toMillis(7);
    } else {
        text = webInterface.getL10n().getString("View.Time.XYearsAgo", "year",
                String.valueOf((long) ((TimeUnit.MILLISECONDS.toDays(age) + 182.64) / 365.28)));
        refresh = TimeUnit.DAYS.toMillis(7);
    }
    return new Time(text, refresh);
}