List of usage examples for java.util.concurrent TimeUnit DAYS
TimeUnit DAYS
To view the source code for java.util.concurrent TimeUnit DAYS.
Click Source Link
From source file:com.lastsoft.plog.adapter.PlayAdapter.java
@Override public void onBindViewHolder(final ViewHolder viewHolder, final int position) { //Log.d(TAG, "Element " + position + " set."); // Get element from your dataset at this position and replace the contents of the view // with that element //if (searchQuery.equals("") || (games.get(position).gameName.toLowerCase().contains(searchQuery.toLowerCase()))) { DateFormat outputFormatter = new SimpleDateFormat("MM/dd/yyyy"); Date theDate = plays.get(position).playDate; long diff = new Date().getTime() - theDate.getTime(); long days = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS); String output_date;/* w w w . j a v a 2 s . c om*/ if (days == 0) { output_date = mActivity.getString(R.string.played_label) + mActivity.getString(R.string.less_than_a_day_ago); } else if (days == 1) { output_date = mActivity.getString(R.string.played_label) + days + mActivity.getString(R.string.day_ago_label); } else if (days <= 6) { output_date = mActivity.getString(R.string.played_label) + days + mActivity.getString(R.string.days_ago_label); } else { output_date = mActivity.getString(R.string.played_label) + outputFormatter.format(theDate); // Output : 01/20/2012 } //String output_date = outputFormatter.format(theDate); // Output : 01/20/2012 if (plays.get(position).playLocation != null) { output_date = output_date + " at " + Location.findById(Location.class, plays.get(position).playLocation.getId()).locationName; } if (plays.get(position).playNotes != null && !plays.get(position).playNotes.equals("")) { viewHolder.getPlayDescView().setVisibility(View.VISIBLE); viewHolder.getPlayDescView().setText("\"" + plays.get(position).playNotes + "\""); } else { Log.d("V1", "gone"); viewHolder.getPlayDescView().setVisibility(View.GONE); } viewHolder.getGameNameView().setText(GamesPerPlay.getBaseGame(plays.get(position)).gameName); viewHolder.getPlayDateView().setText(output_date); viewHolder.getImageView().setTransitionName("imageTrans" + position); viewHolder.getImageView().setTag("imageTrans" + position); viewHolder.getGameNameView().setTransitionName("nameTrans" + position); viewHolder.getGameNameView().setTag("nameTrans" + position); viewHolder.getPlayDateView().setTransitionName("dateTrans" + position); viewHolder.getPlayDateView().setTag("dateTrans" + position); viewHolder.getClickLayout().setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (SystemClock.elapsedRealtime() - mLastClickTime < 2000) { return; } mLastClickTime = SystemClock.elapsedRealtime(); ((MainActivity) mActivity).onPlayClicked(plays.get(position), mFragment, viewHolder.getImageView(), viewHolder.getGameNameView(), viewHolder.getPlayDateView(), position, fromDrawer, playListType, sortType, searchQuery); } }); viewHolder.getOverflowLayout().setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { playPopup(view, position); } }); String playPhoto; playPhoto = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/Plog/" + plays.get(position).playPhoto; if (plays.get(position).playPhoto != null && (plays.get(position).playPhoto.equals("") || new File(playPhoto).exists() == false)) { String gameThumb = GamesPerPlay.getBaseGame(plays.get(position)).gameThumb; if (gameThumb != null && !gameThumb.equals("")) { //ImageLoader.getInstance().displayImage("http:" + GamesPerPlay.getBaseGame(plays.get(position)).gameThumb, viewHolder.getImageView(), options); //ImageLoader.getInstance().loadImage("http:" + GamesPerPlay.getBaseGame(plays.get(position)).gameThumb, options, null); Picasso.with(mActivity).load("http:" + GamesPerPlay.getBaseGame(plays.get(position)).gameThumb) .fit().into(viewHolder.getImageView()); } else { viewHolder.getImageView().setImageDrawable(null); } } else { String thumbPath = playPhoto.substring(0, playPhoto.length() - 4) + "_thumb6.jpg"; if (new File(thumbPath).exists()) { //ImageLoader.getInstance().displayImage("file://" + thumbPath, viewHolder.getImageView(), options); //ImageLoader.getInstance().loadImage("file://" + playPhoto, options, null); Picasso.with(mActivity).load("file://" + thumbPath).into(viewHolder.getImageView()); } else { ImageLoader.getInstance().displayImage("file://" + playPhoto, viewHolder.getImageView(), options); //Picasso.with(mActivity).load(playPhoto).fit().into(viewHolder.getImageView()); // make a thumb String thumbPath2 = playPhoto.substring(0, playPhoto.length() - 4) + "_thumb6.jpg"; try { FileInputStream fis; fis = new FileInputStream(playPhoto); Bitmap imageBitmap = BitmapFactory.decodeStream(fis); Bitmap b = resizeImageForImageView(imageBitmap, 500); if (b != null) { try { b.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(new File(thumbPath2))); } catch (Exception ignored) { } b = null; } if (imageBitmap != null) { imageBitmap = null; } Picasso.with(mActivity).load("file://" + thumbPath2).resize(500, 500).centerCrop() .into(viewHolder.getImageView()); } catch (Exception e) { e.printStackTrace(); } //still use the og picture. next time there will be a thumb } //Picasso.with(mActivity).load(playPhoto).fetch(); //ImageLoader.getInstance().loadImage(playPhoto, options, null); } viewHolder.getPlayWinnerView().setTypeface(null, Typeface.ITALIC); /*if (plays.get(position).winners != null) { viewHolder.getPlayWinnerView().setText(mActivity.getString(R.string.winners) + plays.get(position).winners); }else{*/ String winners = Play.getWinners(plays.get(position)); if (winners == null) { viewHolder.getPlayWinnerView() .setText(mActivity.getString(R.string.winners) + mActivity.getString(R.string.none)); } else { viewHolder.getPlayWinnerView().setText(mActivity.getString(R.string.winners) + winners); } //} }
From source file:com.linkedin.pinot.controller.helix.retention.RetentionManagerTest.java
/** * Test with daysSinceEpoch time unit and make 10 segments with expired time value, 10 segments * with the day after tomorrow's time stamp. * @throws JSONException//from ww w . j a va2 s.c o m * @throws UnsupportedEncodingException * @throws IOException * @throws InterruptedException */ @Test public void testRetentionWithDaysTimeUnit() throws JSONException, UnsupportedEncodingException, IOException, InterruptedException { _retentionManager = new RetentionManager(_pinotHelixResourceManager, 5); _retentionManager.start(); long theDayAfterTomorrowSinceEpoch = System.currentTimeMillis() / 1000 / 60 / 60 / 24 + 2; for (int i = 0; i < 10; ++i) { SegmentMetadata segmentMetadata = getTimeSegmentMetadataImpl("15544", "15544", TimeUnit.DAYS.toString()); registerSegmentMetadata(segmentMetadata); Thread.sleep(100); } for (int i = 0; i < 10; ++i) { SegmentMetadata segmentMetadata = getTimeSegmentMetadataImpl(theDayAfterTomorrowSinceEpoch + "", theDayAfterTomorrowSinceEpoch + "", TimeUnit.DAYS.toString()); registerSegmentMetadata(segmentMetadata); Thread.sleep(100); } validate(); cleanupSegments(); }
From source file:com.atypon.wayf.guice.WayfGuiceModule.java
@Provides @Named("authenticatableCache") @Singleton/*from w w w . j ava2 s. com*/ public LoadingCache<AuthenticationCredentials, AuthenticatedEntity> getLoadingCache( @Named("authenticatableRedisDao") RedisDao<AuthenticationCredentials, AuthenticatedEntity> authenticatableRedisDao, AuthenticationFacade authenticationFacade, CacheManager cacheManager, @Named("authenticationCacheGroup") String authenticationCacheGroupName) { LoadingCacheRedisImpl<AuthenticationCredentials, AuthenticatedEntity> l2Cache = new LoadingCacheRedisImpl<>(); l2Cache.setRedisDao(authenticatableRedisDao); l2Cache.setCacheLoader((key) -> authenticationFacade.determineDao(key).authenticate(key)); l2Cache.setName("AUTHENTICATION_REDIS_CACHE"); LoadingCacheGuavaImpl<AuthenticationCredentials, AuthenticatedEntity> l1Cache = new LoadingCacheGuavaImpl<>(); l1Cache.setGuavaCache(CacheBuilder.newBuilder().expireAfterWrite(1, TimeUnit.DAYS).build()); l1Cache.setCacheLoader((key) -> l2Cache.get(key)); l2Cache.setName("AUTHENTICATION_GUAVA_CACHE"); cacheManager.registerCacheGroup(authenticationCacheGroupName, l1Cache, l2Cache); return l1Cache; }
From source file:org.deegree.tools.coverage.converter.RasterConverter.java
private void shutdownExecutorAndWaitForFinish(ExecutorService executor) throws InterruptedException { executor.shutdown();// w w w .j av a2 s .c om /** oh them tonny */ executor.awaitTermination(42, TimeUnit.DAYS); }
From source file:com.linkedin.pinot.core.indexsegment.generator.SegmentGeneratorConfig.java
public void loadConfigFiles() throws IOException { ObjectMapper objectMapper = new ObjectMapper(); Schema schema;//from w w w . j a va 2 s .c om if (_schemaFile != null) { schema = Schema.fromFile(new File(_schemaFile)); setSchema(schema); } else if (_format == FileFormat.AVRO) { schema = AvroUtils.extractSchemaFromAvro(new File(_inputFilePath)); setSchema(schema); } else { throw new RuntimeException("Input format " + _format + " requires schema."); } setTimeColumnName(schema.getTimeColumnName()); TimeFieldSpec timeFieldSpec = schema.getTimeFieldSpec(); if (timeFieldSpec != null) { setSegmentTimeUnit(timeFieldSpec.getIncomingGranularitySpec().getTimeType()); } else { setSegmentTimeUnit(TimeUnit.DAYS); } if (_readerConfigFile != null) { setReaderConfig(objectMapper.readValue(new File(_readerConfigFile), CSVRecordReaderConfig.class)); } if (_starTreeIndexSpecFile != null) { setStarTreeIndexSpec(objectMapper.readValue(new File(_starTreeIndexSpecFile), StarTreeIndexSpec.class)); } }
From source file:org.opendaylight.controller.cluster.raft.RaftActorTest.java
@Test public void testUpdateElectionTermPersistedWithPersistenceDisabled() throws Exception { new JavaTestKit(getSystem()) { {/*from w w w . j a v a 2 s .c o m*/ String persistenceId = factory.generateActorId("follower-"); DefaultConfigParamsImpl config = new DefaultConfigParamsImpl(); config.setHeartBeatInterval(new FiniteDuration(100, TimeUnit.MILLISECONDS)); config.setElectionTimeoutFactor(1); InMemoryJournal.addWriteMessagesCompleteLatch(persistenceId, 1); TestActorRef<MockRaftActor> ref = factory .createTestActor( MockRaftActor .props(persistenceId, ImmutableMap.<String, String>builder().put("member1", "address") .build(), config, new NonPersistentDataProvider()) .withDispatcher(Dispatchers.DefaultDispatcherId()), persistenceId); InMemoryJournal.waitForWriteMessagesComplete(persistenceId); List<UpdateElectionTerm> entries = InMemoryJournal.get(persistenceId, UpdateElectionTerm.class); assertEquals("UpdateElectionTerm entries", 1, entries.size()); UpdateElectionTerm updateEntry = entries.get(0); factory.killActor(ref, this); config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS)); ref = factory .createTestActor( MockRaftActor .props(persistenceId, ImmutableMap.<String, String>builder().put("member1", "address") .build(), config, new NonPersistentDataProvider()) .withDispatcher(Dispatchers.DefaultDispatcherId()), factory.generateActorId("follower-")); MockRaftActor actor = ref.underlyingActor(); actor.waitForRecoveryComplete(); RaftActorContext newContext = actor.getRaftActorContext(); assertEquals("electionTerm", updateEntry.getCurrentTerm(), newContext.getTermInformation().getCurrentTerm()); assertEquals("votedFor", updateEntry.getVotedFor(), newContext.getTermInformation().getVotedFor()); entries = InMemoryJournal.get(persistenceId, UpdateElectionTerm.class); assertEquals("UpdateElectionTerm entries", 1, entries.size()); } }; }
From source file:org.yccheok.jstock.engine.StockHistoryMonitor.java
public void stop() { ThreadPoolExecutor threadPoolExecutor = null; writerLock.lock();/*from w w w .j a v a 2s .c om*/ try { threadPoolExecutor = ((ThreadPoolExecutor) pool); final int nThreads = threadPoolExecutor.getMaximumPoolSize(); // Dangerous. Some users, do expect receive callback once they submit tasks into // monitor. However, if we are calling shutdownNow, user may not receive any // callback from those submitted tasks, which haven't started yet. Calling // shutdown() enables submitted tasks have chances to run once. // // threadPoolExecutor.shutdownNow(); threadPoolExecutor.shutdown(); threadPoolExecutor.purge(); // pool is not valid any more. Discard it and re-create. pool = Executors.newFixedThreadPool(nThreads); } finally { writerLock.unlock(); } // No unlock after awaitTermination, might cause deadlock. // How to wait for infinity? try { threadPoolExecutor.awaitTermination(100, TimeUnit.DAYS); } catch (InterruptedException exp) { log.error(null, exp); } }
From source file:org.apache.metron.dataloads.bulk.ElasticsearchDataPrunerTest.java
@Test public void testDeletesCorrectIndexes() throws Exception { //Mock Cluster Admin ClusterAdminClient clusterAdminClient = mock(ClusterAdminClient.class); ClusterStateRequestBuilder clusterStateRequestBuilder = mock(ClusterStateRequestBuilder.class); ClusterStateResponse clusterStateResponse = mock(ClusterStateResponse.class); ClusterState clusterState = mock(ClusterState.class); ObjectObjectHashMap<String, IndexMetaData> clusterIndexes = new ObjectObjectHashMap(); MetaData clusterMetadata = mock(MetaData.class); when(adminClient.cluster()).thenReturn(clusterAdminClient); when(clusterAdminClient.prepareState()).thenReturn(clusterStateRequestBuilder); when(clusterStateRequestBuilder.get()).thenReturn(clusterStateResponse); when(clusterStateResponse.getState()).thenReturn(clusterState); when(clusterState.getMetaData()).thenReturn(clusterMetadata); int numDays = 5; Date indexDate = new Date(); indexDate.setTime(testDate.getTime() - TimeUnit.DAYS.toMillis(numDays)); for (int i = 0; i < numDays * 24; i++) { String indexName = "sensor_index_" + dateFormat.format(indexDate); clusterIndexes.put(indexName, null); indexDate.setTime(indexDate.getTime() + TimeUnit.HOURS.toMillis(1)); }//from w w w. ja v a 2s . c om when(clusterMetadata.getIndices()).thenReturn(ImmutableOpenMap.copyOf(clusterIndexes)); EasyMock.expect(deleteIndexResponse.isAcknowledged()).andReturn(true); replayAll(); ElasticsearchDataPruner pruner = new ElasticsearchDataPruner(testDate, 1, configuration, indexClient, "sensor_index_"); pruner.indexClient = indexClient; Long deleteCount = pruner.prune(); assertEquals("Should have pruned 24 indices", 24L, deleteCount.longValue()); verifyAll(); }
From source file:org.dcache.util.histograms.HistogramModelTest.java
@Test public void updateShouldFailOnCountingHistogram() throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { givenCountingHistogram();/* ww w . j a va 2s .c o m*/ givenFilelifetimeValuesFor(150); givenBinCountOf(51); givenBinUnitOf((double) TimeUnit.DAYS.toMillis(1)); givenBinLabelOf(TimeUnit.DAYS.name()); givenDataLabelOf("Count"); givenDataLabelOf("COUNT"); givenHistogramTypeOf("File Lifetime Count"); whenConfigureIsCalled(); assertThatBuildSucceeded(); assertThatUpdateFails(); }
From source file:com.ibm.mil.readyapps.physio.fragments.ProgressFragment.java
private void fetchData(final TimeFilter filter) { fetchPainData(filter);//from ww w .jav a2s. co m Calendar calendar = Calendar.getInstance(); Date endDate = new Date(); calendar.setTime(endDate); TimeUnit unit; int interval; int bound; switch (filter) { case DAY: calendar.add(Calendar.DAY_OF_YEAR, -1); calendar.add(Calendar.HOUR, 1); unit = TimeUnit.HOURS; interval = 1; bound = DAY_BOUND; break; case WEEK: calendar.add(Calendar.WEEK_OF_YEAR, -1); unit = TimeUnit.DAYS; interval = 1; bound = WEEK_BOUND; break; case MONTH: calendar.add(Calendar.MONTH, -1); unit = TimeUnit.DAYS; interval = 7; bound = MONTH_BOUND; break; case YEAR: default: calendar.add(Calendar.YEAR, -1); calendar.add(Calendar.MONTH, 1); unit = TimeUnit.DAYS; interval = 30; bound = YEAR_BOUND; break; } Date startDate = calendar.getTime(); HealthDataRetriever.Builder builder = new HealthDataRetriever.Builder().startDate(startDate) .endDate(endDate).timeUnit(unit).timeInterval(interval); HealthDataRetriever stepsRetriever = builder.dataType(HealthDataRetriever.DataType.STEPS) .handler(new HealthDataRetriever.Handler() { @Override public void handle(List<Integer> data) { switch (filter) { case DAY: stepsDay = data; break; case WEEK: stepsWeek = data; break; case MONTH: stepsMonth = data; break; case YEAR: stepsYear = data; break; } verifyDataIntegrity(); } }).build(); stepsRetriever.retrieve(mClient); HealthDataRetriever heartRetriever = builder.dataType(HealthDataRetriever.DataType.HEART_RATE) .handler(new HealthDataRetriever.Handler() { @Override public void handle(List<Integer> data) { switch (filter) { case DAY: heartDay = data; break; case WEEK: heartWeek = data; break; case MONTH: heartMonth = data; break; case YEAR: heartYear = data; break; } verifyDataIntegrity(); } }).build(); heartRetriever.retrieve(mClient); HealthDataRetriever weightRetriever = builder.dataType(HealthDataRetriever.DataType.WEIGHT) .handler(new HealthDataRetriever.Handler() { @Override public void handle(List<Integer> data) { switch (filter) { case DAY: weightDay = data; break; case WEEK: weightWeek = data; break; case MONTH: weightMonth = data; break; case YEAR: weightYear = data; break; } verifyDataIntegrity(); } }).build(); weightRetriever.retrieve(mClient); calendar.setTime(endDate); int caloriesInterval = bound == DAY_BOUND ? Calendar.HOUR : Calendar.DAY_OF_YEAR; for (int i = 0; i < bound; i++) { endDate = calendar.getTime(); calendar.add(caloriesInterval, -interval); startDate = calendar.getTime(); HealthDataRetriever caloriesRetriever = builder.startDate(startDate).endDate(endDate) .dataType(HealthDataRetriever.DataType.CALORIES).handler(new HealthDataRetriever.Handler() { @Override public void handle(List<Integer> data) { int sum = 0; for (Integer datum : data) { sum += datum; } switch (filter) { case DAY: if (caloriesDay == null) { caloriesDay = new ArrayList<>(); } caloriesDay.add(0, sum); break; case WEEK: if (caloriesWeek == null) { caloriesWeek = new ArrayList<>(); } caloriesWeek.add(0, sum); break; case MONTH: if (caloriesMonth == null) { caloriesMonth = new ArrayList<>(); } caloriesMonth.add(0, sum); break; case YEAR: if (caloriesYear == null) { caloriesYear = new ArrayList<>(); } caloriesYear.add(0, sum); break; } verifyDataIntegrity(); } }).build(); caloriesRetriever.retrieve(mClient); } }