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.wso2.carbon.identity.account.suspension.notification.task.jdbc.JDBCNotificationReceiversRetrieval.java

@Override
public List<NotificationReceiver> getNotificationReceivers(long lookupMin, long lookupMax,
        long delayForSuspension, String tenantDomain) throws AccountSuspensionNotificationException {

    List<NotificationReceiver> users = new ArrayList<NotificationReceiver>();
    RealmService realmService = NotificationTaskDataHolder.getInstance().getRealmService();

    Connection dbConnection = null;
    String sqlStmt = null;/* w  w  w.j  ava  2s .  com*/
    PreparedStatement prepStmt = null;
    ResultSet resultSet = null;

    try {
        ClaimManager claimManager = (ClaimManager) realmService
                .getTenantUserRealm(IdentityTenantUtil.getTenantId(tenantDomain)).getClaimManager();
        String userStoreDomain = realmConfiguration
                .getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME);

        if (StringUtils.isBlank(userStoreDomain)) {
            userStoreDomain = IdentityUtil.getPrimaryDomainName();
        }

        String lastLoginTimeAttribute = claimManager.getAttributeName(userStoreDomain,
                NotificationConstants.LAST_LOGIN_TIME);

        dbConnection = getDBConnection(realmConfiguration);
        sqlStmt = NotificationConstants.GET_USERS_FILTERED_BY_LAST_LOGIN_TIME;
        prepStmt = dbConnection.prepareStatement(sqlStmt);
        prepStmt.setString(1, lastLoginTimeAttribute);
        prepStmt.setString(2, String.valueOf(lookupMin));
        prepStmt.setString(3, String.valueOf(lookupMax));
        prepStmt.setString(4, String.valueOf(IdentityTenantUtil.getTenantId(tenantDomain)));
        prepStmt.setString(5, String.valueOf(IdentityTenantUtil.getTenantId(tenantDomain)));

        resultSet = prepStmt.executeQuery();

        if (resultSet.next()) {

            String userName = resultSet.getString(1);

            if (StringUtils.isNotBlank(userName)) {

                String[] claims = new String[3];
                claims[0] = NotificationConstants.FIRST_NAME_CLAIM;
                claims[1] = NotificationConstants.EMAIL_CLAIM;
                claims[2] = NotificationConstants.LAST_LOGIN_TIME;
                Map<String, String> map = realmService
                        .getTenantUserRealm(IdentityTenantUtil.getTenantId(tenantDomain)).getUserStoreManager()
                        .getUserClaimValues(userName, claims, null);

                NotificationReceiver receiver = new NotificationReceiver();
                receiver.setEmail(map.get(NotificationConstants.EMAIL_CLAIM));
                receiver.setUsername(userName);
                receiver.setFirstName(map.get(NotificationConstants.FIRST_NAME_CLAIM));
                receiver.setUserStoreDomain(userStoreDomain);

                long lastLoginTime = Long.parseLong(map.get(NotificationConstants.LAST_LOGIN_TIME));
                long expireDate = lastLoginTime + TimeUnit.DAYS.toMillis(delayForSuspension);
                receiver.setExpireDate(new SimpleDateFormat("dd-MM-yyyy").format(new Date(expireDate)));
                users.add(receiver);
            }
        }

    } catch (SQLException e) {
        if (log.isDebugEnabled()) {
            log.debug("Using sql : " + sqlStmt);
        }
        throw new AccountSuspensionNotificationException(e.getMessage(), e);
    } catch (Exception e) {
        throw new AccountSuspensionNotificationException(e.getMessage(), e);
    } finally {
        DatabaseUtil.closeAllConnections(dbConnection, resultSet, prepStmt);
    }
    return users;
}

From source file:org.apache.rya.benchmark.periodic.KafkaLatencyBenchmark.java

@Override
public void close() throws Exception {
    logger.info("Stopping threads.");
    scheduler.shutdown();//from   ww  w . jav  a 2s . c o m

    cancelAllScheduledTasks();
    logger.info("Waiting for all threads to terminate...");
    scheduler.awaitTermination(1, TimeUnit.DAYS);
    logger.info("All threads terminated.");
}

From source file:de.blizzy.documentr.context.ContextConfig.java

@Bean(destroyMethod = "shutdown")
@SuppressWarnings("deprecation")
public net.sf.ehcache.CacheManager ehCacheManager(Settings settings) throws IOException {
    File cacheDir = new File(settings.getDocumentrDataDir(), DocumentrConstants.CACHE_DIR_NAME);
    FileUtils.forceMkdir(cacheDir);/*  www.  j a v a  2 s  . c  om*/

    net.sf.ehcache.CacheManager ehCacheManager = net.sf.ehcache.CacheManager
            .newInstance(new net.sf.ehcache.config.Configuration().name("Ehcache") //$NON-NLS-1$
                    .updateCheck(false)
                    .diskStore(new DiskStoreConfiguration().path(cacheDir.getAbsolutePath())));
    ehCacheManager.addCache(new Cache(new CacheConfiguration().name("page_html") //$NON-NLS-1$
            .overflowToDisk(true).diskPersistent(true).maxEntriesLocalHeap(1000)
            .maxBytesLocalDisk(100, MemoryUnit.MEGABYTES)
            .timeToIdleSeconds(TimeUnit.SECONDS.convert(30, TimeUnit.DAYS))));
    ehCacheManager.addCache(new Cache(new CacheConfiguration().name("page_header_html") //$NON-NLS-1$
            .overflowToDisk(true).diskPersistent(true).maxEntriesLocalHeap(100)
            .maxBytesLocalDisk(10, MemoryUnit.MEGABYTES)
            .timeToIdleSeconds(TimeUnit.SECONDS.convert(30, TimeUnit.DAYS))));
    ehCacheManager.addCache(new Cache(new CacheConfiguration().name("page_metadata") //$NON-NLS-1$
            .overflowToDisk(true).diskPersistent(true).maxEntriesLocalHeap(1000)
            .maxBytesLocalDisk(10, MemoryUnit.MEGABYTES)
            .timeToIdleSeconds(TimeUnit.SECONDS.convert(30, TimeUnit.DAYS))));
    ehCacheManager.addCache(new Cache(new CacheConfiguration().name("page_view_restriction_role") //$NON-NLS-1$
            .overflowToDisk(true).diskPersistent(true).maxEntriesLocalHeap(1000)
            .maxBytesLocalDisk(10, MemoryUnit.MEGABYTES)
            .timeToIdleSeconds(TimeUnit.SECONDS.convert(30, TimeUnit.DAYS))));
    return ehCacheManager;
}

From source file:com.linkedin.pinot.core.startree.TestOffheapStarTreeBuilder.java

@Test
public void testRandom() throws Exception {
    int ROWS = 100;
    int numDimensions = 6;
    int numMetrics = 6;
    StarTreeBuilderConfig builderConfig = new StarTreeBuilderConfig();
    Schema schema = new Schema();
    builderConfig.dimensionsSplitOrder = new ArrayList<>();
    for (int i = 0; i < numDimensions; i++) {
        String dimName = "d" + (i + 1);
        DimensionFieldSpec dimensionFieldSpec = new DimensionFieldSpec(dimName, DataType.INT, true);
        schema.addField(dimensionFieldSpec);
        builderConfig.dimensionsSplitOrder.add(dimName);
    }/*from w w w  .  j  a v a 2  s  . c  o m*/
    schema.setTimeFieldSpec(new TimeFieldSpec("daysSinceEpoch", DataType.INT, TimeUnit.DAYS));
    for (int i = 0; i < numMetrics; i++) {
        String metricName = "n" + (i + 1);
        MetricFieldSpec metricFieldSpec = new MetricFieldSpec(metricName, DataType.INT);
        schema.addField(metricFieldSpec);
    }
    builderConfig.maxLeafRecords = 10;
    builderConfig.schema = schema;
    builderConfig.outDir = new File("/tmp/startree");
    OffHeapStarTreeBuilder builder = new OffHeapStarTreeBuilder();
    builder.init(builderConfig);
    Random r = new Random();
    HashMap<String, Object> map = new HashMap<>();
    for (int row = 0; row < ROWS; row++) {
        for (int i = 0; i < numDimensions; i++) {
            String dimName = schema.getDimensionFieldSpecs().get(i).getName();
            map.put(dimName, dimName + "-v" + r.nextInt((numDimensions - i + 2)));
        }
        //time
        map.put("daysSinceEpoch", r.nextInt(1000));
        for (int i = 0; i < numMetrics; i++) {
            String metName = schema.getMetricFieldSpecs().get(i).getName();
            map.put(metName, r.nextInt((numDimensions - i + 2)));
        }

        GenericRow genericRow = new GenericRow();
        genericRow.init(map);
        builder.append(genericRow);
    }
    builder.build();
    FileUtils.deleteDirectory(builderConfig.outDir);
}

From source file:cf.component.VcapComponent.java

private String formatUptime() {
    long delta = System.currentTimeMillis() - startTime;
    delta /= 1000; // Drop the milliseconds
    final long days = delta / TimeUnit.DAYS.toSeconds(1);
    delta -= TimeUnit.DAYS.toSeconds(days);
    final long hours = delta / TimeUnit.HOURS.toSeconds(1);
    delta -= TimeUnit.HOURS.toSeconds(hours);
    final long minutes = delta / TimeUnit.MINUTES.toSeconds(1);
    delta -= TimeUnit.MINUTES.toSeconds(1);
    final long seconds = delta;
    return String.format("%dd:%dh:%dm:%ds", days, hours, minutes, seconds);
}

From source file:com.ibm.mil.readyapps.physio.fragments.LandingFragment.java

private void setupMetricsTabs(View view) {
    LinearLayout metricsTabsArea = (LinearLayout) view.findViewById(R.id.metrics_tabs_area);

    heartRateTab = new HeartRateMetricsTab(getActivity(), null);
    heartRateTab.setOnClickListener(new View.OnClickListener() {
        @Override/*from  ww  w  .j a v  a 2  s.  co  m*/
        public void onClick(View v) {
            openDetailedMetricsScreen(HealthDataRetriever.DataType.HEART_RATE);
        }
    });
    metricsTabsArea.addView(heartRateTab);

    if (DataManager.getCurrentPatient() == null) {
        return;
    }

    stepsTab = new StepsMetricsTab(getActivity(), null);
    stepsTab.setStepsGoal(DataManager.getCurrentPatient().getStepGoal());
    stepsTab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            openDetailedMetricsScreen(HealthDataRetriever.DataType.STEPS);
        }
    });
    metricsTabsArea.addView(stepsTab);

    weightTab = new WeightMetricsTab(getActivity(), null);
    weightTab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            openDetailedMetricsScreen(HealthDataRetriever.DataType.WEIGHT);
        }
    });
    metricsTabsArea.addView(weightTab);

    Calendar cal = Calendar.getInstance();
    Date now = new Date();
    cal.setTime(now);
    cal.add(Calendar.WEEK_OF_YEAR, -1);
    Date startDate = cal.getTime();

    HealthDataRetriever.Builder builder = new HealthDataRetriever.Builder().startDate(startDate).endDate(now)
            .timeUnit(TimeUnit.DAYS).timeInterval(1);

    HealthDataRetriever stepsRetriever = builder.dataType(HealthDataRetriever.DataType.STEPS)
            .handler(new HealthDataRetriever.Handler() {
                @Override
                public void handle(final List<Integer> data) {
                    if (data != null) {
                        stepsTab.setSteps(Utils.sum(data));
                    }
                }
            }).build();
    stepsRetriever.retrieve(mClient);

    HealthDataRetriever weightRetriever = builder.dataType(HealthDataRetriever.DataType.WEIGHT)
            .handler(new HealthDataRetriever.Handler() {
                @Override
                public void handle(final List<Integer> data) {
                    if (data != null) {
                        int lastWeight = data.get(data.size() - 1);
                        int firstWeight = data.get(0);
                        int netWeight = lastWeight - firstWeight;
                        weightTab.setWeight(lastWeight);
                        weightTab.setNetWeight(netWeight);
                    }
                }
            }).build();
    weightRetriever.retrieve(mClient);

    HealthDataRetriever heartRateRetriever = builder.dataType(HealthDataRetriever.DataType.HEART_RATE)
            .handler(new HealthDataRetriever.Handler() {
                @Override
                public void handle(final List<Integer> data) {
                    if (data != null) {
                        heartRateTab.setBeatsPerMin(Utils.average(data));
                        heartRateTab.setMinMaxBpm(Utils.min(data), Utils.max(data));
                    }
                }
            }).build();
    heartRateRetriever.retrieve(mClient);

    RelativeLayout metricsSwipeArea = (RelativeLayout) view.findViewById(R.id.metrics_swipe_area);

    metricsSwipeArea.setOnTouchListener(new OnSwipeTouchListener(getActivity()) {
        @Override
        public void onSwipeLeft() {
            if (!metricsIsOpen) {
                animateMetricsIn(false);
                metricsIsOpen = true;
            }
        }

        @Override
        public void onSwipeRight() {
            if (metricsIsOpen) {
                animateMetricsOut(false);
                metricsIsOpen = false;
            }
        }
    });

    animateMetricsOut(true);
}

From source file:org.wso2.carbon.governance.api.util.CheckpointTimeUtils.java

/**
 * This method is used to format a timestamp to 'dd:hh:mm:ss'.
 *
 * @param duration  timestamp duration./*from   w  w w.j  a v  a  2  s .  c  om*/
 * @return          formatted time duration to 'dd:hh:mm:ss'.
 */
public static String formatTimeDuration(long duration) {
    String timeDuration;
    long days = TimeUnit.MILLISECONDS.toDays(duration);
    long hours = TimeUnit.MILLISECONDS.toHours(duration)
            - TimeUnit.DAYS.toHours(TimeUnit.MILLISECONDS.toDays(duration));
    long minutes = TimeUnit.MILLISECONDS.toMinutes(duration)
            - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(duration));
    long seconds = TimeUnit.MILLISECONDS.toSeconds(duration)
            - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(duration));
    // Setting the duration to a readable format.
    if (days == 0 && hours == 0 && minutes == 0) {
        timeDuration = String.format(durationSecondsFormat, seconds);
    } else if (days == 0 && hours == 0) {
        timeDuration = String.format(durationMinutesSecondsFormat, minutes, seconds);
    } else if (days == 0) {
        timeDuration = String.format(durationHoursMinutesSecondsFormat, hours, minutes, seconds);
    } else {
        timeDuration = String.format(durationDaysHoursMinutesSecondsFormat, days, hours, minutes, seconds);
    }
    return timeDuration;
}

From source file:org.apache.marmotta.ldcache.backend.infinispan.LDCachingInfinispanBackend.java

/**
 * Create a clustered instance of the infinispan cache backend using the provided cluster and machine name
 * @param clusterName/*from   w  w w.  j  a  va  2  s. c  o m*/
 * @param machineName
 * @param clusterPort port to use for multicast messages
 */
public LDCachingInfinispanBackend(String clusterName, String machineName, int clusterPort) {
    try {
        String jgroupsXml = IOUtils
                .toString(LDCachingInfinispanBackend.class.getResourceAsStream("/jgroups-ldcache.xml"));

        jgroupsXml = jgroupsXml.replaceAll("mcast_port=\"[0-9]+\"",
                String.format("mcast_port=\"%d\"", clusterPort));

        globalConfiguration = new GlobalConfigurationBuilder()
                .classLoader(LDCachingInfinispanBackend.class.getClassLoader()).transport().defaultTransport()
                .clusterName(clusterName).machineId(machineName).addProperty("configurationXml", jgroupsXml)
                .globalJmxStatistics().jmxDomain("org.apache.marmotta.ldcache").allowDuplicateDomains(true)
                .serialization().addAdvancedExternalizer(new ModelExternalizer())
                .addAdvancedExternalizer(new ValueExternalizer()).build();
    } catch (IOException ex) {
        log.warn("error loading JGroups configuration from archive: {}", ex.getMessage());
        log.warn("some configuration options will not be available");

        globalConfiguration = new GlobalConfigurationBuilder()
                .classLoader(LDCachingInfinispanBackend.class.getClassLoader()).transport().defaultTransport()
                .clusterName(clusterName).machineId(machineName)
                .addProperty("configurationFile", "jgroups-ldcache.xml").globalJmxStatistics()
                .jmxDomain("org.apache.marmotta.ldcache").allowDuplicateDomains(true).serialization()
                .addAdvancedExternalizer(new ModelExternalizer())
                .addAdvancedExternalizer(new ValueExternalizer()).build();
    }

    defaultConfiguration = new ConfigurationBuilder().clustering().cacheMode(CacheMode.DIST_ASYNC).async()
            .asyncMarshalling().l1().lifespan(5, TimeUnit.MINUTES).hash().numOwners(2).numSegments(40)
            .consistentHashFactory(new SyncConsistentHashFactory()).stateTransfer().fetchInMemoryState(false)
            .eviction().strategy(EvictionStrategy.LIRS).maxEntries(100000).expiration()
            .lifespan(7, TimeUnit.DAYS).maxIdle(1, TimeUnit.DAYS).build();

    clustered = true;

}

From source file:com.pytsoft.cachelock.core.CacheLock.java

/**
 * Acquires the lock unless the current thread is
 * {@linkplain Thread#interrupt interrupted}.
 *
 * <p>Acquires the lock if it is available and returns immediately.
 *
 * <p>If the lock is not available then the current thread becomes
 * disabled for thread scheduling purposes and lies dormant until
 * one of two things happens:/*from  ww  w.j a  v  a2 s .co m*/
 *
 * <ul>
 * <li>The lock is acquired by the current thread; or
 * <li>Some other thread {@linkplain Thread#interrupt interrupts} the
 * current thread, and interruption of lock acquisition is supported.
 * </ul>
 *
 * <p>If the current thread:
 * <ul>
 * <li>has its interrupted status set on entry to this method; or
 * <li>is {@linkplain Thread#interrupt interrupted} while acquiring the
 * lock, and interruption of lock acquisition is supported,
 * </ul>
 * then {@link InterruptedException} is thrown and the current thread's
 * interrupted status is cleared.
 *
 * @throws InterruptedException
 *         if the current thread is
 *         interrupted while acquiring the lock (and interruption
 *         of lock acquisition is supported)
 */
@Override
public void lockInterruptibly() throws InterruptedException {
    this.tryLock(10, TimeUnit.DAYS);
}

From source file:com.dalamar.model.LateTrainDaoImpl.java

private Conjunction createDateCriterion(Date begin, Date end) {
    begin.setHours(0);/*from   w  ww  .j a v  a2  s  . c  o m*/
    begin.setMinutes(0);
    begin.setSeconds(0);
    end.setHours(0);
    end.setMinutes(0);
    end.setSeconds(0);
    Date beginDate = begin;
    Date endDate = new Date(end.getTime() + TimeUnit.DAYS.toMillis(1));
    Conjunction andOperator = Restrictions.conjunction();
    andOperator.add(Restrictions.ge("dateCaptured", beginDate));
    andOperator.add(Restrictions.lt("dateCaptured", endDate));
    return andOperator;
}