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:com.hyperaware.conference.android.fragment.HomeFragment.java

private void updateUpNextCard() {
    ViewGroup time_groups = (ViewGroup) cardUpNext.findViewById(R.id.vg_time_groups);
    time_groups.removeAllViews();//from   w  w  w . j a  v a 2 s  .com

    final SortedMap<DateRange, List<AgendaItem>> up_next = AgendaItems.upNext(agenda.getItems().values(),
            timeAtUpdate, TimeUnit.DAYS.toMillis(1), TimeUnit.HOURS.toMillis(1));

    if (up_next.size() > 0) {
        populateTimeGroups(up_next, time_groups);
        cardUpNext.setVisibility(View.VISIBLE);
        upNextStartTime = up_next.firstKey().start;
    } else {
        cardUpNext.setVisibility(View.GONE);
    }
}

From source file:org.kse.crypto.x509.X509CertificateGenerator.java

private X509Certificate generateVersion1(X500Name subject, X500Name issuer, Date validityStart,
        Date validityEnd, PublicKey publicKey, PrivateKey privateKey, SignatureType signatureType,
        BigInteger serialNumber) throws CryptoException {
    Date notBefore = validityStart == null ? new Date() : validityStart;
    Date notAfter = validityEnd == null ? new Date(notBefore.getTime() + TimeUnit.DAYS.toMillis(365))
            : validityEnd;/* www. ja  v a 2s  . co m*/

    JcaX509v1CertificateBuilder certBuilder = new JcaX509v1CertificateBuilder(issuer, serialNumber, notBefore,
            notAfter, subject, publicKey);

    try {
        ContentSigner certSigner = new JcaContentSignerBuilder(signatureType.jce()).setProvider("BC")
                .build(privateKey);
        return new JcaX509CertificateConverter().setProvider("BC")
                .getCertificate(certBuilder.build(certSigner));
    } catch (CertificateException ex) {
        throw new CryptoException(res.getString("CertificateGenFailed.exception.message"), ex);
    } catch (IllegalStateException ex) {
        throw new CryptoException(res.getString("CertificateGenFailed.exception.message"), ex);
    } catch (OperatorCreationException ex) {
        throw new CryptoException(res.getString("CertificateGenFailed.exception.message"), ex);
    }
}

From source file:cn.keke.travelmix.publictransport.type.EfaConnectionResponseHandler.java

/**
 * approximated minutes diff of two locations
 * /*from  ww w. j  a va  2s .  co m*/
 * @param loc1
 * @param loc2
 * @return
 */
private int getLocationMinutesDiff(LocationPoint loc1, LocationPoint loc2) {
    if (loc1.hasTime() && loc2.hasTime()) {
        return (int) (TimeUnit.DAYS.toMinutes((loc2.getYearInt() - loc1.getYearInt()) * 365)
                + TimeUnit.DAYS.toMinutes((loc2.getMonthInt() - loc1.getMonthInt()) * 30)
                + TimeUnit.DAYS.toMinutes(loc2.getDayInt() - loc1.getDayInt())
                + TimeUnit.HOURS.toMinutes(loc2.getHourInt() - loc1.getHourInt()) + loc2.getMinuteInt()
                - loc1.getMinuteInt());

    }
    return 0;
}

From source file:org.opendaylight.controller.cluster.raft.AbstractRaftActorIntegrationTest.java

protected DefaultConfigParamsImpl newLeaderConfigParams() {
    DefaultConfigParamsImpl configParams = new DefaultConfigParamsImpl();
    configParams.setHeartBeatInterval(new FiniteDuration(100, TimeUnit.MILLISECONDS));
    configParams.setElectionTimeoutFactor(4);
    configParams.setSnapshotBatchCount(snapshotBatchCount);
    configParams.setSnapshotDataThresholdPercentage(70);
    configParams.setIsolatedLeaderCheckInterval(new FiniteDuration(1, TimeUnit.DAYS));
    configParams.setSnapshotChunkSize(snapshotChunkSize);
    return configParams;
}

From source file:org.alfresco.extension.bulkimport.impl.Scanner.java

/**
 * @see java.lang.Runnable#run()//from   ww  w .  j a  va  2  s . co m
 */
@Override
public void run() {
    boolean inPlacePossible = false;

    try {
        source.init(importStatus, parameters);
        inPlacePossible = source.inPlaceImportPossible();

        if (info(log))
            info(log, "Import (" + (inPlacePossible ? "in-place" : "streaming") + ") started from "
                    + source.getName() + ".");

        importStatus.importStarted(userId, source, targetAsPath, importThreadPool, batchWeight, inPlacePossible,
                dryRun);

        // ------------------------------------------------------------------
        // Phase 1 - Folder scanning (single threaded)
        // ------------------------------------------------------------------

        source.scanFolders(importStatus, this);

        if (debug(log))
            debug(log, "Folder import complete in " + getHumanReadableDuration(importStatus.getDurationInNs())
                    + ".");

        // ------------------------------------------------------------------
        // Phase 2 - File scanning
        // ------------------------------------------------------------------

        filePhase = true;

        // Maximise level of concurrency, since there's no longer any risk of out-of-order batches
        source.scanFiles(importStatus, this);

        if (debug(log))
            debug(log,
                    "File scan complete in " + getHumanReadableDuration(importStatus.getDurationInNs()) + ".");

        importStatus.scanningComplete();

        // ------------------------------------------------------------------
        // Phase 3 - Wait for multi-threaded import to complete and shutdown
        // ------------------------------------------------------------------

        submitCurrentBatch(); // Submit whatever is left in the final (partial) batch...
        awaitCompletion();

        if (debug(log))
            debug(log, "Import complete" + (multiThreadedImport ? ", thread pool shutdown" : "") + ".");
    } catch (final Throwable t) {
        Throwable rootCause = getRootCause(t);
        String rootCauseClassName = rootCause.getClass().getName();

        if (importStatus.isStopping()
                && (rootCause instanceof InterruptedException || rootCause instanceof ClosedByInterruptException
                        || "com.hazelcast.core.RuntimeInterruptedException".equals(rootCauseClassName))) // For compatibility across 4.x *sigh*
        {
            // A stop import was requested
            if (debug(log))
                debug(log, Thread.currentThread().getName() + " was interrupted by a stop request.", t);
        } else {
            // An unexpected exception occurred during scanning - log it and kill the import
            error(log, "Bulk import from '" + source.getName() + "' failed.", t);
            importStatus.unexpectedError(t);
        }

        if (debug(log))
            debug(log, "Forcibly shutting down import thread pool and awaiting shutdown...");
        importThreadPool.shutdownNow();

        try {
            importThreadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS); // Wait forever (technically merely a very long time, but whatevs...)
        } catch (final InterruptedException ie) {
            // Not much we can do here but log it and keep on truckin'
            if (warn(log))
                warn(log, Thread.currentThread().getName()
                        + " was interrupted while awaiting shutdown of import thread pool.", ie);
        }
    } finally {
        // Reset the thread factory
        if (importThreadPool.getThreadFactory() instanceof BulkImportThreadFactory) {
            ((BulkImportThreadFactory) importThreadPool.getThreadFactory()).reset();
        }

        // Mark the import complete
        importStatus.importComplete();

        // Invoke the completion handlers (if any)
        if (completionHandlers != null) {
            for (final BulkImportCompletionHandler handler : completionHandlers) {
                try {
                    handler.importComplete(importStatus);
                } catch (final Exception e) {
                    if (error(log))
                        error(log, "Completion handler threw an unexpected exception. It will be ignored.", e);
                }
            }
        }

        // Always invoke the logging completion handler last
        loggingBulkImportCompletionHandler.importComplete(importStatus);
    }
}

From source file:com.ms.commons.standalone.service.StandaloneServiceImpl.java

@Override
public List<String> listAllLogs() {
    File logDir = new File(String.format("%s/logs", baseStandalonePath));
    List<String> allLogs = new ArrayList<String>();
    long currentTimeMillis = System.currentTimeMillis();
    if (logDir.exists()) {
        for (File logFile : logDir.listFiles()) {
            if (logFile.isFile() && logFile.canRead()
                    && currentTimeMillis - logFile.lastModified() < TimeUnit.DAYS.toMillis(7)) {
                allLogs.add(logFile.getName());
            }// w ww  .  ja v  a2s  .  co  m
        }
    }
    Collections.sort(allLogs);
    return allLogs;
}

From source file:org.eclipse.skalli.core.rest.admin.StatisticsQueryTest.java

@Test
public void testFromToNow() throws Exception {
    Calendar cal = Calendar.getInstance();
    long now = cal.getTimeInMillis();

    StatisticsQuery query = new StatisticsQuery(getParams(null, "now", null), now);
    Assert.assertEquals(0, query.getFrom());
    Assert.assertEquals(now, query.getTo());

    query = new StatisticsQuery(getParams("-1h", "now", null), now);
    Assert.assertEquals(now - TimeUnit.MILLISECONDS.convert(1, TimeUnit.HOURS), query.getFrom());
    Assert.assertEquals(now, query.getTo());

    long fromMillis = now - TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS);
    cal.setTimeInMillis(fromMillis);/* ww w  .  ja va2  s. com*/
    String fromStr = DatatypeConverter.printDateTime(cal);
    query = new StatisticsQuery(getParams(fromStr, "now", null), now);
    Assert.assertEquals(fromMillis, query.getFrom());
    Assert.assertEquals(now, query.getTo());

    query = new StatisticsQuery(getParams("now", null, null), now);
    Assert.assertEquals(now, query.getFrom());
    Assert.assertEquals(now, query.getTo());

    query = new StatisticsQuery(getParams("now", "now", null), now);
    Assert.assertEquals(now, query.getFrom());
    Assert.assertEquals(now, query.getTo());

    // period is ignored, if from and to are specified
    query = new StatisticsQuery(getParams("now", "now", "1d"), now);
    Assert.assertEquals(now, query.getFrom());
    Assert.assertEquals(now, query.getTo());
}

From source file:com.spvp.dal.MySqlDatabase.java

private void osvjeziHistorijuPrognozaZaGrad(Grad g, WebService ws) {

    try (Connection conn = getConnection()) {

        PreparedStatement ps = conn.prepareStatement("SELECT hp.datum dat "
                + "FROM historija_prognoze hp, gradovi_prognoze gp "
                + "WHERE hp.id = gp.prognoza_id AND gp.grad_id = ? " + "ORDER BY hp.datum DESC " + "LIMIT 1");

        ps.setInt(1, g.getIdGrada());/*from w ww  . j a  v  a  2s .  c o  m*/

        ResultSet rs = ps.executeQuery();

        if (rs.next()) {

            Calendar cal = Calendar.getInstance();
            cal.setTime(rs.getDate("dat"));
            cal.set(Calendar.MILLISECOND, 0);
            cal.set(Calendar.SECOND, 0);
            cal.set(Calendar.MINUTE, 0);
            cal.set(Calendar.HOUR, 0);

            //System.out.println("Zadnji datum u bazi je bio: " + cal.getTime().toString());

            Calendar tempDate = Calendar.getInstance();
            tempDate.set(Calendar.MILLISECOND, 0);
            tempDate.set(Calendar.SECOND, 0);
            tempDate.set(Calendar.MINUTE, 0);
            tempDate.set(Calendar.HOUR, 0);

            //System.out.println("Danasnji datum je: " + tempDate.getTime().toString());

            long diff = tempDate.getTime().getTime() - cal.getTime().getTime();
            long brDana = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);

            //System.out.println("Razlika u danima je: " + brDana);

            if (brDana == 0)
                return;

            //System.out.println("Osvjezavanje zadnjeg dana u bazi...");

            this.osvjeziZadnjuPrognozuZaGrad(g, ws);

            //System.out.println("Ucitavanje novih prognoza...");

            Location l = new Location(false);
            l.setCity(g.getImeGrada());
            l.setCountry("Bosnia and Herzegovina");
            l.setCountryCode("ba");
            l.setLatitude(g.getLatitude());
            l.setLongitude(g.getLongitude());
            l.setStatus(Boolean.TRUE);

            this.ucitajPrognozeUBazu(ws.getHistorijskePodatkeByLocation(l, (int) brDana));

        } else { // Ne postoji ni jedan unos prognoze za dati grad

            //System.out.println("Zadnji datum u bazi je bio: " + rs.getDate("dat").toString());

            Location l = new Location(true);
            l.setCity(g.getImeGrada());
            l.setCountryCode("ba");
            l.setLatitude(g.getLatitude());
            l.setLongitude(g.getLongitude());
            l.setCountry("Bosnia and Herzegovina");

            this.ucitajPrognozeUBazu(ws.getHistorijskePodatkeByLocation(l, 15));

        }

    } catch (SQLException ex) {
        Logger.getLogger(MySqlDatabase.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ParseException ex) {
        Logger.getLogger(MySqlDatabase.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.linkedin.pinot.core.segment.index.ColumnMetadataTest.java

@Test
public void testHllIndexRelatedMetadata() throws Exception {
    SegmentWithHllIndexCreateHelper helper = null;
    try {//from ww w. j a v  a  2  s.com
        // Build the Segment metadata.
        helper = new SegmentWithHllIndexCreateHelper("testHllIndexRelatedMetadata", "data/test_data-sv.avro",
                "daysSinceEpoch", TimeUnit.DAYS);
        helper.build(true, new HllConfig(9, new HashSet<String>(Arrays.asList("column7")), "_hllSuffix"));

        // Load segment metadata.
        IndexSegment segment = Loaders.IndexSegment.load(helper.getSegmentDirectory(), ReadMode.mmap);
        SegmentMetadataImpl metadata = (SegmentMetadataImpl) segment.getSegmentMetadata();
        Assert.assertEquals(metadata.getHllLog2m(), 9);

        // Verify Hll Related Info
        StarTreeMetadata starTreeMetadata = metadata.getStarTreeMetadata();
        Assert.assertNotNull(starTreeMetadata);
        ColumnMetadata column = metadata.getColumnMetadataFor("column7_hllSuffix");
        Assert.assertEquals(column.getDerivedMetricType(), MetricFieldSpec.DerivedMetricType.HLL);
        Assert.assertEquals(column.getOriginColumnName(), "column7");
    } finally {
        if (helper != null) {
            helper.cleanTempDir();
        }
    }
}

From source file:org.apache.synapse.transport.amqp.pollingtask.AMQPTransportPollingTaskFactory.java

private static TimeUnit getTimeUnit(String timeUnit) {

    if ("days".equals(timeUnit)) {
        return TimeUnit.DAYS;
    } else if ("hours".equals(timeUnit)) {
        return TimeUnit.HOURS;
    } else if ("minutes".equals(timeUnit)) {
        return TimeUnit.MINUTES;
    } else if ("seconds".equals(timeUnit)) {
        return TimeUnit.SECONDS;
    } else if ("milliseconds".equals(timeUnit)) {
        return TimeUnit.MILLISECONDS;
    } else {//from w ww  .  ja va 2 s. c o  m
        return TimeUnit.MICROSECONDS;
    }
}