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.apache.metron.dataloads.bulk.ElasticsearchDataPrunerTest.java

@Test
public void testFilter() throws Exception {

    ObjectObjectHashMap<String, IndexMetaData> indexNames = new ObjectObjectHashMap();
    SimpleDateFormat dateChecker = new SimpleDateFormat("yyyyMMdd");
    int numDays = 5;
    String[] expectedIndices = new String[24];
    Date indexDate = new Date();

    indexDate.setTime(testDate.getTime() - TimeUnit.DAYS.toMillis(numDays));

    for (int i = 0, j = 0; i < numDays * 24; i++) {

        String indexName = "sensor_index_" + dateFormat.format(indexDate);
        //Delete 20160330
        if (dateChecker.format(indexDate).equals("20160330")) {
            expectedIndices[j++] = indexName;
        }/*from ww w.j a v  a2s.  c  om*/

        indexNames.put(indexName, null);
        indexDate.setTime(indexDate.getTime() + TimeUnit.HOURS.toMillis(1));

    }

    ImmutableOpenMap<String, IndexMetaData> testIndices = ImmutableOpenMap.copyOf(indexNames);

    ElasticsearchDataPruner pruner = new ElasticsearchDataPruner(testDate, 1, configuration, indexClient,
            "sensor_index_");
    pruner.indexClient = indexClient;

    Iterable<String> filteredIndices = pruner.getFilteredIndices(testIndices);

    Object[] indexArray = IteratorUtils.toArray(filteredIndices.iterator());
    Arrays.sort(indexArray);
    Arrays.sort(expectedIndices);

    assertArrayEquals(expectedIndices, indexArray);

}

From source file:de.phillme.PhotoSorter.java

private void detectNewEvent(PhotoFile photoFile, Date dateOld, Date dateNew, boolean lastFile)
        throws IOException {
    if (dateOld == null) {
        LOGGER.finest("\nBeginning... Using DateNew for first event");
        this.eventStartDate = dateNew;
        this.dateOld = dateNew;

        movePhotoToEvent(photoFile, this.eventStartDate);
        return;/*from  w ww .j  a  v  a  2 s . c o m*/
    }
    long dateDiffInHours = PhotoSorter.getDateDiff(dateOld, dateNew, TimeUnit.HOURS);

    if (dateDiffInHours > hoursBetweenEvents) {
        LOGGER.info("");
        LOGGER.finest("Open event will be closed. HoursbetweenEvents exceeded. Range: \n  " + dateOld
                + " to \n  " + dateNew);
        this.eventEndDate = dateOld;
        //TODO this handles only the event before the last event. for the last event this has to be repeated and file has to be moved
        this.eventList.add(handleEvent());

        this.eventStartDate = dateNew;

        this.photoNumberInEvent++;

        if (lastFile) {
            //this is the last file. This means the last file's time range triggered an end of another event
            //but should be an event by itself in the event list. This is what we do here
            LOGGER.info("Last file leads to an additional event.");

            this.eventEndDate = dateNew;
            this.eventList.add(handleEvent());
        }
        //after the new startDate for the event is set we can move the file to the new event folder
        movePhotoToEvent(photoFile, this.eventStartDate);
    } else {
        //increase photo number for filenames;
        this.photoNumberInEvent++;
        //move all files to current event
        movePhotoToEvent(photoFile, this.eventStartDate);

        if (lastFile) {
            //if this is the lastfile but has not enough time between, still add it
            LOGGER.finest("Found an event between \n  " + dateOld + " and \n  " + dateNew);
            this.eventEndDate = dateNew;
            this.eventList.add(handleEvent());
        }
    }
}

From source file:com.frontier45.flume.sink.elasticsearch2.ElasticSearchSink.java

private long parseTTL(String ttl) {
    matcher = matcher.reset(ttl);/*from w ww  .  ja  va  2  s.  c o  m*/
    while (matcher.find()) {
        if (matcher.group(2).equals("ms")) {
            return Long.parseLong(matcher.group(1));
        } else if (matcher.group(2).equals("s")) {
            return TimeUnit.SECONDS.toMillis(Integer.parseInt(matcher.group(1)));
        } else if (matcher.group(2).equals("m")) {
            return TimeUnit.MINUTES.toMillis(Integer.parseInt(matcher.group(1)));
        } else if (matcher.group(2).equals("h")) {
            return TimeUnit.HOURS.toMillis(Integer.parseInt(matcher.group(1)));
        } else if (matcher.group(2).equals("d")) {
            return TimeUnit.DAYS.toMillis(Integer.parseInt(matcher.group(1)));
        } else if (matcher.group(2).equals("w")) {
            return TimeUnit.DAYS.toMillis(7L * Integer.parseInt(matcher.group(1)));
        } else if (matcher.group(2).equals("")) {
            logger.info("TTL qualifier is empty. Defaulting to day qualifier.");
            return TimeUnit.DAYS.toMillis(Integer.parseInt(matcher.group(1)));
        } else {
            logger.debug("Unknown TTL qualifier provided. Setting TTL to 0.");
            return 0;
        }
    }
    logger.info("TTL not provided. Skipping the TTL config by returning 0.");
    return 0;
}

From source file:org.apache.marmotta.kiwi.infinispan.embedded.InfinispanEmbeddedCacheManager.java

/**
 * Return the prefix -> namespace cache from the cache manager. Used for looking up namespaces
 * @return/*from w  ww . ja  v  a 2 s.c om*/
 */
public Map getNamespacePrefixCache() {
    if (nsPrefixCache == null) {
        if (isClustered()) {
            Configuration nsprefixConfiguration = new ConfigurationBuilder().read(defaultConfiguration)
                    .clustering().cacheMode(CacheMode.REPL_ASYNC).eviction()
                    .maxEntries(config.getNamespaceCacheSize()).expiration().lifespan(1, TimeUnit.DAYS).build();
            cacheManager.defineConfiguration(NS_PREFIX_CACHE, nsprefixConfiguration);

        } else {
            Configuration nsprefixConfiguration = new ConfigurationBuilder().read(defaultConfiguration)
                    .eviction().maxEntries(config.getNamespaceCacheSize()).expiration()
                    .lifespan(1, TimeUnit.HOURS).build();
            cacheManager.defineConfiguration(NS_PREFIX_CACHE, nsprefixConfiguration);

        }
        nsPrefixCache = cacheManager.getCache(NS_PREFIX_CACHE).getAdvancedCache().withFlags(Flag.SKIP_LOCKING,
                Flag.SKIP_CACHE_LOAD, Flag.SKIP_REMOTE_LOOKUP);
    }
    return nsPrefixCache;
}

From source file:org.eclipse.gyrex.p2.internal.PackageManager.java

@Override
public IStatus verifyPackageIsModifiable(final String id)
        throws IllegalStateException, IllegalArgumentException {
    if (!IdHelper.isValidId(id))
        return new Status(IStatus.ERROR, P2Activator.SYMBOLIC_NAME, "invalid package id");

    try {//from w  ww. ja v a 2s  . c  o  m
        if (!isPackageNodeAvailable(id))
            return new Status(IStatus.ERROR, P2Activator.SYMBOLIC_NAME, "package does not exist");

        final Preferences pkgNode = getPackageNode(id);
        final InstallState installState = InstallState.fromString(pkgNode.get(PREF_KEY_INSTALL_STATE, null));
        if (installState == InstallState.ROLLOUT)
            return new Status(IStatus.ERROR, P2Activator.SYMBOLIC_NAME,
                    String.format("Package '%s' is marked for rollout! Please revoke it first.", id));
        else if (installState == InstallState.REVOKE) {
            final long revokeDuration = System.currentTimeMillis()
                    - pkgNode.getLong(PREF_KEY_INSTALL_STATE_TIMESTAMP, 0);
            if (revokeDuration < TimeUnit.HOURS.toMillis(48))
                return new Status(IStatus.ERROR, P2Activator.SYMBOLIC_NAME, String.format(
                        "Package '%s' was revoked %s! Please wait at least 48 hours before modifying a revoked package!",
                        id, toRelativeTime(revokeDuration)));
        }

        return Status.OK_STATUS;
    } catch (final BackingStoreException e) {
        return new Status(IStatus.ERROR, P2Activator.SYMBOLIC_NAME,
                String.format("Error accessing backend store. Unable to verify package modifiability. %s",
                        e.getMessage()),
                e);
    }
}

From source file:com.github.rinde.datgen.pdptw.DatasetGenerator.java

Dataset<GeneratedScenario> doGenerate() {

    final ListeningExecutorService service = MoreExecutors
            .listeningDecorator(Executors.newFixedThreadPool(builder.numThreads));
    final Dataset<GeneratedScenario> dataset = Dataset.naturalOrder();

    final List<ScenarioCreator> jobs = new ArrayList<>();

    final RandomGenerator rng = new MersenneTwister(builder.randomSeed);
    final Map<GeneratorSettings, IdSeedGenerator> rngMap = new LinkedHashMap<>();

    for (final Long urgency : builder.urgencyLevels) {
        for (final Double scale : builder.scaleLevels) {
            for (final Entry<TimeSeriesType, Collection<Range<Double>>> dynLevel : builder.dynamismLevels
                    .asMap().entrySet()) {

                final int reps = builder.numInstances * dynLevel.getValue().size();

                final long urg = urgency * 60 * 1000L;
                // The office hours is the period in which new orders are accepted,
                // it is defined as [0,officeHoursLength).
                final long officeHoursLength;
                if (urg < halfDiagTT) {
                    officeHoursLength = builder.scenarioLengthMs - twoDiagTT - PICKUP_DURATION
                            - DELIVERY_DURATION;
                } else {
                    officeHoursLength = builder.scenarioLengthMs - urg - oneAndHalfDiagTT - PICKUP_DURATION
                            - DELIVERY_DURATION;
                }//from www  . ja  va2 s  . c  o  m

                final int numOrders = DoubleMath.roundToInt(scale * numOrdersPerScale,
                        RoundingMode.UNNECESSARY);

                final ImmutableMap.Builder<String, String> props = ImmutableMap.builder();

                props.put("expected_num_orders", Integer.toString(numOrders));
                props.put("pickup_duration", Long.toString(PICKUP_DURATION));
                props.put("delivery_duration", Long.toString(DELIVERY_DURATION));
                props.put("width_height", String.format("%1.1fx%1.1f", AREA_WIDTH, AREA_WIDTH));

                // TODO store this in TimeSeriesType?
                final RangeSet<Double> rset = TreeRangeSet.create();
                for (final Range<Double> r : dynLevel.getValue()) {
                    rset.add(r);
                }

                // createTimeSeriesGenerator(dynLevel.getKey(), officeHoursLength,
                // numOrders, numOrdersPerScale, props);

                final GeneratorSettings set = GeneratorSettings.builder().setDayLength(builder.scenarioLengthMs)
                        .setOfficeHours(officeHoursLength).setTimeSeriesType(dynLevel.getKey())
                        .setDynamismRangeCenters(builder.dynamismRangeMap.subRangeMap(rset.span()))
                        .setUrgency(urg).setScale(scale).setNumOrders(numOrders).setProperties(props.build())
                        .build();

                final IdSeedGenerator isg = new IdSeedGenerator(rng.nextLong());
                rngMap.put(set, isg);

                for (int i = 0; i < reps; i++) {
                    final LocationGenerator lg = Locations.builder().min(0d).max(AREA_WIDTH).buildUniform();

                    final TimeSeriesGenerator tsg2 = createTimeSeriesGenerator(dynLevel.getKey(),
                            officeHoursLength, numOrders, numOrdersPerScale,
                            ImmutableMap.<String, String>builder());
                    final ScenarioGenerator gen = createGenerator(officeHoursLength, urg, scale, tsg2,
                            set.getDynamismRangeCenters(), lg, builder, numOrdersPerScale);

                    jobs.add(ScenarioCreator.create(isg.next(), set, gen));
                }
            }
        }
    }

    final AtomicLong currentJobs = new AtomicLong(0L);
    final AtomicLong datasetSize = new AtomicLong(0L);

    LOGGER.info(" - Submitting " + jobs.size() + " Jobs");
    for (final ScenarioCreator job : jobs) {
        submitJob(currentJobs, service, job, builder.numInstances, dataset, rngMap, datasetSize);
    }

    final long targetSize = builder.numInstances * builder.dynamismLevels.values().size()
            * builder.scaleLevels.size() * builder.urgencyLevels.size();
    while (datasetSize.get() < targetSize || dataset.size() < targetSize) {
        try {
            // LOGGER.info(" - Waiting, current size ==" + dataset.size());
            Thread.sleep(THREAD_SLEEP_DURATION);
        } catch (final InterruptedException e) {
            throw new IllegalStateException(e);
        }
    }

    LOGGER.info(" - Shutdown Service, Awaiting Termination");
    service.shutdown();
    try {
        service.awaitTermination(1L, TimeUnit.HOURS);
    } catch (final InterruptedException e) {
        throw new IllegalStateException(e);
    }

    LOGGER.info(" - Returning dataset");

    return dataset;
}

From source file:net.clcworld.thermometer.TakeTemperatureReadingActivity.java

@Override
public void onResume() {
    super.onResume();
    long lastReadingTime = mPrefs.getLong("LAST_READING", -1);
    if (lastReadingTime != -1) {
        long timeDelta = System.currentTimeMillis() - lastReadingTime;
        String templateStr = this.getString(R.string.timesincelastmeasurement);
        String timeSinceLastReading = String.format(templateStr, TimeUnit.MILLISECONDS.toHours(timeDelta),
                TimeUnit.MILLISECONDS.toMinutes(timeDelta)
                        - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(timeDelta)));
        final TextView timeSinceLastReadingTextView = (TextView) findViewById(R.id.timeSinceLastMeasurement);
        timeSinceLastReadingTextView.setText(timeSinceLastReading);

        if (mIsActivated && (timeDelta >= WARNING_THRESHOLD)) {
            if (mWarningDialog == null) {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setCancelable(false);
                builder.setTitle(R.string.warning_title);
                builder.setMessage(R.string.warning_message);
                builder.setPositiveButton(R.string.ok, null);
                mWarningDialog = builder.create();
            }//from   w ww.j  ava2s . co  m
            if (!mWarningDialog.isShowing()) {
                mWarningDialog.show();
            }
        }
    }
}

From source file:fr.gael.dhus.server.http.valve.processings.ProcessingValve.java

private String formatInterval(final long ns) {
    long l = ns / 1000000;
    final long hr = TimeUnit.MILLISECONDS.toHours(l);
    final long min = TimeUnit.MILLISECONDS.toMinutes(l - TimeUnit.HOURS.toMillis(hr));
    final long sec = TimeUnit.MILLISECONDS
            .toSeconds(l - TimeUnit.HOURS.toMillis(hr) - TimeUnit.MINUTES.toMillis(min));
    final long ms = TimeUnit.MILLISECONDS.toMillis(
            l - TimeUnit.HOURS.toMillis(hr) - TimeUnit.MINUTES.toMillis(min) - TimeUnit.SECONDS.toMillis(sec));
    return String.format("%02d:%02d:%02d.%03d", hr, min, sec, ms);
}

From source file:org.diorite.impl.DioriteCore.java

@Override
public String getVersion() {
    if (this.serverVersion == null) {
        SpammyError.err("Missing server version!", (int) TimeUnit.HOURS.toSeconds(1), "serverVersion");
        return "Unknown" + " (MC: " + Core.getMinecraftVersion() + ")";
    }/*  www.j a v  a  2 s.  c  o  m*/
    return this.serverVersion + " (MC: " + Core.getMinecraftVersion() + ")";
}

From source file:org.apache.hadoop.metrics2.sink.RollingFileSystemSink.java

/**
 * Extract the roll interval from the configuration and return it in
 * milliseconds.// w ww .ja  v a 2  s. co m
 *
 * @return the roll interval in millis
 */
@VisibleForTesting
protected long getRollInterval() {
    String rollInterval = properties.getString(ROLL_INTERVAL_KEY, DEFAULT_ROLL_INTERVAL);
    Pattern pattern = Pattern.compile("^\\s*(\\d+)\\s*([A-Za-z]*)\\s*$");
    Matcher match = pattern.matcher(rollInterval);
    long millis;

    if (match.matches()) {
        String flushUnit = match.group(2);
        int rollIntervalInt;

        try {
            rollIntervalInt = Integer.parseInt(match.group(1));
        } catch (NumberFormatException ex) {
            throw new MetricsException("Unrecognized flush interval: " + rollInterval
                    + ". Must be a number followed by an optional "
                    + "unit. The unit must be one of: minute, hour, day", ex);
        }

        if ("".equals(flushUnit)) {
            millis = TimeUnit.HOURS.toMillis(rollIntervalInt);
        } else {
            switch (flushUnit.toLowerCase()) {
            case "m":
            case "min":
            case "minute":
            case "minutes":
                millis = TimeUnit.MINUTES.toMillis(rollIntervalInt);
                break;
            case "h":
            case "hr":
            case "hour":
            case "hours":
                millis = TimeUnit.HOURS.toMillis(rollIntervalInt);
                break;
            case "d":
            case "day":
            case "days":
                millis = TimeUnit.DAYS.toMillis(rollIntervalInt);
                break;
            default:
                throw new MetricsException("Unrecognized unit for flush interval: " + flushUnit
                        + ". Must be one of: minute, hour, day");
            }
        }
    } else {
        throw new MetricsException("Unrecognized flush interval: " + rollInterval
                + ". Must be a number followed by an optional unit."
                + " The unit must be one of: minute, hour, day");
    }

    if (millis < 60000) {
        throw new MetricsException(
                "The flush interval property must be " + "at least 1 minute. Value was " + rollInterval);
    }

    return millis;
}