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:edu.unc.lib.dl.cdr.services.BatchIngestService.java

protected void initializeExecutor() {
    LOG.debug("Initializing batch ingest thread pool executor with " + this.maxThreads + " threads.");
    this.executor = new ServicesThreadPoolExecutor<BatchIngestTask>(this.maxThreads, "BatchIngest");
    this.executor.setKeepAliveTime(0, TimeUnit.DAYS);
    (this.executor).setBeforeExecuteDelay(beforeExecuteDelay);
}

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

private List<Double> getRawLifetimes(int days) {
    List<Double> lifetimes = new ArrayList<>();
    long radix = TimeUnit.DAYS.toMillis(days);
    /*//from   w  w w. j a  v  a 2  s. c  o m
     *  Ensure that the max is there so
     *  the assertion always works, regardless
     *  of the other random values.
     */
    lifetimes.add((double) radix);
    for (int i = 1; i < days; ++i) {
        long duration = FastMath.abs(RANDOM.nextLong()) % radix;
        lifetimes.add((double) duration);
    }
    return lifetimes;
}

From source file:org.wso2.carbon.identity.account.suspension.notification.task.ldap.LDAPNotificationReceiversRetrieval.java

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

    List<NotificationReceiver> users = new ArrayList<NotificationReceiver>();

    if (realmConfiguration != null) {
        String ldapSearchBase = realmConfiguration.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);
        RealmService realmService = NotificationTaskDataHolder.getInstance().getRealmService();

        try {/*from  w  w  w .  ja  va 2 s.c om*/
            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 usernameMapAttribute = claimManager.getAttributeName(userStoreDomain,
                    NotificationConstants.USERNAME_CLAIM);
            String firstNameMapAttribute = claimManager.getAttributeName(userStoreDomain,
                    NotificationConstants.FIRST_NAME_CLAIM);
            String emailMapAttribute = claimManager.getAttributeName(userStoreDomain,
                    NotificationConstants.EMAIL_CLAIM);
            String lastLoginTimeAttribute = claimManager.getAttributeName(userStoreDomain,
                    NotificationConstants.LAST_LOGIN_TIME);

            if (log.isDebugEnabled()) {
                log.debug(
                        "Retrieving ldap user list for lookupMin: " + lookupMin + " - lookupMax: " + lookupMax);
            }

            LDAPConnectionContext ldapConnectionContext = new LDAPConnectionContext(realmConfiguration);
            DirContext ctx = ldapConnectionContext.getContext();

            //carLicense is the mapped LDAP attribute for LastLoginTime claim
            String searchFilter = "(&(" + lastLoginTimeAttribute + ">=" + lookupMin + ")("
                    + lastLoginTimeAttribute + "<=" + lookupMax + "))";

            SearchControls searchControls = new SearchControls();
            searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

            NamingEnumeration<SearchResult> results = ctx.search(ldapSearchBase, searchFilter, searchControls);

            if (log.isDebugEnabled()) {
                log.debug("LDAP user list retrieved.");
            }

            while (results.hasMoreElements()) {
                SearchResult result = results.nextElement();

                NotificationReceiver receiver = new NotificationReceiver();
                receiver.setEmail((String) result.getAttributes().get(emailMapAttribute).get());
                receiver.setUsername((String) result.getAttributes().get(usernameMapAttribute).get());
                receiver.setFirstName((String) result.getAttributes().get(firstNameMapAttribute).get());
                receiver.setUserStoreDomain(userStoreDomain);

                long lastLoginTime = Long
                        .parseLong(result.getAttributes().get(lastLoginTimeAttribute).get().toString());
                long expireDate = lastLoginTime + TimeUnit.DAYS.toMillis(delayForSuspension);
                receiver.setExpireDate(new SimpleDateFormat("dd-MM-yyyy").format(new Date(expireDate)));

                if (log.isDebugEnabled()) {
                    log.debug("Expire date was set to: " + receiver.getExpireDate());
                }
                users.add(receiver);
            }
        } catch (NamingException e) {
            throw new AccountSuspensionNotificationException("Failed to filter users from LDAP user store.", e);
        } catch (UserStoreException e) {
            throw new AccountSuspensionNotificationException("Failed to load LDAP connection context.", e);
        } catch (org.wso2.carbon.user.api.UserStoreException e) {
            throw new AccountSuspensionNotificationException(
                    "Error occurred while getting tenant user realm for " + "tenant:" + tenantDomain, e);
        }
    }
    return users;
}

From source file:com.linkedin.pinot.query.plan.PlanMakerTest.java

private void setupSegment() throws Exception {
    final String filePath = TestUtils
            .getFileFromResourceUrl(PlanMakerTest.class.getClassLoader().getResource(LARGE_AVRO_DATA));

    if (INDEX_DIR.exists()) {
        FileUtils.deleteQuietly(INDEX_DIR);
    }//from   ww  w .  java2  s.c  om

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

    final SegmentIndexCreationDriver driver = SegmentCreationDriverFactory.get(null);
    driver.init(config);
    driver.build();

    LOGGER.debug("built at: {}", INDEX_DIR.getAbsolutePath());
    final File indexSegmentDir = new File(INDEX_DIR, driver.getSegmentName());
    _indexSegment = ColumnarSegmentLoader.load(indexSegmentDir, ReadMode.mmap);
}

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

private void setupSegmentList(int numberOfSegments) throws Exception {
    final String filePath = TestUtils
            .getFileFromResourceUrl(getClass().getClassLoader().getResource(SMALL_AVRO_DATA));
    _indexSegmentList.clear();/*from   w  w w. j a va2 s  .c om*/
    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:com.linkedin.pinot.routing.RoutingTableTest.java

@Test
public void testTimeBoundaryRegression() throws Exception {
    final FakePropertyStore propertyStore = new FakePropertyStore();
    final OfflineSegmentZKMetadata offlineSegmentZKMetadata = new OfflineSegmentZKMetadata();
    offlineSegmentZKMetadata.setTimeUnit(TimeUnit.DAYS);
    offlineSegmentZKMetadata.setEndTime(1234L);

    propertyStore.setContents(//from   w  ww  .j a v  a 2 s .  c  o  m
            ZKMetadataProvider.constructPropertyStorePathForSegment("myTable_OFFLINE", "someSegment_0"),
            offlineSegmentZKMetadata.toZNRecord());

    final ExternalView offlineExternalView = new ExternalView("myTable_OFFLINE");
    offlineExternalView.setState("someSegment_0", "Server_1.2.3.4_1234", "ONLINE");

    final MutableBoolean timeBoundaryUpdated = new MutableBoolean(false);

    HelixExternalViewBasedRouting routingTable = new HelixExternalViewBasedRouting(propertyStore,
            NO_LLC_ROUTING, null, new BaseConfiguration()) {
        @Override
        protected ExternalView fetchExternalView(String table) {
            return offlineExternalView;
        }

        @Override
        protected void updateTimeBoundary(String tableName, ExternalView externalView) {
            if (tableName.equals("myTable_OFFLINE")) {
                timeBoundaryUpdated.setValue(true);
            }
        }
    };
    routingTable.setBrokerMetrics(new BrokerMetrics(new MetricsRegistry()));

    Assert.assertFalse(timeBoundaryUpdated.booleanValue());

    final ArrayList<InstanceConfig> instanceConfigList = new ArrayList<>();
    instanceConfigList.add(new InstanceConfig("Server_1.2.3.4_1234"));

    routingTable.markDataResourceOnline("myTable_OFFLINE", offlineExternalView, instanceConfigList);
    routingTable.markDataResourceOnline("myTable_REALTIME", new ExternalView("myTable_REALTIME"), null);

    Assert.assertTrue(timeBoundaryUpdated.booleanValue());
}

From source file:com.linkedin.pinot.query.aggregation.AggregationGroupByWithDictionaryAndTrieTreeOperatorTest.java

private void setupSegment() throws Exception {
    final String filePath = TestUtils
            .getFileFromResourceUrl(getClass().getClassLoader().getResource(AVRO_DATA));
    if (INDEX_DIR.exists()) {
        FileUtils.deleteQuietly(INDEX_DIR);
    }/* w  w w  .j av a  2s .  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();

    LOGGER.debug("built at : {}", INDEX_DIR.getAbsolutePath());
    final File indexSegmentDir = new File(INDEX_DIR, driver.getSegmentName());
    _indexSegment = ColumnarSegmentLoader.load(indexSegmentDir, ReadMode.heap);
    _medataMap = ((SegmentMetadataImpl) _indexSegment.getSegmentMetadata()).getColumnMetadataMap();
}

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

@Test
public void testFromToIntervals() throws Exception {
    long now = System.currentTimeMillis();
    StatisticsQuery query = new StatisticsQuery(getParams("-1d", null, null), now);
    Assert.assertEquals(now - TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS), query.getFrom());
    Assert.assertEquals(now, query.getTo());

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

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

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

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

    // from + period > now => to = now
    query = new StatisticsQuery(getParams("-1d", null, "2d"), now);
    Assert.assertEquals(now - TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS), query.getFrom());
    Assert.assertEquals(now, query.getTo());

    // period is ignored, if from and to are specified
    query = new StatisticsQuery(getParams("-2d", "-1d", "1h"), now);
    Assert.assertEquals(now - TimeUnit.MILLISECONDS.convert(2, TimeUnit.DAYS), query.getFrom());
    Assert.assertEquals(now - TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS), query.getTo());

    // positive to interval is treated as not specified => to = now
    query = new StatisticsQuery(getParams("-1d", "4711d", null), now);
    Assert.assertEquals(now - TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS), query.getFrom());
    Assert.assertEquals(now, query.getTo());

    // positive from interval is treated as not specified => from = 0
    query = new StatisticsQuery(getParams("4711d", "-1d", null), now);
    Assert.assertEquals(0, query.getFrom());
    Assert.assertEquals(now - TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS), query.getTo());

    // positive from interval are treated as not specified => show 1 day
    query = new StatisticsQuery(getParams("4711d", "4711d", null), now);
    Assert.assertEquals(now - TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS), query.getFrom());
    Assert.assertEquals(now, query.getTo());
}

From source file:com.carvoyant.modularinput.Program.java

@Override
public void streamEvents(InputDefinition inputs, EventWriter ew)
        throws MalformedDataException, XMLStreamException, IOException {

    Service splunkSvc = getService(inputs.getServerUri(), inputs.getSessionKey());

    for (String inputName : inputs.getInputs().keySet()) {
        String clientId = ((SingleValueParameter) inputs.getInputs().get(inputName).get("clientId")).getValue();
        String clientSecret = ((SingleValueParameter) inputs.getInputs().get(inputName).get("clientSecret"))
                .getValue();/*from ww  w . ja va  2 s.c  om*/
        String token = ((SingleValueParameter) inputs.getInputs().get(inputName).get("token")).getValue();
        String refreshToken = ((SingleValueParameter) inputs.getInputs().get(inputName).get("refreshToken"))
                .getValue();

        SingleValueParameter expDate = (SingleValueParameter) inputs.getInputs().get(inputName)
                .get("expirationDate");
        long expirationDate = expDate.getLong();
        long expirationWindow = TimeUnit.DAYS.toMillis(1);
        long currentTime = System.currentTimeMillis();

        // If the access token is going to expire, then refresh it
        if ((expirationDate - currentTime) < expirationWindow) {
            JSONObject tokenJson = getRefreshToken(ew, clientId, clientSecret, refreshToken);

            if (tokenJson != null) {
                token = tokenJson.getString("access_token");
                refreshToken = tokenJson.getString("refresh_token");
                int ttl = tokenJson.getInt("expires_in");
                expirationDate = System.currentTimeMillis() + (long) ttl * 1000;

                // Update this configuration with the new settings
                String[] splunkApiInputName = inputName.split("://");
                updateInput(ew, splunkSvc, splunkApiInputName[1], clientId, clientSecret, token, refreshToken,
                        expirationDate);
            } else {
                throw new XMLStreamException("Cannot not refresh the token for " + inputName);
            }
        }

        // Get Carvoyant Data
        try {
            URL url = new URL("https://api.carvoyant.com/v1/api/account/data/?sinceLastCall=true");
            //            URL url = new URL("https://sandbox-api.carvoyant.com/sandbox/api/account/data/?sinceLastCall=true");
            URLConnection urlConnection = url.openConnection();

            String basicAuth = "Bearer " + token;
            urlConnection.setRequestProperty("Authorization", basicAuth);

            BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {

                JSONObject obj = new JSONObject(inputLine);
                JSONArray arr = obj.getJSONArray("data");

                for (int i = 0; i < arr.length(); i++) {
                    String timeString = arr.getJSONObject(i).getString("timestamp");
                    DateFormat format = new SimpleDateFormat("yyyyMMdd'T'HHmmssZ");
                    Date date = format.parse(timeString);

                    Event event = new Event();
                    event.setStanza(inputName);
                    event.setTime(date);
                    event.setData(arr.getJSONObject(i).toString());
                    ew.writeEvent(event);
                }
            }

            in.close();
        } catch (IOException ioe) {
            throw new XMLStreamException("Could not retrieve Carvoyant Data", ioe);
        } catch (ParseException pe) {
            throw new XMLStreamException("Could not parse Carvoyant Data", pe);
        }
    }
}

From source file:com.omertron.slackbot.functions.scheduler.AbstractBotTask.java

/**
 * Convert seconds to Hours, Minutes and Seconds
 *
 * @param seconds/* w w  w. j av  a 2 s .  c o  m*/
 * @return
 */
protected final String formatSeconds(long seconds) {
    int day = (int) TimeUnit.SECONDS.toDays(seconds);
    long hours = TimeUnit.SECONDS.toHours(seconds) - TimeUnit.DAYS.toHours(day);
    long minute = TimeUnit.SECONDS.toMinutes(seconds) - TimeUnit.DAYS.toMinutes(day)
            - TimeUnit.HOURS.toMinutes(hours);
    long second = TimeUnit.SECONDS.toSeconds(seconds) - TimeUnit.DAYS.toSeconds(day)
            - TimeUnit.HOURS.toSeconds(hours) - TimeUnit.MINUTES.toSeconds(minute);

    return String.format("%1$dh %2$dm %3$ds", hours, minute, second);
}