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:org.jenkinsci.remoting.protocol.ProtocolStackLoopbackLoadStress.java
public ProtocolStackLoopbackLoadStress(boolean nio, boolean ssl) throws IOException, NoSuchAlgorithmException, CertificateException, KeyStoreException, UnrecoverableKeyException, KeyManagementException, OperatorCreationException { KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA"); gen.initialize(2048); // maximum supported by JVM with export restrictions keyPair = gen.generateKeyPair();//from w ww . j a v a 2 s . c o m Date now = new Date(); Date firstDate = new Date(now.getTime() + TimeUnit.DAYS.toMillis(10)); Date lastDate = new Date(now.getTime() + TimeUnit.DAYS.toMillis(-10)); SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo .getInstance(keyPair.getPublic().getEncoded()); X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE); X500Name subject = nameBuilder.addRDN(BCStyle.CN, getClass().getSimpleName()).addRDN(BCStyle.C, "US") .build(); X509v3CertificateBuilder certGen = new X509v3CertificateBuilder(subject, BigInteger.ONE, firstDate, lastDate, subject, subjectPublicKeyInfo); JcaX509ExtensionUtils instance = new JcaX509ExtensionUtils(); certGen.addExtension(X509Extension.subjectKeyIdentifier, false, instance.createSubjectKeyIdentifier(subjectPublicKeyInfo)); ContentSigner signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider(BOUNCY_CASTLE_PROVIDER) .build(keyPair.getPrivate()); certificate = new JcaX509CertificateConverter().setProvider(BOUNCY_CASTLE_PROVIDER) .getCertificate(certGen.build(signer)); char[] password = "password".toCharArray(); KeyStore store = KeyStore.getInstance("jks"); store.load(null, password); store.setKeyEntry("alias", keyPair.getPrivate(), password, new Certificate[] { certificate }); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(store, password); context = SSLContext.getInstance("TLS"); context.init(kmf.getKeyManagers(), new TrustManager[] { new PublicKeyMatchingX509ExtendedTrustManager(keyPair.getPublic()) }, null); hub = IOHub.create(executorService); serverSocketChannel = ServerSocketChannel.open(); acceptor = new Acceptor(serverSocketChannel, nio, ssl); }
From source file:de.metas.procurement.webui.service.impl.LoginRememberMeService.java
private void createRememberMeCookie(final User user) { try {//from w w w . ja v a 2 s. com final String rememberMeToken = createRememberMeToken(user); final Cookie rememberMeCookie = new Cookie(COOKIENAME_RememberMe, rememberMeToken); final int maxAge = (int) TimeUnit.SECONDS.convert(cookieMaxAgeDays, TimeUnit.DAYS); rememberMeCookie.setMaxAge(maxAge); final String path = "/"; // (VaadinService.getCurrentRequest().getContextPath()); rememberMeCookie.setPath(path); VaadinService.getCurrentResponse().addCookie(rememberMeCookie); logger.debug("Cookie added for {}: {} (maxAge={}, path={})", user, rememberMeToken, maxAge, path); } catch (final Exception e) { logger.warn("Failed creating cookie for user: {}. Skipped.", user, e); } }
From source file:com.mapr.synth.samplers.CommonPointOfCompromise.java
@Override public JsonNode sample() { ArrayNode r = nodeFactory.arrayNode(); double t = start; double averageInterval = TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS) / transactionsPerDay.nextDouble(); Exponential interval = new Exponential(1 / averageInterval, gen); Date date = new Date(); boolean compromised = false; while (t < end) { ObjectNode transaction = new ObjectNode(nodeFactory); t += interval.nextDouble();/*from w w w . j a v a2 s .c om*/ date.setTime((long) t); transaction.set("timestamp", new LongNode((long) (t / 1000))); transaction.set("date", new TextNode(df.format(date))); Integer merchantId = merchant.sample(); transaction.set("merchant", new IntNode(merchantId)); if (merchantId == 0 && t >= compromiseStart && t < compromiseEnd) { compromised = true; transaction.set("compromise", new IntNode(1)); } else { transaction.set("compromise", new IntNode(0)); } if (t > exploitEnd) { compromised = false; } double pFraud; if (t >= exploitStart && compromised) { pFraud = compromisedFraudRate; } else { pFraud = uncompromisedFraudRate; } transaction.set("fraud", new IntNode((gen.nextDouble() < pFraud) ? 1 : 0)); r.add(transaction); } return r; }
From source file:com.philliphsu.clock2.alarms.Alarm.java
public long ringsAt() { // Always with respect to the current date and time Calendar calendar = new GregorianCalendar(); calendar.set(Calendar.HOUR_OF_DAY, hour()); calendar.set(Calendar.MINUTE, minutes()); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); long baseRingTime = calendar.getTimeInMillis(); if (!hasRecurrence()) { if (baseRingTime <= System.currentTimeMillis()) { // The specified time has passed for today baseRingTime += TimeUnit.DAYS.toMillis(1); }// w w w. j av a 2s . c o m return baseRingTime; } else { // Compute the ring time just for the next closest recurring day. // Remember that day constants defined in the Calendar class are // not zero-based like ours, so we have to compensate with an offset // of magnitude one, with the appropriate sign based on the situation. int weekdayToday = calendar.get(Calendar.DAY_OF_WEEK); int numDaysFromToday = -1; for (int i = weekdayToday; i <= Calendar.SATURDAY; i++) { if (isRecurring(i - 1 /*match up with our day constant*/)) { if (i == weekdayToday) { if (baseRingTime > System.currentTimeMillis()) { // The normal ring time has not passed yet numDaysFromToday = 0; break; } } else { numDaysFromToday = i - weekdayToday; break; } } } // Not computed yet if (numDaysFromToday < 0) { for (int i = Calendar.SUNDAY; i < weekdayToday; i++) { if (isRecurring(i - 1 /*match up with our day constant*/)) { numDaysFromToday = Calendar.SATURDAY - weekdayToday + i; break; } } } // Still not computed yet. The only recurring day is weekdayToday, // and its normal ring time has already passed. if (numDaysFromToday < 0 && isRecurring(weekdayToday - 1) && baseRingTime <= System.currentTimeMillis()) { numDaysFromToday = 7; } if (numDaysFromToday < 0) throw new IllegalStateException("How did we get here?"); return baseRingTime + TimeUnit.DAYS.toMillis(numDaysFromToday); } }
From source file:com.linkedin.pinot.query.selection.SelectionOnlyQueriesForMultiValueColumnTest.java
private void setupSegment() throws Exception { if (_indexSegment != null) { return;//from ww w .java 2 s .co m } final String filePath = TestUtils .getFileFromResourceUrl(getClass().getClassLoader().getResource(AVRO_DATA)); if (INDEX_DIR.exists()) { FileUtils.deleteQuietly(INDEX_DIR); } final SegmentGeneratorConfig config = SegmentTestUtils.getSegmentGenSpecWithSchemAndProjectedColumns( new File(filePath), INDEX_DIR, "daysSinceEpoch", TimeUnit.DAYS, "test"); final SegmentIndexCreationDriver driver = SegmentCreationDriverFactory.get(null); driver.init(config); driver.build(); System.out.println("built at : " + INDEX_DIR.getAbsolutePath()); final File indexSegmentDir = new File(INDEX_DIR, driver.getSegmentName()); _indexSegment = ColumnarSegmentLoader.load(indexSegmentDir, ReadMode.heap); _medataMap = ((SegmentMetadataImpl) ((IndexSegmentImpl) _indexSegment).getSegmentMetadata()) .getColumnMetadataMap(); }
From source file:com.linkedin.pinot.query.executor.QueryExecutorTest.java
private void setupSegmentList(int numberOfSegments) throws Exception { final String filePath = TestUtils .getFileFromResourceUrl(getClass().getClassLoader().getResource(SMALL_AVRO_DATA)); _indexSegmentList.clear();// w w w. j av a 2 s . c o m if (INDEXES_DIR.exists()) { FileUtils.deleteQuietly(INDEXES_DIR); } INDEXES_DIR.mkdir(); for (int i = 0; i < numberOfSegments; ++i) { final File segmentDir = new File(INDEXES_DIR, "segment_" + i); final SegmentGeneratorConfig config = SegmentTestUtils.getSegmentGenSpecWithSchemAndProjectedColumns( new File(filePath), segmentDir, "dim" + i, TimeUnit.DAYS, "midas"); config.setSegmentNamePostfix(String.valueOf(i)); final SegmentIndexCreationDriver driver = SegmentCreationDriverFactory.get(null); driver.init(config); driver.build(); File parent = new File(INDEXES_DIR, "segment_" + String.valueOf(i)); String segmentName = parent.list()[0]; _indexSegmentList.add(ColumnarSegmentLoader.load(new File(parent, segmentName), ReadMode.mmap)); System.out.println("built at : " + segmentDir.getAbsolutePath()); } }
From source file:com.codebullets.sagalib.timeout.InMemoryTimeoutManagerTest.java
/** * <pre>/* w ww. j av a 2s . c o m*/ * Given => Timeout is added * When => timeout is canceled afterwards * Then => timeout is removed from schedule * </pre> */ @Test public void timeoutCanceled_timeoutHasBeenAdded_timeoutRemovedFromSchedule() { // given ScheduledFuture future = mock(ScheduledFuture.class); when(executor.schedule(any(Runnable.class), anyLong(), any(TimeUnit.class))).thenReturn(future); TimeoutId timeoutId = sut.requestTimeout(null, "", 1, TimeUnit.DAYS, null, null); // when sut.cancelTimeout(timeoutId); // then verify(future).cancel(false); }
From source file:org.dcache.util.histograms.HistogramModelTest.java
@Test public void binUnitShouldBe2ForMaxValue100Days() throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { givenCountingHistogram();//from www . j a v a2 s . c om givenFilelifetimeValuesFor(100); givenBinCountOf(51); givenBinUnitOf((double) TimeUnit.DAYS.toMillis(1)); givenBinLabelOf(TimeUnit.DAYS.name()); givenDataLabelOf("COUNT"); givenHistogramTypeOf("File Lifetime Count"); whenConfigureIsCalled(); assertThatBuildSucceeded(); assertThatBinWidthIs(2); }
From source file:com.linkedin.pinot.broker.routing.RoutingTableTest.java
@Test public void testTimeBoundaryRegression() throws Exception { final FakePropertyStore propertyStore = new FakePropertyStore(); final OfflineSegmentZKMetadata offlineSegmentZKMetadata = new OfflineSegmentZKMetadata(); offlineSegmentZKMetadata.setTimeUnit(TimeUnit.DAYS); offlineSegmentZKMetadata.setEndTime(1234L); propertyStore.setContents(/*from ww w.j a v a 2s . c om*/ ZKMetadataProvider.constructPropertyStorePathForSegment("myTable_OFFLINE", "someSegment_0"), offlineSegmentZKMetadata.toZNRecord()); final ExternalView offlineExternalView = new ExternalView("myTable_OFFLINE"); offlineExternalView.setState("someSegment_0", "Server_1.2.3.4_1234", "ONLINE"); final MutableBoolean timeBoundaryUpdated = new MutableBoolean(false); HelixExternalViewBasedRouting routingTable = new HelixExternalViewBasedRouting(propertyStore, null, new BaseConfiguration()) { @Override protected ExternalView fetchExternalView(String table) { return offlineExternalView; } @Override protected void updateTimeBoundary(String tableName, ExternalView externalView) { if (tableName.equals("myTable_OFFLINE")) { timeBoundaryUpdated.setValue(true); } } }; routingTable.setBrokerMetrics(new BrokerMetrics(new MetricsRegistry())); Assert.assertFalse(timeBoundaryUpdated.booleanValue()); final ArrayList<InstanceConfig> instanceConfigList = new ArrayList<>(); instanceConfigList.add(new InstanceConfig("Server_1.2.3.4_1234")); TableConfig myTableOfflineConfig = generateTableConfig("myTable_OFFLINE"); TableConfig myTableRealtimeConfig = generateTableConfig("myTable_REALTIME"); routingTable.markDataResourceOnline(myTableOfflineConfig, offlineExternalView, instanceConfigList); routingTable.markDataResourceOnline(myTableRealtimeConfig, new ExternalView("myTable_REALTIME"), new ArrayList<InstanceConfig>()); Assert.assertTrue(timeBoundaryUpdated.booleanValue()); }
From source file:org.dcache.util.histograms.CountingHistogramTest.java
@Test public void buildShouldFailWhenNoUnitGivenToCountingHistogram() throws Exception { givenCountingHistogram();/*from w w w . ja v a 2 s . co m*/ givenFilelifetimeValuesFor(150); givenBinCountOf(51); givenBinLabelOf(TimeUnit.DAYS.name()); givenDataLabelOf("COUNT"); givenHistogramTypeOf("File Lifetime Count"); whenConfigureIsCalled(); assertThatBuildFailed(); }