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.alley.android.ppi.app.OverviewFragment.java
@Override public Loader<Cursor> onCreateLoader(int id, Bundle bundle) { String sortOrder = PropertyContract.PropertyEntry.COLUMN_DATE + " DESC"; String locationSetting = Utility.getPreferredLocation(getActivity()); Uri propertyForLocationUri = null;/* w w w. j av a 2s . c o m*/ propertyForLocationUri = PropertyContract.PropertyEntry .buildPropertiesLocationWithStartDate(locationSetting, System.currentTimeMillis() - TimeUnit.DAYS.toMillis(Utility.getPreferredNumberOfDaysToKeep(this.getActivity()))); return new CursorLoader(getActivity(), propertyForLocationUri, PROPERTY_LIST_COLUMNS, null, null, sortOrder); }
From source file:org.kse.crypto.x509.X509CertificateGenerator.java
private X509Certificate generateVersion3(X500Name subject, X500Name issuer, Date validityStart, Date validityEnd, PublicKey publicKey, PrivateKey privateKey, SignatureType signatureType, BigInteger serialNumber, X509Extension extensions, Provider provider) throws CryptoException, CertIOException { Date notBefore = validityStart == null ? new Date() : validityStart; Date notAfter = validityEnd == null ? new Date(notBefore.getTime() + TimeUnit.DAYS.toMillis(365)) : validityEnd;/* w w w . j av a 2 s.com*/ JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(issuer, serialNumber, notBefore, notAfter, subject, publicKey); if (extensions != null) { for (String oid : extensions.getCriticalExtensionOIDs()) { certBuilder.addExtension(new ASN1ObjectIdentifier(oid), true, getExtensionValue(extensions, oid)); } for (String oid : extensions.getNonCriticalExtensionOIDs()) { certBuilder.addExtension(new ASN1ObjectIdentifier(oid), false, getExtensionValue(extensions, oid)); } } try { ContentSigner certSigner = null; if (provider == null) { certSigner = new JcaContentSignerBuilder(signatureType.jce()).build(privateKey); } else { certSigner = new JcaContentSignerBuilder(signatureType.jce()).setProvider(provider) .build(privateKey); } return new JcaX509CertificateConverter().setProvider("BC") .getCertificate(certBuilder.build(certSigner)); } catch (CertificateException ex) { throw new CryptoException(res.getString("CertificateGenFailed.exception.message"), ex); } catch (IllegalStateException ex) { throw new CryptoException(res.getString("CertificateGenFailed.exception.message"), ex); } catch (OperatorCreationException ex) { throw new CryptoException(res.getString("CertificateGenFailed.exception.message"), ex); } }
From source file:org.apache.pirk.querier.wideskies.encrypt.EncryptQuery.java
private SortedMap<Integer, BigInteger> parallelEncrypt(Map<Integer, Integer> selectorQueryVecMapping, int numThreads) throws InterruptedException, PIRException { // Encrypt and form the query vector ExecutorService es = Executors.newCachedThreadPool(); List<Future<SortedMap<Integer, BigInteger>>> futures = new ArrayList<>(numThreads); int numElements = 1 << queryInfo.getHashBitSize(); // 2^hashBitSize // Split the work across the requested number of threads int elementsPerThread = numElements / numThreads; for (int i = 0; i < numThreads; ++i) { // Grab the range for this thread int start = i * elementsPerThread; int stop = start + elementsPerThread - 1; if (i == numThreads - 1) { stop = numElements - 1;// www .ja v a 2 s . co m } // Create the runnable and execute EncryptQueryTask runEnc = new EncryptQueryTask(queryInfo.getDataPartitionBitSize(), paillier, selectorQueryVecMapping, start, stop); futures.add(es.submit(runEnc)); } // Pull all encrypted elements and add to resultMap SortedMap<Integer, BigInteger> queryElements = new TreeMap<>(); try { for (Future<SortedMap<Integer, BigInteger>> future : futures) { queryElements.putAll(future.get(1, TimeUnit.DAYS)); } } catch (TimeoutException | ExecutionException e) { throw new PIRException("Exception in encryption threads.", e); } es.shutdown(); return queryElements; }
From source file:com.lastsoft.plog.adapter.GameAdapter.java
@Override public void onBindViewHolder(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"); if (games.get(position).tbtCount >= 5) { viewHolder.getNickDimeView().setVisibility(View.VISIBLE); if (games.get(position).tbtCount >= 25) { viewHolder.getNickDimeView().setText("25"); } else if (games.get(position).tbtCount >= 10) { viewHolder.getNickDimeView().setText("10"); } else {/*from w ww . j a va2 s . c om*/ viewHolder.getNickDimeView().setText("5"); } } else { viewHolder.getNickDimeView().setVisibility(View.GONE); } viewHolder.getTextView().setText(games.get(position).gameName); if (games.get(position).gameThumb != null && !games.get(position).gameThumb.equals("")) { //Log.d("V1", "gameThumb = " + games.get(position).gameThumb); //ImageLoader.getInstance().displayImage("http:" + games.get(position).gameThumb, viewHolder.getImageView(), options); Picasso.with(mActivity).load("http:" + games.get(position).gameThumb).into(viewHolder.getImageView()); } else { viewHolder.getImageView().setImageDrawable(null); } if (games.get(position).recentPlay > 0) { Date theDate = new Date((long) games.get(position).recentPlay); long diff = new Date().getTime() - theDate.getTime(); long days = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS); String output_date2; if (days == 0) { output_date2 = mActivity.getString(R.string.less_than_a_day_ago); } else if (days == 1) { output_date2 = mActivity.getString(R.string.last_play_label) + days + mActivity.getString(R.string.day_ago_label); } else if (days <= 6) { output_date2 = mActivity.getString(R.string.last_play_label) + days + mActivity.getString(R.string.days_ago_label); } else { output_date2 = mActivity.getString(R.string.last_play_label) + outputFormatter.format(theDate); // Output : 01/20/2012 } viewHolder.getRecentPlayView().setText(output_date2); viewHolder.getRecentPlayView().setVisibility(View.VISIBLE); } else { viewHolder.getRecentPlayView().setVisibility(View.INVISIBLE); } if (games.get(position).taggedToPlay > 0 && playListType == 2) { Date theDate = new Date(((long) games.get(position).taggedToPlay) * 1000L); long diff = new Date().getTime() - theDate.getTime(); long days = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS); String output_date; if (days == 0) { output_date = mActivity.getString(R.string.added) + mActivity.getString(R.string.less_than_a_day_ago); } else if (days == 1) { output_date = mActivity.getString(R.string.added) + days + mActivity.getString(R.string.day_ago_label); } else if (days <= 6) { output_date = mActivity.getString(R.string.added) + days + mActivity.getString(R.string.days_ago_label); } else { output_date = mActivity.getString(R.string.added) + outputFormatter.format(theDate); // Output : 01/20/2012 } //String output_date = outputFormatter.format(theDate); // Output : 01/20/2012 viewHolder.getBucketDateView().setText(output_date); viewHolder.getBucketDateView().setVisibility(View.VISIBLE); } else { viewHolder.getBucketDateView().setVisibility(View.GONE); } if (playListType != 1) { viewHolder.getOverflowLayout().setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { playPopup(view, position); } }); if (games.get(position).expansionFlag == false) { viewHolder.getClickLayout().setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (SystemClock.elapsedRealtime() - mLastClickTime < 1000) { return; } mLastClickTime = SystemClock.elapsedRealtime(); ((MainActivity) mActivity).openAddPlay(mFragment, games.get(position).gameName, -1, false); } }); } else { viewHolder.getClickLayout().setOnClickListener(null); } } else { viewHolder.getOverflowLayout().setVisibility(View.GONE); } viewHolder.getGamePlaysView().setText(mActivity.getString(R.string.plays) + games.get(position).playCount); //} }
From source file:org.openmrs.module.openconceptlab.updater.Updater.java
private void processInput() throws IOException { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.getDeserializationConfig().setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")); JsonParser parser = objectMapper.getJsonFactory().createJsonParser(in); JsonToken token = parser.nextToken(); if (token != JsonToken.START_OBJECT) { throw new IOException("JSON must start from an object"); }// www. java 2 s . c o m token = parser.nextToken(); token = advanceToListOf("concepts", "mappings", parser); if (token == JsonToken.END_OBJECT || token == null) { return; } String baseUrl = updateService.getSubscription().getUrl(); if (baseUrl != null) { try { URI uri = new URI(baseUrl); baseUrl = uri.getScheme() + "://" + uri.getHost(); if (uri.getPort() != -1) { baseUrl += ":" + uri.getPort(); } } catch (Exception e) { throw new IllegalStateException(baseUrl + " is not valid", e); } } ThreadPoolExecutor runner = newRunner(); List<OclConcept> oclConcepts = new ArrayList<OclConcept>(); while (parser.nextToken() != JsonToken.END_ARRAY) { OclConcept oclConcept = parser.readValueAs(OclConcept.class); oclConcept.setVersionUrl(prependBaseUrl(baseUrl, oclConcept.getVersionUrl())); oclConcept.setUrl(prependBaseUrl(baseUrl, oclConcept.getUrl())); oclConcepts.add(oclConcept); if (oclConcepts.size() >= BATCH_SIZE) { ImportRunner importRunner = new ImportRunner(importer, new CacheService(conceptService), updateService, update); importRunner.setOclConcepts(oclConcepts); oclConcepts = new ArrayList<OclConcept>(); runner.execute(importRunner); } } if (oclConcepts.size() != 0) { ImportRunner importRunner = new ImportRunner(importer, new CacheService(conceptService), updateService, update); importRunner.setOclConcepts(oclConcepts); runner.execute(importRunner); } runner.shutdown(); try { runner.awaitTermination(32, TimeUnit.DAYS); } catch (InterruptedException e) { throw new RuntimeException(e); } token = advanceToListOf("mappings", null, parser); if (token == JsonToken.END_OBJECT) { return; } runner = newRunner(); List<OclMapping> oclMappings = new ArrayList<OclMapping>(); while (parser.nextToken() != JsonToken.END_ARRAY) { OclMapping oclMapping = parser.readValueAs(OclMapping.class); oclMapping.setUrl(prependBaseUrl(baseUrl, oclMapping.getUrl())); oclMapping.setFromConceptUrl(prependBaseUrl(baseUrl, oclMapping.getFromConceptUrl())); oclMapping.setFromSourceUrl(prependBaseUrl(baseUrl, oclMapping.getFromSourceUrl())); oclMapping.setToConceptUrl(prependBaseUrl(baseUrl, oclMapping.getToConceptUrl())); oclMappings.add(oclMapping); if (oclMappings.size() >= BATCH_SIZE) { ImportRunner importRunner = new ImportRunner(importer, new CacheService(conceptService), updateService, update); importRunner.setOclMappings(oclMappings); oclMappings = new ArrayList<OclMapping>(); runner.execute(importRunner); } } if (oclMappings.size() != 0) { ImportRunner importRunner = new ImportRunner(importer, new CacheService(conceptService), updateService, update); importRunner.setOclMappings(oclMappings); runner.execute(importRunner); } runner.shutdown(); try { runner.awaitTermination(32, TimeUnit.DAYS); } catch (InterruptedException e) { throw new RuntimeException(e); } }
From source file:name.persistent.behaviours.ValidatingDomainSupport.java
private boolean startResolving(Integer days) throws QueryEvaluationException { if (days == null || days < 1) return false; int count = Math.max(1, countTargets()); Resolver resolver = new Resolver(this); synchronized (resolvers) { if (resolvers.containsKey(resolver.key)) { resolver = resolvers.get(resolver.key); } else {/*from ww w . j a v a2 s.c o m*/ resolvers.put(resolver.key, resolver); } } int periods = (count + 99) / 100; // check 100 targets at a time long maxHours = TimeUnit.DAYS.toHours(days); int interval = Math.max(1, (int) maxHours / periods); resolver.schedule(interval, TimeUnit.HOURS, Math.max(100, count * 2)); return true; }
From source file:org.apache.cloudstack.quota.QuotaAlertManagerImpl.java
public static long getDifferenceDays(Date d1, Date d2) { long diff = d2.getTime() - d1.getTime(); return TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS); }
From source file:org.carbondata.processing.globalsurrogategenerator.LevelGlobalSurrogateGeneratorThread.java
private void createGlobalSurrogateKey(long currentTimeMillis, long currentTimeMillis1, boolean isPartitionColumn, String levelFileName, List<PartitionMemberVo> partitionMemberVoList, ExecutorService ex, int maxSeqenceKey) throws InterruptedException { int[] key = new int[partitionMemberVoList.get(0).getMembersMap().size()]; int[] value = new int[partitionMemberVoList.get(0).getMembersMap().size()]; int[] localKey = null; int[] localValue = null; int countVal = 0; int minSeqenceKey = Integer.MAX_VALUE; if (!isPartitionColumn) { for (Entry<String, Integer> entryInfo : partitionMemberVoList.get(0).getMembersMap().entrySet()) { if (minSeqenceKey > entryInfo.getValue()) { minSeqenceKey = entryInfo.getValue(); }/*from w ww.j a v a 2 s .c o m*/ key[countVal] = entryInfo.getValue(); value[countVal] = ++maxSeqenceKey; countVal++; } localKey = key; localValue = value; LOGGER.info("Time Taken to generate global surrogate for Level: " + levelFileName + " : " + (System.currentTimeMillis() - currentTimeMillis)); currentTimeMillis = System.currentTimeMillis(); ex.submit(new WriterThread(localKey, localValue, partitionMemberVoList.get(0).getPath(), levelFileName + ".globallevel", maxSeqenceKey, minSeqenceKey)); processNonPartitionedColumn(currentTimeMillis, levelFileName, partitionMemberVoList, ex, maxSeqenceKey); } else { for (int i = 0; i < partitionMemberVoList.size(); i++) { countVal = 0; minSeqenceKey = Integer.MAX_VALUE; key = new int[partitionMemberVoList.get(i).getMembersMap().size()]; value = new int[partitionMemberVoList.get(i).getMembersMap().size()]; for (Entry<String, Integer> entry : partitionMemberVoList.get(i).getMembersMap().entrySet()) { if (minSeqenceKey > entry.getValue()) { minSeqenceKey = entry.getValue(); } key[countVal] = entry.getValue(); value[countVal] = ++maxSeqenceKey; countVal++; } localKey = key; localValue = value; LOGGER.info("Time Taken to generate global surrogate for Level: " + levelFileName + " : " + (System.currentTimeMillis() - currentTimeMillis)); currentTimeMillis = System.currentTimeMillis(); ex.submit(new WriterThread(localKey, localValue, partitionMemberVoList.get(i).getPath(), levelFileName + ".globallevel", maxSeqenceKey, minSeqenceKey)); } } LOGGER.info("Time Taken to write global surrogate for Level: " + levelFileName + " : " + (System.currentTimeMillis() - currentTimeMillis1)); ex.shutdown(); ex.awaitTermination(1, TimeUnit.DAYS); }
From source file:com.linkedin.pinot.query.transform.TransformGroupByTest.java
/** * Helper method to build a segment with one dimension column containing values * from {@link #_dimensionValues}, and one metric column. * * Also builds the expected group by result as it builds the segments. * * @param segmentDirName Name of segment directory * @param segmentName Name of segment/*from w w w . ja v a2 s .com*/ * @param schema Schema for segment * @return Schema built for the segment * @throws Exception */ private RecordReader buildSegment(String segmentDirName, String segmentName, Schema schema) throws Exception { SegmentGeneratorConfig config = new SegmentGeneratorConfig(schema); config.setOutDir(segmentDirName); config.setFormat(FileFormat.AVRO); config.setTableName(TABLE_NAME); config.setSegmentName(segmentName); Random random = new Random(RANDOM_SEED); long currentTimeMillis = System.currentTimeMillis(); // Divide the day into fixed parts, and decrement time column value by this delta, so as to get // continuous days in the input. This gives about 10 days per 10k rows. long timeDelta = TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS) / 1000; final List<GenericRow> data = new ArrayList<>(); int numDimValues = _dimensionValues.length; for (int row = 0; row < NUM_ROWS; row++) { HashMap<String, Object> map = new HashMap<>(); map.put(DIMENSION_NAME, _dimensionValues[random.nextInt(numDimValues)]); map.put(METRIC_NAME, random.nextDouble()); map.put(TIME_COLUMN_NAME, currentTimeMillis); currentTimeMillis -= timeDelta; GenericRow genericRow = new GenericRow(); genericRow.init(map); data.add(genericRow); } SegmentIndexCreationDriverImpl driver = new SegmentIndexCreationDriverImpl(); RecordReader reader = new TestUtils.GenericRowRecordReader(schema, data); driver.init(config, reader); driver.build(); LOGGER.info("Built segment {} at {}", segmentName, segmentDirName); return reader; }
From source file:com.mapr.synth.SchemaSamplerTest.java
@Test public void testEvents() throws IOException, ParseException { SchemaSampler s = new SchemaSampler( Resources.asCharSource(Resources.getResource("schema012.json"), Charsets.UTF_8).read()); long t = System.currentTimeMillis(); SimpleDateFormat df0 = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat df2 = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); JsonNode old = s.sample();// ww w . j a v a 2 s.com long old1 = df0.parse(old.get("foo1").asText()).getTime(); assertTrue(Math.abs(old1 - t) < TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS)); long old2 = df1.parse(old.get("foo2").asText()).getTime(); assertEquals((double) old2, df1.parse("2014-01-01 00:00:00").getTime(), 10.0); long old3 = df2.parse(old.get("foo3").asText()).getTime(); assertEquals(old3, df1.parse("2014-02-01 00:00:00").getTime(), 10); double sum1 = 0; double sum2 = 0; double sum3 = 0; final int N = 10000; for (int k = 0; k < N; k++) { JsonNode r = s.sample(); long t1 = df0.parse(r.get("foo1").asText()).getTime(); sum1 += t1 - old1; old1 = t1; long t2 = df1.parse(r.get("foo2").asText()).getTime(); sum2 += t2 - old2; old2 = t2; long t3 = df2.parse(r.get("foo3").asText()).getTime(); sum3 += t3 - old3; old3 = t3; } assertEquals((double) TimeUnit.MILLISECONDS.convert(10, TimeUnit.DAYS), (sum1 / N), 0.03 * (sum1 / N)); assertEquals(100, sum2 / N, 3); assertEquals(2000, sum3 / N, 2000 * 0.03); }