Example usage for java.util.concurrent TimeUnit HOURS

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

Introduction

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

Prototype

TimeUnit HOURS

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

Click Source Link

Document

Time unit representing sixty minutes.

Usage

From source file:org.efaps.esjp.accounting.transaction.Transaction_Base.java

/**
 * @param _parameter Parameter as passed by the eFaps API
 * @param _instance Instance of the period or subperiod
 * @param _date     date the rate must be evaluated for
 * @param _currentCurrencyInst instance of the currency the rate is wanted for
 * @return RateInfo instance/*w  w  w  .j  a  va  2s  . c  om*/
 * @throws EFapsException on error
 */
protected RateInfo evaluateRate(final Parameter _parameter, final Instance _instance, final DateTime _date,
        final Instance _currentCurrencyInst) throws EFapsException {
    final Instance instance;
    if (_instance.getType().isKindOf(CIAccounting.SubPeriod.getType())) {
        final PrintQuery print = new CachedPrintQuery(_instance, SubPeriod_Base.CACHEKEY);
        final SelectBuilder selPeriodInst = SelectBuilder.get().linkto(CIAccounting.SubPeriod.PeriodLink)
                .instance();
        print.addSelect(selPeriodInst);
        print.execute();
        instance = print.<Instance>getSelect(selPeriodInst);
    } else {
        instance = _instance;
    }

    final PrintQuery print = new CachedPrintQuery(instance).setLifespan(1).setLifespanUnit(TimeUnit.HOURS);
    final SelectBuilder sel = SelectBuilder.get().linkto(CIAccounting.Period.CurrencyLink).instance();
    print.addSelect(sel);
    print.execute();
    final Instance perCurrInst = print.<Instance>getSelect(sel);
    final Instance baseCurrency = Currency.getBaseCurrency();

    final Currency currency = getCurrency(_parameter);
    final RateInfo ret;
    if (perCurrInst.equals(baseCurrency) || _currentCurrencyInst == null) {
        ret = currency.evaluateRateInfo(_parameter, _date,
                _currentCurrencyInst == null ? perCurrInst : _currentCurrencyInst);
    } else {
        ret = currency.evaluateRateInfos(_parameter, _date, _currentCurrencyInst, perCurrInst)[2];
    }
    return ret;
}

From source file:org.alfresco.bm.event.mongo.MongoResultServiceTest.java

/**
 * Create some results but then search for something that does not match
 *///from w  w  w .  j  a  v a2  s .  c om
@Test
public void getZeroResultsUsingHandler() {
    pumpRecords(10);
    long after = resultService.getLastResult().getStartTime() + TimeUnit.HOURS.toMillis(1); // Make sure the query window is out of range

    final AtomicInteger count = new AtomicInteger();
    resultService.getResults(new ResultHandler() {
        @Override
        public boolean processResult(long fromTime, long toTime,
                Map<String, DescriptiveStatistics> statsByEventName, Map<String, Integer> failuresByEventName)
                throws Throwable {
            // Check that we have a failure count for each event
            if (failuresByEventName.size() != statsByEventName.size()) {
                throw new RuntimeException("Didn't have a failure count matching stats count.");
            }
            // Increment
            count.incrementAndGet();
            return true;
        }
    }, after, 20L, 10L, false);

    // Check
    assertEquals(0, count.get());
}

From source file:org.apache.metron.profiler.client.window.WindowProcessor.java

/**
 * We've set a time unit.  We support the timeunits provided by java.util.concurrent.TimeUnit
 * @param ctx/*from   w  w w  .  ja va 2s. c om*/
 */
@Override
public void exitTimeUnit(org.apache.metron.profiler.client.window.generated.WindowParser.TimeUnitContext ctx) {
    checkForException(ctx);
    switch (normalizeTimeUnit(ctx.getText())) {
    case "DAY":
        stack.push(new Token<>(TimeUnit.DAYS, TimeUnit.class));
        break;
    case "HOUR":
        stack.push(new Token<>(TimeUnit.HOURS, TimeUnit.class));
        break;
    case "MINUTE":
        stack.push(new Token<>(TimeUnit.MINUTES, TimeUnit.class));
        break;
    case "SECOND":
        stack.push(new Token<>(TimeUnit.SECONDS, TimeUnit.class));
        break;
    default:
        throw new IllegalStateException("Unsupported time unit: " + ctx.getText()
                + ".  Supported units are limited to: day, hour, minute, second "
                + "with any pluralization or capitalization.");
    }
}

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

@Test
public void updateOnTimeframeHistogramShouldReplaceLastValue() throws NoSuchMethodException,
        InstantiationException, IllegalAccessException, InvocationTargetException {
    givenTimeframeHistogram();//from   w w w .j  av a2  s.  c om
    givenQueueCountValuesFor(48);
    givenBinUnitOf((double) TimeUnit.HOURS.toMillis(1));
    givenBinCountOf(48);
    givenBinLabelOf(TimeUnit.HOURS.name());
    givenDataLabelOf("COUNT");
    givenHistogramTypeOf("Queued Movers");
    givenHighestBinOf(getHoursInThePastFromNow(0));
    whenConfigureIsCalled();
    assertThatUpdateReplacesLastValue();
}

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

private double getHoursInThePastFromNow(int hours) {
    Calendar calendar = Calendar.getInstance();
    long diff = TimeUnit.HOURS.toMillis(hours);
    calendar.setTimeInMillis(now - diff);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);
    return (double) calendar.getTimeInMillis();
}

From source file:com.linkedin.pinot.controller.helix.retention.RetentionManagerTest.java

/**
 * @throws JSONException/*ww  w  .j  a v  a2 s .c  om*/
 * @throws UnsupportedEncodingException
 * @throws IOException
 * @throws InterruptedException
 */
@Test
public void testRetentionWithHoursTimeUnit()
        throws JSONException, UnsupportedEncodingException, IOException, InterruptedException {
    _retentionManager = new RetentionManager(_pinotHelixResourceManager, 5);
    _retentionManager.start();
    long theDayAfterTomorrowSinceEpoch = System.currentTimeMillis() / 1000 / 60 / 60 / 24 + 2;
    long hoursSinceEpochTimeStamp = theDayAfterTomorrowSinceEpoch * 24;
    for (int i = 0; i < 10; ++i) {
        SegmentMetadata segmentMetadata = getTimeSegmentMetadataImpl("373056", "373056",
                TimeUnit.HOURS.toString());
        registerSegmentMetadata(segmentMetadata);
        Thread.sleep(100);
    }
    for (int i = 0; i < 10; ++i) {
        SegmentMetadata segmentMetadata = getTimeSegmentMetadataImpl(hoursSinceEpochTimeStamp + "",
                hoursSinceEpochTimeStamp + "", TimeUnit.HOURS.toString());
        registerSegmentMetadata(segmentMetadata);
        Thread.sleep(100);
    }
    validate();
    cleanupSegments();
}

From source file:org.apache.rya.accumulo.mr.merge.util.TimeUtils.java

/**
 * Convert a millisecond duration to a string format.
 * @param durationMs A duration to convert to a string form.
 * @param showSign {@code true} to show if the duration is positive or negative. {@code false}
 * to not display the sign./*from ww  w . j a va2s  .  c  om*/
 * @return A string of the form "X Days Y Hours Z Minutes A Seconds B Milliseconds".
 */
public static String getDurationBreakdown(final long durationMs, final boolean showSign) {
    long tempDurationMs = Math.abs(durationMs);

    final long days = TimeUnit.MILLISECONDS.toDays(tempDurationMs);
    tempDurationMs -= TimeUnit.DAYS.toMillis(days);
    final long hours = TimeUnit.MILLISECONDS.toHours(tempDurationMs);
    tempDurationMs -= TimeUnit.HOURS.toMillis(hours);
    final long minutes = TimeUnit.MILLISECONDS.toMinutes(tempDurationMs);
    tempDurationMs -= TimeUnit.MINUTES.toMillis(minutes);
    final long seconds = TimeUnit.MILLISECONDS.toSeconds(tempDurationMs);
    tempDurationMs -= TimeUnit.SECONDS.toMillis(seconds);
    final long milliseconds = TimeUnit.MILLISECONDS.toMillis(tempDurationMs);

    final StringBuilder sb = new StringBuilder();
    if (tempDurationMs != 0 && showSign) {
        sb.append(tempDurationMs > 0 ? "+" : "-");
    }
    if (days > 0) {
        sb.append(days);
        sb.append(days == 1 ? " Day " : " Days ");
    }
    if (hours > 0) {
        sb.append(hours);
        sb.append(hours == 1 ? " Hour " : " Hours ");
    }
    if (minutes > 0) {
        sb.append(minutes);
        sb.append(minutes == 1 ? " Minute " : " Minutes ");
    }
    if (seconds > 0) {
        sb.append(seconds);
        sb.append(seconds == 1 ? " Second " : " Seconds ");
    }
    if (milliseconds > 0 || (!showSign && sb.length() == 0) || (showSign && sb.length() == 1)) {
        // At least show the milliseconds if nothing else has been shown so far
        sb.append(milliseconds);
        sb.append(milliseconds == 1 ? " Millisecond" : " Milliseconds");
    }

    return StringUtils.trim(sb.toString());
}

From source file:org.apache.tez.dag.app.launcher.ContainerLauncherImpl.java

@Override
public void serviceStart() {
    cmProxy = new ContainerManagementProtocolProxy(getConfig());

    ThreadFactory tf = new ThreadFactoryBuilder().setNameFormat("ContainerLauncher #%d").setDaemon(true)
            .build();//from  www.jav  a2s.c o m

    // Start with a default core-pool size of 10 and change it dynamically.
    launcherPool = new ThreadPoolExecutor(INITIAL_POOL_SIZE, Integer.MAX_VALUE, 1, TimeUnit.HOURS,
            new LinkedBlockingQueue<Runnable>(), tf);
    eventHandlingThread = new Thread() {
        @Override
        public void run() {
            NMCommunicatorEvent event = null;
            while (!Thread.currentThread().isInterrupted()) {
                try {
                    event = eventQueue.take();
                } catch (InterruptedException e) {
                    LOG.error("Returning, interrupted : " + e);
                    return;
                }
                int poolSize = launcherPool.getCorePoolSize();

                // See if we need up the pool size only if haven't reached the
                // maximum limit yet.
                if (poolSize != limitOnPoolSize) {

                    // nodes where containers will run at *this* point of time. This is
                    // *not* the cluster size and doesn't need to be.
                    int numNodes = context.getAllNodes().size();
                    int idealPoolSize = Math.min(limitOnPoolSize, numNodes);

                    if (poolSize < idealPoolSize) {
                        // Bump up the pool size to idealPoolSize+INITIAL_POOL_SIZE, the
                        // later is just a buffer so we are not always increasing the
                        // pool-size
                        int newPoolSize = Math.min(limitOnPoolSize, idealPoolSize + INITIAL_POOL_SIZE);
                        LOG.info("Setting ContainerLauncher pool size to " + newPoolSize
                                + " as number-of-nodes to talk to is " + numNodes);
                        launcherPool.setCorePoolSize(newPoolSize);
                    }
                }

                // the events from the queue are handled in parallel
                // using a thread pool
                launcherPool.execute(createEventProcessor(event));

                // TODO: Group launching of multiple containers to a single
                // NodeManager into a single connection
            }
        }
    };
    eventHandlingThread.setName("ContainerLauncher Event Handler");
    eventHandlingThread.start();
}

From source file:org.openhie.openempi.configuration.Configuration.java

private TimeUnit getTimeUnit(org.openhie.openempi.configuration.xml.ScheduledTask.TimeUnit.Enum timeUnit) {
    if (timeUnit == org.openhie.openempi.configuration.xml.ScheduledTask.TimeUnit.DAYS) {
        return TimeUnit.DAYS;
    } else if (timeUnit == org.openhie.openempi.configuration.xml.ScheduledTask.TimeUnit.HOURS) {
        return TimeUnit.HOURS;
    } else if (timeUnit == org.openhie.openempi.configuration.xml.ScheduledTask.TimeUnit.MICROSECONDS) {
        return TimeUnit.MICROSECONDS;
    } else if (timeUnit == org.openhie.openempi.configuration.xml.ScheduledTask.TimeUnit.MILLISECONDS) {
        return TimeUnit.MILLISECONDS;
    } else if (timeUnit == org.openhie.openempi.configuration.xml.ScheduledTask.TimeUnit.MINUTES) {
        return TimeUnit.MINUTES;
    } else if (timeUnit == org.openhie.openempi.configuration.xml.ScheduledTask.TimeUnit.NANOSECONDS) {
        return TimeUnit.NANOSECONDS;
    } else if (timeUnit == org.openhie.openempi.configuration.xml.ScheduledTask.TimeUnit.SECONDS) {
        return TimeUnit.SECONDS;
    }//  w ww . j a v a2  s  . co  m
    log.warn("An unknown time-unit was specified for a scheduled task of " + timeUnit
            + " so will resort to seconds as the default time unit.");
    return TimeUnit.SECONDS;
}

From source file:com.erudika.scoold.controllers.SigninController.java

@ResponseBody
@GetMapping("/scripts/globals.js")
public ResponseEntity<String> globals(HttpServletRequest req, HttpServletResponse res) {
    res.setContentType("text/javascript");
    StringBuilder sb = new StringBuilder();
    sb.append("APPID = \"").append(Config.getConfigParam("access_key", "app:scoold").substring(4))
            .append("\"; ");
    sb.append("ENDPOINT = \"").append(pc.getEndpoint()).append("\"; ");
    sb.append("CONTEXT_PATH = \"").append(CONTEXT_PATH).append("\"; ");
    sb.append("CSRF_COOKIE = \"").append(CSRF_COOKIE).append("\"; ");
    sb.append("FB_APP_ID = \"").append(Config.FB_APP_ID).append("\"; ");
    sb.append("GOOGLE_CLIENT_ID = \"").append(Config.getConfigParam("google_client_id", "")).append("\"; ");
    sb.append("GOOGLE_ANALYTICS_ID = \"").append(Config.getConfigParam("google_analytics_id", ""))
            .append("\"; ");
    sb.append("GITHUB_APP_ID = \"").append(Config.GITHUB_APP_ID).append("\"; ");
    sb.append("LINKEDIN_APP_ID = \"").append(Config.LINKEDIN_APP_ID).append("\"; ");
    sb.append("TWITTER_APP_ID = \"").append(Config.TWITTER_APP_ID).append("\"; ");
    sb.append("MICROSOFT_APP_ID = \"").append(Config.MICROSOFT_APP_ID).append("\"; ");
    sb.append("OAUTH2_ENDPOINT = \"").append(Config.getConfigParam("security.oauth.authz_url", ""))
            .append("\"; ");
    sb.append("OAUTH2_APP_ID = \"").append(Config.getConfigParam("oa2_app_id", "")).append("\"; ");
    sb.append("OAUTH2_SCOPE = \"").append(Config.getConfigParam("security.oauth.scope", "")).append("\"; ");

    Locale currentLocale = utils.getCurrentLocale(utils.getLanguageCode(req), req);
    sb.append("RTL_ENABLED = ").append(utils.isLanguageRTL(currentLocale.getLanguage())).append("; ");
    String result = sb.toString();
    return ResponseEntity.ok().cacheControl(CacheControl.maxAge(1, TimeUnit.HOURS)).eTag(Utils.md5(result))
            .body(result);//w  ww .  ja  v  a 2 s  . co m
}