List of usage examples for java.util.concurrent TimeUnit HOURS
TimeUnit HOURS
To view the source code for java.util.concurrent TimeUnit HOURS.
Click Source Link
From source file:org.oncoblocks.centromere.dataimport.cli.CommandLineRunner.java
/** * From http://stackoverflow.com/a/6710604/1458983 * Converts a long-formatted timespan into a human-readable string that denotes the length of time * that has elapsed.//from w w w.j a v a2s . c o m * @param l Long representation of a diff between two time stamps. * @return String formatted time span. */ private static String formatInterval(final long l) { 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:com.enigmastation.ml.bayes.CorpusTest.java
@Test(groups = { "fulltest" }) public void testCorpus() throws URISyntaxException, IOException, InterruptedException { final Classifier classifier = new FisherClassifierImpl(); ExecutorService service = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); // first we expand the test dataset URL resource = this.getClass().getResource("/src/test/resources/publiccorpus"); File resourceFile = new File(resource.toURI()); String[] dataFileNames = resourceFile.list(new FilenameFilter() { @Override/*from w w w . j a v a2 s. com*/ public boolean accept(File dir, String name) { return name.endsWith(".bz2"); } }); List<String> directories = new ArrayList<String>(); final List<File> trainingFiles = new ArrayList<>(); for (String fileName : dataFileNames) { directories.add(expandFile(fileName)); } // collect every name, plus mark to delete on exit for (String inputDirectory : directories) { URL url = this.getClass().getResource(inputDirectory); File[] dataFiles = new File(url.toURI()).listFiles(); for (File f : dataFiles) { handleFiles(f, trainingFiles); } } long startTime = System.currentTimeMillis(); final int[] counter = { 0 }; final int[] marker = { 0 }; // now let's walk through a training cycle for (final File file : trainingFiles) { service.submit(new Runnable() { @Override public void run() { if ((++marker[0]) % 100 == 0) { System.out.println("Progress training: " + marker[0] + " of " + trainingFiles.size()); } if (counter[0] > 2) { try { trainWith(classifier, file); } catch (IOException e) { throw new RuntimeException(e); } } counter[0] = (counter[0] + 1) % 10; } }); } service.shutdown(); service.awaitTermination(2, TimeUnit.HOURS); service = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); long endTime = System.currentTimeMillis(); System.out.printf("Training took %d ms%n", (endTime - startTime)); startTime = System.currentTimeMillis(); marker[0] = 0; // now test against the training data for (final File file : trainingFiles) { service.submit(new Runnable() { public void run() { if ((++marker[0]) % 100 == 0) { System.out.println("Progress evaluating: " + marker[0] + " of " + trainingFiles.size()); } if (counter[0] < 3) { try { classify(classifier, file); } catch (IOException e) { throw new RuntimeException(e); } } counter[0] = (counter[0] + 1) % 10; } }); } service.shutdown(); service.awaitTermination(2, TimeUnit.HOURS); endTime = System.currentTimeMillis(); System.out.printf("Training accuracy: %d tests, %f%% accuracy%n", tests, (hits * 100.0) / tests); System.out.printf("Training took %d ms%n", (endTime - startTime)); }
From source file:org.eclipse.skalli.core.rest.admin.StatisticsQuery.java
private long getTimeInterval(String param) { long timeInterval = 0; if (StringUtils.isNotBlank(param)) { int defaultValue = 0; TimeUnit unit = TimeUnit.DAYS; char unitSymbol = param.charAt(param.length() - 1); if (unitSymbols.indexOf(unitSymbol) >= 0) { if (unitSymbol == 'h' || unitSymbol == 'H') { unit = TimeUnit.HOURS; } else if (unitSymbol == 'm' || unitSymbol == 'M') { unit = TimeUnit.MINUTES; }//from w w w . j a v a 2 s.c o m param = StringUtils.chop(param); defaultValue = 1; } int value = NumberUtils.toInt(param, defaultValue); if (value != 0) { timeInterval = TimeUnit.MILLISECONDS.convert(value, unit); } } return timeInterval; }
From source file:net.sourceforge.subsonic.backend.service.EmailReminderGenerator.java
public void init() { Runnable task = new Runnable() { public void run() { try { LOG.info("Starting email reminder generator."); EmailSession emailSession = new EmailSession(); Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, 7); Date in7Days = cal.getTime(); cal.add(Calendar.DATE, 1); Date in8Days = cal.getTime(); cal.add(Calendar.DATE, 6); Date in14Days = cal.getTime(); cal.add(Calendar.DATE, 1); Date in15Days = cal.getTime(); LOG.info("In 7 days: " + in7Days); LOG.info("In 8 days: " + in8Days); LOG.info("In 14 days: " + in14Days); LOG.info("In 15 days: " + in15Days); processPayments(emailSession, in7Days, in8Days); processPayments(emailSession, in14Days, in15Days); processSubscriptions(emailSession, in7Days, in8Days); processSubscriptions(emailSession, in14Days, in15Days); LOG.info("Completed email reminder generator."); } catch (Throwable x) { LOG.error("Failed to process reminder emails.", x); }// w w w . j ava 2s .c o m } }; executor.scheduleWithFixedDelay(task, DELAY_HOURS, DELAY_HOURS, TimeUnit.HOURS); LOG.info("Scheduled email reminder generator to run every " + DELAY_HOURS + " hours."); }
From source file:se.team05.activity.ShowResultsActivity.java
/** * This method will calculate and present the values of the result. *//*from www .jav a 2 s . co m*/ private void showResults() { int timeInSeconds = result.getTime(); long millis = timeInSeconds * 1000; int distanceInMeters = result.getDistance(); double speed = (distanceInMeters / timeInSeconds) * 3.6; long timestamp = result.getTimestamp(); Date date = new Date(timestamp * 1000); int calories = result.getCalories(); //Present date TextView dateView = (TextView) findViewById(R.id.show_date_result_textview); String dateString = String.valueOf(date); dateView.setText(dateString); //Present time TextView timeView = (TextView) findViewById(R.id.show_time_result_textview); String formattedTimeString = String.format(" %02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis), TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)), TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))); timeView.setText(formattedTimeString); //Present distance TextView distanceView = (TextView) findViewById(R.id.show_distance_result_textview); String formattedDistanceString = String.format(" %,d", distanceInMeters); distanceView.setText(formattedDistanceString + getString(R.string.km)); //Present speed TextView speedView = (TextView) findViewById(R.id.show_speed_result_textview); String speedString = String.valueOf(speed); speedView.setText(speedString + getString(R.string.km) + "/" + getString(R.string.h)); //Present calories TextView caloriesView = (TextView) findViewById(R.id.show_calories_result_textview); String caloriesString = String.valueOf(calories); caloriesView.setText(caloriesString + getString(R.string.kcal)); }
From source file:com.todo.backend.config.MetricsConfiguration.java
@PostConstruct public void init() { log.debug("Registering JVM gauges"); metricRegistry.register(PROP_METRIC_REG_JVM_MEMORY, new MemoryUsageGaugeSet()); metricRegistry.register(PROP_METRIC_REG_JVM_GARBAGE, new GarbageCollectorMetricSet()); metricRegistry.register(PROP_METRIC_REG_JVM_THREADS, new ThreadStatesGaugeSet()); metricRegistry.register(PROP_METRIC_REG_JVM_FILES, new FileDescriptorRatioGauge()); metricRegistry.register(PROP_METRIC_REG_JVM_BUFFERS, new BufferPoolMetricSet(ManagementFactory.getPlatformMBeanServer())); if (customProperties.getMetrics().getLogs().isEnabled()) { log.info("Initializing Metrics Log reporting..."); final Slf4jReporter reporter = Slf4jReporter.forRegistry(metricRegistry) .outputTo(LoggerFactory.getLogger(METRICS)).convertRatesTo(TimeUnit.SECONDS) .convertDurationsTo(TimeUnit.MILLISECONDS).build(); reporter.start(1, TimeUnit.HOURS); }//from w w w . j a va 2 s .c o m if (customProperties.getMetrics().getGraphite().isEnabled()) { log.info("Initializing Metrics Graphite reporting..."); final String host = customProperties.getMetrics().getGraphite().getHost(); final Integer port = customProperties.getMetrics().getGraphite().getPort(); final String prefix = customProperties.getMetrics().getGraphite().getPrefix(); final Graphite graphite = new Graphite(new InetSocketAddress(host, port)); final GraphiteReporter graphiteReporter = GraphiteReporter.forRegistry(metricRegistry) .convertRatesTo(TimeUnit.SECONDS).convertDurationsTo(TimeUnit.MILLISECONDS).prefixedWith(prefix) .build(graphite); graphiteReporter.start(1, TimeUnit.HOURS); } }
From source file:com.linkedin.pinot.core.segment.index.loader.LoadersTest.java
@BeforeMethod public void setUp() throws Exception { INDEX_DIR = Files.createTempDirectory(LoadersTest.class.getName() + "_segmentDir").toFile(); final String filePath = TestUtils .getFileFromResourceUrl(Loaders.class.getClassLoader().getResource(AVRO_DATA)); final SegmentGeneratorConfig config = SegmentTestUtils.getSegmentGenSpecWithSchemAndProjectedColumns( new File(filePath), INDEX_DIR, "daysSinceEpoch", TimeUnit.HOURS, "testTable"); config.setSegmentNamePostfix("1"); config.setTimeColumnName("daysSinceEpoch"); final SegmentIndexCreationDriver driver = SegmentCreationDriverFactory.get(null); driver.init(config);//from w w w . j av a 2 s. c o m driver.build(); segmentDirectory = new File(INDEX_DIR, driver.getSegmentName()); Configuration tableConfig = new PropertiesConfiguration(); tableConfig.addProperty(IndexLoadingConfigMetadata.KEY_OF_SEGMENT_FORMAT_VERSION, "v1"); v1LoadingConfig = new IndexLoadingConfigMetadata(tableConfig); tableConfig.clear(); tableConfig.addProperty(IndexLoadingConfigMetadata.KEY_OF_SEGMENT_FORMAT_VERSION, "v3"); v3LoadingConfig = new IndexLoadingConfigMetadata(tableConfig); }
From source file:org.apache.hadoop.hive.common.type.HiveIntervalDayTime.java
public void set(int days, int hours, int minutes, int seconds, int nanos) { long totalSeconds = seconds; totalSeconds += TimeUnit.DAYS.toSeconds(days); totalSeconds += TimeUnit.HOURS.toSeconds(hours); totalSeconds += TimeUnit.MINUTES.toSeconds(minutes); totalSeconds += TimeUnit.NANOSECONDS.toSeconds(nanos); nanos = nanos % IntervalDayTimeUtils.NANOS_PER_SEC; this.totalSeconds = totalSeconds; this.nanos = nanos; normalizeSecondsAndNanos();//from w ww . j a v a 2 s . c om }
From source file:com.serphacker.serposcope.task.proxy.ProxyChecker.java
@Override public void run() { LOG.info("starting proxy checking task, threads = {}, timeout in MS = {}", nThread, timeoutMS); long start = System.currentTimeMillis(); List<Proxy> proxies = db.proxy.list(); if (proxies == null || proxies.isEmpty()) { LOG.debug("no proxy to check"); return;// w w w . j a va2 s . c o m } totalProxies = proxies.size(); ExecutorService executor = Executors.newFixedThreadPool(nThread); db.proxy.updateStatus(Proxy.Status.UNCHECKED, proxies.stream().map((t) -> t.getId()).collect(Collectors.toList())); for (Proxy proxy : proxies) { executor.submit(new Runnable() { @Override public void run() { ScrapClient cli = new ScrapClient(); cli.setTimeout(timeoutMS); ScrapProxy scrapProxy = proxy.toScrapProxy(); cli.setProxy(scrapProxy); LOG.info("checking {}", scrapProxy); Proxy.Status proxyStatus = Proxy.Status.ERROR; // try{Thread.sleep(30000l);}catch(Exception ex){} int httpStatus = cli.get(judgeUrl); if (httpStatus == 200 && cli.getContentAsString() != null) { Matcher matcher = PATTERN_IP.matcher(cli.getContentAsString()); if (matcher.find()) { proxy.setRemoteip(matcher.group(1)); proxyStatus = Proxy.Status.OK; } } proxy.setStatus(proxyStatus); proxy.setLastCheck(LocalDateTime.now()); db.proxy.update(proxy); checked.incrementAndGet(); } }); } executor.shutdown(); try { executor.awaitTermination(1, TimeUnit.HOURS); } catch (InterruptedException ex) { executor.shutdownNow(); } LOG.info("proxy checking finished in {}", DurationFormatUtils.formatDurationHMS(System.currentTimeMillis() - start)); }
From source file:org.apache.nifi.web.security.x509.X509AuthenticationProviderTest.java
@Before public void setup() { extractor = new SubjectDnX509PrincipalExtractor(); certificateIdentityProvider = mock(X509IdentityProvider.class); when(certificateIdentityProvider.authenticate(any(X509Certificate[].class))).then(invocation -> { final X509Certificate[] certChain = invocation.getArgumentAt(0, X509Certificate[].class); final String identity = extractor.extractPrincipal(certChain[0]).toString(); if (INVALID_CERTIFICATE.equals(identity)) { throw new IllegalArgumentException(); }// w w w .j a v a2 s . c om return new AuthenticationResponse(identity, identity, TimeUnit.MILLISECONDS.convert(12, TimeUnit.HOURS), ""); }); authorizer = mock(Authorizer.class); when(authorizer.authorize(any(AuthorizationRequest.class))).then(invocation -> { final AuthorizationRequest request = invocation.getArgumentAt(0, AuthorizationRequest.class); if (UNTRUSTED_PROXY.equals(request.getIdentity())) { return AuthorizationResult.denied(); } return AuthorizationResult.approved(); }); x509AuthenticationProvider = new X509AuthenticationProvider(certificateIdentityProvider, authorizer, NiFiProperties.createBasicNiFiProperties(null, null)); }