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.brightcove.player.samples.offlineplayback.VideoListAdapter.java
/** * Converts the given duration into a time span string. * * @param duration elapsed time as number of milliseconds. * @return the formatted time span string. *//* www. j ava 2 s . c o m*/ @NonNull public static String millisecondsToString(long duration) { final TimeUnit scale = TimeUnit.MILLISECONDS; StringBuilder builder = new StringBuilder(); long days = scale.toDays(duration); duration -= TimeUnit.DAYS.toMillis(days); if (days > 0) { builder.append(days); builder.append(days > 1 ? " days " : " day "); } long hours = scale.toHours(duration); duration -= TimeUnit.HOURS.toMillis(hours); if (hours > 0) { builder.append(String.format("%02d:", hours)); } long minutes = scale.toMinutes(duration); duration -= TimeUnit.MINUTES.toMillis(minutes); long seconds = scale.toSeconds(duration); builder.append(String.format("%02d:%02d", minutes, seconds)); return builder.toString(); }
From source file:de.lmu.ifi.dbs.jfeaturelib.utils.Extractor.java
/** * closes the thread pool and awaits termination *//*from ww w.j av a 2s. c om*/ private void closePool() { log.debug("close pool"); try { pool.shutdown(); pool.awaitTermination(TERMINATION_TIMEOUT, TimeUnit.DAYS); } catch (InterruptedException ex) { log.warn(ex.getMessage(), ex); throw new IllegalStateException("error while shutting down pool"); } }
From source file:org.opendaylight.controller.cluster.raft.RaftActorTest.java
@Test public void testApplyJournalEntriesCallsDataPersistence() throws Exception { new JavaTestKit(getSystem()) { {/*from w w w. j a v a2 s.co m*/ String persistenceId = factory.generateActorId("leader-"); DefaultConfigParamsImpl config = new DefaultConfigParamsImpl(); config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS)); DataPersistenceProvider dataPersistenceProvider = mock(DataPersistenceProvider.class); TestActorRef<MockRaftActor> mockActorRef = factory .createTestActor(MockRaftActor.props(persistenceId, Collections.<String, String>emptyMap(), config, dataPersistenceProvider), persistenceId); MockRaftActor mockRaftActor = mockActorRef.underlyingActor(); mockRaftActor.waitForInitializeBehaviorComplete(); mockRaftActor.waitUntilLeader(); mockRaftActor.onReceiveCommand(new ApplyJournalEntries(10)); verify(dataPersistenceProvider).persist(any(ApplyJournalEntries.class), any(Procedure.class)); } }; }
From source file:org.apache.nifi.registry.security.util.CertificateUtils.java
/** * Generates a self-signed {@link X509Certificate} suitable for use as a Certificate Authority. * * @param keyPair the {@link KeyPair} to generate the {@link X509Certificate} for * @param dn the distinguished name to user for the {@link X509Certificate} * @param signingAlgorithm the signing algorithm to use for the {@link X509Certificate} * @param certificateDurationDays the duration in days for which the {@link X509Certificate} should be valid * @return a self-signed {@link X509Certificate} suitable for use as a Certificate Authority * @throws CertificateException if there is an generating the new certificate *//*from w w w .j a va 2 s . c o m*/ public static X509Certificate generateSelfSignedX509Certificate(KeyPair keyPair, String dn, String signingAlgorithm, int certificateDurationDays) throws CertificateException { try { ContentSigner sigGen = new JcaContentSignerBuilder(signingAlgorithm) .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(keyPair.getPrivate()); SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()); Date startDate = new Date(); Date endDate = new Date(startDate.getTime() + TimeUnit.DAYS.toMillis(certificateDurationDays)); X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(reverseX500Name(new X500Name(dn)), getUniqueSerialNumber(), startDate, endDate, reverseX500Name(new X500Name(dn)), subPubKeyInfo); // Set certificate extensions // (1) digitalSignature extension certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.keyAgreement | KeyUsage.nonRepudiation | KeyUsage.cRLSign | KeyUsage.keyCertSign)); certBuilder.addExtension(Extension.basicConstraints, false, new BasicConstraints(true)); certBuilder.addExtension(Extension.subjectKeyIdentifier, false, new JcaX509ExtensionUtils().createSubjectKeyIdentifier(keyPair.getPublic())); certBuilder.addExtension(Extension.authorityKeyIdentifier, false, new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(keyPair.getPublic())); // (2) extendedKeyUsage extension certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage( new KeyPurposeId[] { KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth })); // Sign the certificate X509CertificateHolder certificateHolder = certBuilder.build(sigGen); return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME) .getCertificate(certificateHolder); } catch (CertIOException | NoSuchAlgorithmException | OperatorCreationException e) { throw new CertificateException(e); } }
From source file:org.opendaylight.controller.cluster.raft.RaftActorTest.java
@Test public void testApplyState() throws Exception { new JavaTestKit(getSystem()) { {//from w w w . j av a2 s . co m String persistenceId = factory.generateActorId("leader-"); DefaultConfigParamsImpl config = new DefaultConfigParamsImpl(); config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS)); DataPersistenceProvider dataPersistenceProvider = mock(DataPersistenceProvider.class); TestActorRef<MockRaftActor> mockActorRef = factory .createTestActor(MockRaftActor.props(persistenceId, Collections.<String, String>emptyMap(), config, dataPersistenceProvider), persistenceId); MockRaftActor mockRaftActor = mockActorRef.underlyingActor(); mockRaftActor.waitForInitializeBehaviorComplete(); ReplicatedLogEntry entry = new MockRaftActorContext.MockReplicatedLogEntry(1, 5, new MockRaftActorContext.MockPayload("F")); final Identifier id = new MockIdentifier("apply-state"); mockRaftActor.onReceiveCommand(new ApplyState(mockActorRef, id, entry)); verify(mockRaftActor.actorDelegate).applyState(eq(mockActorRef), eq(id), anyObject()); } }; }
From source file:de.yaacc.upnp.server.contentdirectory.YaaccContentDirectory.java
public String formatDuration(String millisStr) { String res = ""; long duration = Long.valueOf(millisStr); long hours = TimeUnit.MILLISECONDS.toHours(duration) - TimeUnit.DAYS.toHours(TimeUnit.MILLISECONDS.toDays(duration)); long minutes = TimeUnit.MILLISECONDS.toMinutes(duration) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(duration)); long seconds = TimeUnit.MILLISECONDS.toSeconds(duration) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(duration)); res = String.format(Locale.US, "%02d:%02d:%02d", hours, minutes, seconds); return res;/* ww w. j a v a 2s .co m*/ // Date d = new Date(Long.parseLong(millis)); // SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss"); // return df.format(d); }
From source file:org.codice.alliance.nsili.client.SampleNsiliClient.java
public void testStandingQueryMgr() throws Exception { if (standingQueryMgr != null) { LOGGER.info("----------------------"); LOGGER.info("Standing Query Manager Test"); Event[] events = standingQueryMgr.get_event_descriptions(); if (events != null) { Arrays.stream(events).forEach(event -> LOGGER.info("Event: {}\n Name: {}\n Desc: {}", event.event_type.value(), event.event_name, event.event_description)); }/*from w ww . ja v a 2 s .com*/ LifeEvent start = new LifeEvent(); java.util.Date startDate = new java.util.Date(); start.at(ResultDAGConverter.getAbsTime(startDate)); LifeEvent end = new LifeEvent(); final long ONE_YEAR_IN_MS = TimeUnit.DAYS.toMillis(365); long endTime = System.currentTimeMillis() + ONE_YEAR_IN_MS; java.util.Date endDate = new java.util.Date(); endDate.setTime(endTime); end.at(ResultDAGConverter.getAbsTime(endDate)); LifeEvent[] frequency = new LifeEvent[1]; LifeEvent freqOne = new LifeEvent(); Time time = new Time((short) 0, (short) 0, 30.0f); freqOne.rt(time); frequency[0] = freqOne; QueryLifeSpan queryLifeSpan = new QueryLifeSpan(start, end, frequency); NameValue[] props = new NameValue[0]; String callbackId = UUID.randomUUID().toString(); try { standingQueryRequest = standingQueryMgr.submit_standing_query(STANDING_ALL_QUERY, getResultAttributes(), getSortableAttributes(), queryLifeSpan, props); standingQueryRequest.set_user_info(ALLIANCE); standingQueryRequest.set_number_of_hits(200); TestNsiliStandingQueryCallback nsiliCallback = new TestNsiliStandingQueryCallback( standingQueryRequest); final String ENCODING = "ISO-8859-1"; try { poa.activate_object_with_id(callbackId.getBytes(Charset.forName(ENCODING)), nsiliCallback); } catch (ServantAlreadyActive | ObjectAlreadyActive | WrongPolicy e) { LOGGER.error("Order : Unable to activate callback object, already active : {}", NsilCorbaExceptionUtil.getExceptionDetails(e), e); } org.omg.CORBA.Object obj = poa.create_reference_with_id( callbackId.getBytes(Charset.forName(ENCODING)), CallbackHelper.id()); Callback callback = CallbackHelper.narrow(obj); String standingQueryCallbackId = standingQueryRequest.register_callback(callback); nsiliCallback.setCallbackID(standingQueryCallbackId); standingQueryCallbacks.add(nsiliCallback); LOGGER.info("Registered NSILI Callback: {}", standingQueryCallbackId); LOGGER.info("Standing Query Submitted"); } catch (Exception e) { LOGGER.debug("Error submitting standing query: ", NsilCorbaExceptionUtil.getExceptionDetails(e)); throw (e); } } else { LOGGER.info("StandingQueryMgr is not initialized, unable to test"); } }
From source file:io.druid.segment.realtime.appenderator.AppenderatorImpl.java
@Override public void close() { log.info("Shutting down..."); final List<ListenableFuture<?>> futures = Lists.newArrayList(); for (Map.Entry<SegmentIdentifier, Sink> entry : sinks.entrySet()) { futures.add(abandonSegment(entry.getKey(), entry.getValue(), false)); }/* w w w . j ava2s .co m*/ try { Futures.allAsList(futures).get(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); log.warn(e, "Interrupted during close()"); } catch (ExecutionException e) { log.warn(e, "Unable to abandon existing segments during close()"); } try { shutdownExecutors(); Preconditions.checkState(persistExecutor.awaitTermination(365, TimeUnit.DAYS), "persistExecutor not terminated"); Preconditions.checkState(pushExecutor.awaitTermination(365, TimeUnit.DAYS), "pushExecutor not terminated"); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new ISE("Failed to shutdown executors during close()"); } // Only unlock if executors actually shut down. unlockBasePersistDirectory(); }
From source file:org.apache.nifi.registry.security.util.CertificateUtils.java
/** * Generates an issued {@link X509Certificate} from the given issuer certificate and {@link KeyPair} * * @param dn the distinguished name to use * @param publicKey the public key to issue the certificate to * @param extensions extensions extracted from the CSR * @param issuer the issuer's certificate * @param issuerKeyPair the issuer's keypair * @param signingAlgorithm the signing algorithm to use * @param days the number of days it should be valid for * @return an issued {@link X509Certificate} from the given issuer certificate and {@link KeyPair} * @throws CertificateException if there is an error issuing the certificate *//*from w w w.j a v a2 s . co m*/ public static X509Certificate generateIssuedCertificate(String dn, PublicKey publicKey, Extensions extensions, X509Certificate issuer, KeyPair issuerKeyPair, String signingAlgorithm, int days) throws CertificateException { try { ContentSigner sigGen = new JcaContentSignerBuilder(signingAlgorithm) .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(issuerKeyPair.getPrivate()); SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded()); Date startDate = new Date(); Date endDate = new Date(startDate.getTime() + TimeUnit.DAYS.toMillis(days)); X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder( reverseX500Name(new X500Name(issuer.getSubjectX500Principal().getName())), getUniqueSerialNumber(), startDate, endDate, reverseX500Name(new X500Name(dn)), subPubKeyInfo); certBuilder.addExtension(Extension.subjectKeyIdentifier, false, new JcaX509ExtensionUtils().createSubjectKeyIdentifier(publicKey)); certBuilder.addExtension(Extension.authorityKeyIdentifier, false, new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(issuerKeyPair.getPublic())); // Set certificate extensions // (1) digitalSignature extension certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.keyAgreement | KeyUsage.nonRepudiation)); certBuilder.addExtension(Extension.basicConstraints, false, new BasicConstraints(false)); // (2) extendedKeyUsage extension certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage( new KeyPurposeId[] { KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth })); // (3) subjectAlternativeName if (extensions != null && extensions.getExtension(Extension.subjectAlternativeName) != null) { certBuilder.addExtension(Extension.subjectAlternativeName, false, extensions.getExtensionParsedValue(Extension.subjectAlternativeName)); } X509CertificateHolder certificateHolder = certBuilder.build(sigGen); return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME) .getCertificate(certificateHolder); } catch (CertIOException | NoSuchAlgorithmException | OperatorCreationException e) { throw new CertificateException(e); } }
From source file:org.structr.rest.resource.LogResource.java
/** * This method takes a date format and finds the time interval that it * represents./*from w w w . ja v a2 s.c o m*/ */ private long findInterval(final String dateFormat) { final long max = TimeUnit.DAYS.toMillis(365); final long step = TimeUnit.SECONDS.toMillis(60); try { final SimpleDateFormat format = new SimpleDateFormat(dateFormat); final long initial = format.parse(format.format(3600)).getTime(); for (long i = initial; i < max; i += step) { final long current = format.parse(format.format(i)).getTime(); if (initial != current) { return i - initial; } } return max; } catch (ParseException pex) { pex.printStackTrace(); } return max; }