List of usage examples for java.util.concurrent TimeUnit NANOSECONDS
TimeUnit NANOSECONDS
To view the source code for java.util.concurrent TimeUnit NANOSECONDS.
Click Source Link
From source file:com.netflix.genie.web.security.saml.SAMLUserDetailsServiceImplUnitTests.java
/** * Make sure if no username is found an exception is thrown. *///from w w w.j av a 2s.co m @Test(expected = UsernameNotFoundException.class) public void doesThrowErrorOnUserIdNotFound() { final SAMLCredential credential = Mockito.mock(SAMLCredential.class); Mockito.when(credential.getAttributeAsString(Mockito.eq(USER_ATTRIBUTE_NAME))).thenReturn(null); this.service.loadUserBySAML(credential); Mockito.verify(this.loadAuthenticationTimer, Mockito.times(1)).record(Mockito.anyLong(), Mockito.eq(TimeUnit.NANOSECONDS)); }
From source file:org.apache.mnemonic.bench.Sort.java
static void reportElapse(String msg, long t1, long t2) { LOGGER.info("{} : {} ms.", msg, TimeUnit.NANOSECONDS.toMillis(t2 - t1)); }
From source file:org.apache.camel.component.javaspace.JavaSpaceConsumer.java
protected void doStart() throws Exception { // TODO: There should be a switch to enable/disable using this security hack Utility.setSecurityPolicy("policy.all", "policy_consumer.all"); int verb = TAKE; if (this.verb.equalsIgnoreCase("read")) { verb = READ;//from ww w. jav a2s.c o m } javaSpace = JiniSpaceAccessor.findSpace(((JavaSpaceEndpoint) this.getEndpoint()).getRemaining(), ((JavaSpaceEndpoint) this.getEndpoint()).getSpaceName()); if (transactional) { transactionHelper = TransactionHelper .getInstance(((JavaSpaceEndpoint) this.getEndpoint()).getRemaining()); } for (int i = 0; i < concurrentConsumers; ++i) { Task worker = new Task((JavaSpaceEndpoint) this.getEndpoint(), this.getProcessor(), javaSpace, transactionHelper, transactionTimeout, verb, templateId); executor.scheduleWithFixedDelay(worker, 0, 1, TimeUnit.NANOSECONDS); } (new File("policy_consumer.all")).delete(); }
From source file:biospectra.classify.server.ClassifierServer.java
@Override public void close() throws IOException { try {//from w ww . j a v a 2s.co m this.executor.shutdown(); this.executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); } catch (InterruptedException ex) { LOG.error("executor service is interrupted", ex); } this.receiver.close(); this.searcher.close(); }
From source file:com.continuuity.weave.kafka.client.KafkaTest.java
@Test public void testKafkaClient() throws Exception { String topic = "testClient"; Thread t1 = createPublishThread(kafkaClient, topic, Compression.GZIP, "GZIP Testing message", 10); Thread t2 = createPublishThread(kafkaClient, topic, Compression.NONE, "Testing message", 10); t1.start();/*from w ww. j a v a 2 s . c o m*/ t2.start(); Thread t3 = createPublishThread(kafkaClient, topic, Compression.SNAPPY, "Snappy Testing message", 10); t2.join(); t3.start(); Iterator<FetchedMessage> consumer = kafkaClient.consume(topic, 0, 0, 1048576); int count = 0; long startTime = System.nanoTime(); while (count < 30 && consumer.hasNext() && secondsPassed(startTime, TimeUnit.NANOSECONDS) < 5) { LOG.info(Charsets.UTF_8.decode(consumer.next().getBuffer()).toString()); count++; } Assert.assertEquals(30, count); }
From source file:biospectra.classify.LocalClassifier.java
public void classify(File inputFasta, File classifyOutput, File summaryOutput) throws Exception { if (inputFasta == null) { throw new IllegalArgumentException("inputFasta is null"); }/*from w w w. j a v a 2 s . c om*/ if (classifyOutput == null) { throw new IllegalArgumentException("classifyOutput is null"); } if (!classifyOutput.getParentFile().exists()) { classifyOutput.getParentFile().mkdirs(); } if (summaryOutput != null) { if (!summaryOutput.getParentFile().exists()) { summaryOutput.getParentFile().mkdirs(); } } FASTAReader reader = FastaFileReader.getFASTAReader(inputFasta); FASTAEntry read = null; FileWriter fw = new FileWriter(classifyOutput, false); final BufferedWriter bw = new BufferedWriter(fw, 1024 * 1024); final ClassificationResultSummary summary = new ClassificationResultSummary(); summary.setQueryFilename(inputFasta.getName()); summary.setStartTime(new Date()); int threads = this.conf.getWorkerThreads(); BlockingExecutor executor = new BlockingExecutor(threads, threads * 2); while ((read = reader.readNext()) != null) { final String sequence = read.getSequence(); final String header = read.getHeaderLine(); Runnable worker = new Runnable() { @Override public void run() { try { ClassificationResult result = classifier.classify(header, sequence); JsonSerializer serializer = new JsonSerializer(); String json = serializer.toJson(result); synchronized (summary) { summary.report(result); } synchronized (bw) { bw.write(json + "\n"); } } catch (Exception ex) { LOG.error("Exception occurred during search", ex); } } }; executor.execute(worker); } executor.shutdown(); executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); bw.close(); reader.close(); summary.setEndTime(new Date()); LOG.info("classifying " + summary.getQueryFilename() + " finished in " + summary.getTimeTaken() + " millisec"); if (summaryOutput != null) { summary.saveTo(summaryOutput); } }
From source file:org.apache.hadoop.hbase.client.AsyncRpcRetryingCaller.java
protected void onError(Throwable error, Supplier<String> errMsg, Consumer<Throwable> updateCachedLocation) { error = translateException(error);/*w w w. ja v a2 s . c om*/ if (tries > startLogErrorsCnt) { LOG.warn(errMsg.get() + ", tries = " + tries + ", maxAttempts = " + maxAttempts + ", timeout = " + TimeUnit.NANOSECONDS.toMillis(operationTimeoutNs) + " ms, time elapsed = " + elapsedMs() + " ms", error); } RetriesExhaustedException.ThrowableWithExtraContext qt = new RetriesExhaustedException.ThrowableWithExtraContext( error, EnvironmentEdgeManager.currentTime(), ""); exceptions.add(qt); if (error instanceof DoNotRetryIOException || tries >= maxAttempts) { completeExceptionally(); return; } long delayNs; if (operationTimeoutNs > 0) { long maxDelayNs = remainingTimeNs() - SLEEP_DELTA_NS; if (maxDelayNs <= 0) { completeExceptionally(); return; } delayNs = Math.min(maxDelayNs, getPauseTime(pauseNs, tries - 1)); } else { delayNs = getPauseTime(pauseNs, tries - 1); } updateCachedLocation.accept(error); tries++; retryTimer.newTimeout(t -> doCall(), delayNs, TimeUnit.NANOSECONDS); }
From source file:io.micrometer.spring.scheduling.ScheduledMethodMetrics.java
private Object recordThrowable(Timer timer, ThrowableCallable f) throws Throwable { long start = registry.config().clock().monotonicTime(); try {/*from ww w.java2s . c om*/ return f.call(); } finally { timer.record(registry.config().clock().monotonicTime() - start, TimeUnit.NANOSECONDS); } }
From source file:com.netflix.genie.web.security.oauth2.pingfederate.PingFederateJWTTokenServicesUnitTests.java
/** * Make sure we can successfully load an authentication. * * @throws AuthenticationException On error * @throws InvalidTokenException When the token is invalid * @throws InvalidJwtException On invalid JWT token * @throws MalformedClaimException A bad claim *//*from www . j a v a 2 s .c o m*/ @Test public void canLoadAuthentication() throws AuthenticationException, InvalidTokenException, InvalidJwtException, MalformedClaimException { final JwtClaims claims = Mockito.mock(JwtClaims.class); final String clientId = UUID.randomUUID().toString(); final String scope1 = "genie_admin"; final String scope2 = UUID.randomUUID().toString(); final Set<String> scopes = Sets.newHashSet(scope1, scope2); Mockito.when(claims.getClaimValue("client_id", String.class)).thenReturn(clientId); Mockito.when(claims.getClaimValue("scope", Collection.class)).thenReturn(scopes); Mockito.when(this.jwtConsumer.processToClaims(Mockito.anyString())).thenReturn(claims); final OAuth2Authentication authentication = this.tokenServices .loadAuthentication(UUID.randomUUID().toString()); Assert.assertNull(authentication.getUserAuthentication()); Assert.assertThat(authentication.getPrincipal(), Matchers.is(clientId)); final Collection<GrantedAuthority> authorities = authentication.getAuthorities(); Assert.assertThat(authorities.size(), Matchers.is(3)); Assert.assertTrue(authorities.containsAll(Sets.newHashSet(new SimpleGrantedAuthority("ROLE_ADMIN"), new SimpleGrantedAuthority("ROLE_" + scope2.toUpperCase()), new SimpleGrantedAuthority("ROLE_USER")))); Mockito.verify(this.loadAuthenticationTimer, Mockito.times(1)).record(Mockito.anyLong(), Mockito.eq(TimeUnit.NANOSECONDS)); }
From source file:com.twosigma.beakerx.kernel.magic.command.functionality.TimeMagicCommand.java
private String format(Long nanoSeconds) { if (nanoSeconds < 1000) { //leave in ns return nanoSeconds + " ns"; } else if (nanoSeconds >= 1000 && nanoSeconds < 1_000_000) { //convert to s return TimeUnit.NANOSECONDS.toMicros(nanoSeconds) + " s"; } else if (nanoSeconds > 1_000_000 && nanoSeconds < 1_000_000_000) { //convert to ms return TimeUnit.NANOSECONDS.toMillis(nanoSeconds) + " ms"; } else {/* w w w . ja v a 2s . co m*/ //convert to s return TimeUnit.NANOSECONDS.toSeconds(nanoSeconds) + " s"; } }