List of usage examples for java.util.concurrent TimeUnit MILLISECONDS
TimeUnit MILLISECONDS
To view the source code for java.util.concurrent TimeUnit MILLISECONDS.
Click Source Link
From source file:org.zalando.zmon.actuator.ZmonMetricsFilterTest.java
@Test public void test() throws InterruptedException { for (int i = 0; i < 100; i++) { restTemplate.getForObject("http://localhost:" + port + "/hello", String.class); TimeUnit.MILLISECONDS.sleep(random.nextInt(500)); }//from w w w. ja va 2s. c o m assertThat(metricRegistry.getTimers().get("zmon.response.200.GET.hello")).isNotNull(); assertThat(metricRegistry.getTimers().get("zmon.response.503.GET.hello")).isNotNull(); String metricsEndpointResponse = restTemplate.getForObject("http://localhost:" + port + "/metrics", String.class); logger.info(metricsEndpointResponse); }
From source file:com.epam.reportportal.apache.http.impl.execchain.TestConnectionHolder.java
@Test public void testAbortConnectionIOError() throws Exception { Mockito.doThrow(new IOException()).when(conn).shutdown(); connHolder.abortConnection();/*from ww w .j a va 2 s .c om*/ Assert.assertTrue(connHolder.isReleased()); Mockito.verify(conn).shutdown(); Mockito.verify(mgr).releaseConnection(conn, null, 0, TimeUnit.MILLISECONDS); }
From source file:com.watchrabbit.executor.spring.AnnotationDiscoverTest.java
@Test public void shouldCloseCircuit() throws Exception { try {/*w ww .j ava 2 s. c om*/ annotatedService.fastClose(() -> { throw new Exception(); }); failBecauseExceptionWasNotThrown(Exception.class); } catch (Exception ex) { } Sleep.untilTrue(Boolean.TRUE::booleanValue, 10, TimeUnit.MILLISECONDS); CountDownLatch latch = new CountDownLatch(1); annotatedService.fastClose(() -> { latch.countDown(); return "ok"; }); assertThat(latch.getCount()).isEqualTo(0); }
From source file:com.microsoft.azuretools.adauth.ResponseUtils.java
public static AuthenticationResult parseTokenResponse(TokenResponse tokenResponse) throws IOException { AuthenticationResult result;/* w ww . j a va2 s .c om*/ if (tokenResponse.accessToken != null) { long expiresOn = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()) + tokenResponse.expiresIn; result = new AuthenticationResult(tokenResponse.tokenType, tokenResponse.accessToken, tokenResponse.refreshToken, expiresOn); result.resource = tokenResponse.resource; IdToken idToken = parseIdToken(tokenResponse.idToken); if (idToken != null) { String tenantId = idToken.tenantId; String uniqueId = null; String displayableId = null; if (!StringUtils.isNullOrWhiteSpace(idToken.objectId)) { uniqueId = idToken.objectId; } else if (!StringUtils.isNullOrWhiteSpace(idToken.subject)) { uniqueId = idToken.subject; } if (!StringUtils.isNullOrWhiteSpace(idToken.upn)) { displayableId = idToken.upn; } else if (!StringUtils.isNullOrWhiteSpace(idToken.email)) { displayableId = idToken.email; } String givenName = idToken.givenName; String familyName = idToken.familyName; String identityProvider = (idToken.identityProvider == null) ? idToken.issuer : idToken.identityProvider; long passwordExpiresOffest = 0; if (idToken.passwordExpiration > 0) { passwordExpiresOffest = System.currentTimeMillis() + idToken.passwordExpiration; } URI changePasswordUri = null; if (!StringUtils.isNullOrEmpty(idToken.passwordChangeUrl)) { try { changePasswordUri = new URI(idToken.passwordChangeUrl); } catch (URISyntaxException ex) { ex.printStackTrace(); log.log(Level.SEVERE, "parseTokenResponse@ResponseUtils", ex); throw new IOException(ex); } } result.updateTenantAndUserInfo(tenantId, tokenResponse.idToken, new UserInfo(uniqueId, displayableId, givenName, familyName, identityProvider, passwordExpiresOffest, changePasswordUri)); } } else if (tokenResponse.error != null) { String message = tokenResponse.error + tokenResponse.errorDescription; log.log(Level.SEVERE, message); throw new AuthException(tokenResponse.error, tokenResponse.errorDescription); } else { String message = AuthError.Unknown + AuthErrorMessage.Unknown; log.log(Level.SEVERE, message); throw new AuthException(AuthError.Unknown, AuthErrorMessage.Unknown); } return result; }
From source file:io.mandrel.worker.Loop.java
@Override public void run() { while (true) { try {/*from w ww . j a v a 2 s . co m*/ if (!run.get()) { log.trace("Waiting..."); try { TimeUnit.MILLISECONDS.sleep(2000); } catch (InterruptedException e) { // Don't care log.trace("", e); } continue; } log.trace("> Asking for uri..."); Next next = clients.onRandomFrontier().map(frontier -> frontier.next(spider.getId())).get(20000, TimeUnit.MILLISECONDS); Uri uri = next.getUri(); if (uri != null) { log.trace("> Getting uri {} !", uri); // StopWatch watch = new StopWatch(); watch.start(); // Optional<Requester<? extends Strategy>> requester = Requesters.of(spider.getId(), uri.getScheme()); if (requester.isPresent()) { Requester<? extends Strategy> r = requester.get(); Blob blob = null; try { blob = processBlob(uri, watch, r); } catch (Exception t) { // TODO create and use internal exception instead... if (t instanceof ConnectTimeoutException) { spiderAccumulator.incConnectTimeout(); add(spider.getId(), uri); } else if (t instanceof ReadTimeoutException) { spiderAccumulator.incReadTimeout(); add(spider.getId(), uri); } else { log.debug("Error while looping", t); } } finally { barrier.passOrWait( blob != null && blob.getMetadata() != null ? blob.getMetadata().getSize() : null); } } else { // TODO Unknown protocol log.debug("Unknown protocol, can not find requester for '{}'", uri.getScheme()); } } else { log.trace("Frontier returned null Uri, waiting"); try { TimeUnit.MILLISECONDS.sleep(10000); } catch (InterruptedException e) { // Don't care log.trace("", e); } } } catch (RemoteException e) { switch (e.getError()) { case G_UNKNOWN: log.warn("Got a problem, waiting 2 sec...", e); try { TimeUnit.MILLISECONDS.sleep(2000); } catch (InterruptedException ie) { // Don't care log.trace("", ie); } } } catch (Exception e) { log.warn("Got a problem, waiting 2 sec...", e); try { TimeUnit.MILLISECONDS.sleep(2000); } catch (InterruptedException ie) { // Don't care log.trace("", ie); } } } }
From source file:com.couchbase.devex.ImportJsonToCouchbase.java
@Override public Observable<? extends Document> call(Document doc) { return asyncBucket.upsert(doc).timeout(importTimeout, TimeUnit.MILLISECONDS) .retryWhen(RetryBuilder.anyOf(RequestCancelledException.class) .delay(fixed(requestCancelledExceptionDelay, TimeUnit.MILLISECONDS)) .max(requestCancelledExceptionRetries).build()) .retryWhen(RetryBuilder.anyOf(TemporaryFailureException.class, BackpressureException.class) .delay(fixed(temporaryFailureExceptionDelay, TimeUnit.MILLISECONDS)) .max(temporaryFailureExceptionRetries).build()) .doOnError(t -> writeToErrorLog(doc.id())).doOnNext(jd -> writeToSuccessLog(doc.id())) .onErrorResumeNext(new Func1<Throwable, Observable<Document>>() { @Override/*from w ww . j a v a2s. c o m*/ public Observable<Document> call(Throwable throwable) { log.error(String.format("Could not import document ", doc.id())); log.error(throwable); return Observable.empty(); } }); }
From source file:com.amazonaws.mobileconnectors.pinpoint.internal.event.EventRecorder.java
public static EventRecorder newInstance(final PinpointContext pinpointContext, final PinpointDBUtil dbUtil) { final ExecutorService submissionRunnableQueue = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(MAX_EVENT_OPERATIONS), new ThreadPoolExecutor.DiscardPolicy()); return new EventRecorder(pinpointContext, dbUtil, submissionRunnableQueue); }
From source file:com.adaptris.core.fs.NonDeletingFsConsumerTest.java
public void testConsume() throws Exception { String subDir = new GuidGenerator().safeUUID(); MockMessageListener stub = new MockMessageListener(10); NonDeletingFsConsumer fs = createConsumer(subDir, "testConsume"); fs.setPoller(new FixedIntervalPoller(new TimeInterval(300L, TimeUnit.MILLISECONDS))); StandaloneConsumer sc = new StandaloneConsumer(fs); sc.registerAdaptrisMessageListener(stub); int count = 10; File parentDir = FsHelper// w w w .jav a 2 s. c o m .createFileReference(FsHelper.createUrlFromString(PROPERTIES.getProperty(BASE_KEY), true)); try { File baseDir = new File(parentDir, subDir); LifecycleHelper.init(sc); createFiles(baseDir, ".xml", count); LifecycleHelper.start(sc); waitForMessages(stub, count); assertMessages(stub.getMessages(), count, baseDir.listFiles((FilenameFilter) new Perl5FilenameFilter(".*\\.xml"))); } catch (Exception e) { log.warn(e.getMessage(), e); } finally { stop(sc); FileUtils.deleteQuietly(new File(parentDir, subDir)); } }
From source file:com.garethahealy.karaf.commands.ensemble.healthy.EnsembleHealthyAction.java
protected Boolean waitForEnsembleHealthy() throws InterruptedException { Boolean hasTimedOut = false;//from www . j a va 2 s . co m Long currentTime = System.nanoTime(); Long waitTimeout = currentTime + TimeUnit.MILLISECONDS.toNanos(wait); while (!hasTimedOut) { List<String> containersInEnsemble = clusterService.getEnsembleContainers(); //Sort them to be alphabetical Collections.sort(containersInEnsemble); Boolean isEqualList = ListUtils.isEqualList(containers, containersInEnsemble); if (isEqualList) { log.trace("MATCH: Expected: {}, Result: {}", StringUtils.join(containers, ','), StringUtils.join(containersInEnsemble, ',')); System.out.println( String.format(FORMAT, "Ensemble List: ", StringUtils.join(containersInEnsemble, ','))); System.out.println("Ensemble Healthy: success"); break; } else { log.trace("NON-MATCH: Expected: {}, Result: {}. Waiting...", StringUtils.join(containers, ','), StringUtils.join(containersInEnsemble, ',')); } currentTime = System.nanoTime(); if (currentTime > waitTimeout) { log.trace("Ensemble of {} took too long. Current time {}ns is greater than wait {}ns", StringUtils.join(containers, ','), currentTime, waitTimeout); hasTimedOut = true; break; } //Probably not the best way, but does its job TimeUnit.MILLISECONDS.sleep(tick); } return hasTimedOut; }
From source file:apiserver.services.pdf.ConvertHtmlToPdfGatewayTest.java
@Test public void convertHtmlToPdfGateway() { try {/*from ww w . j a va 2 s . c om*/ Html2PdfResult args = new Html2PdfResult(); args.setHtml("<b>Hello World</b>"); args.setFontEmbed(true); args.setMarginBottom(2); args.setMarginTop(2); args.setMarginLeft(2); args.setMarginRight(2); String[] permissions = new String[] { CFDocumentJob.Permission.AllowCopy.name(), CFDocumentJob.Permission.AllowPrinting.name(), CFDocumentJob.Permission.AllowScreenReaders.name() }; args.setPermissions(permissions); Future<Map> resultFuture = pdfHtmlGateway.convertHtmlToPdf(args); Object result = resultFuture.get(defaultTimeout, TimeUnit.MILLISECONDS); Assert.assertTrue(result != null); Assert.assertTrue(((Html2PdfResult) result).getResult().length > 10000); PdfTestBase.saveFileToLocalDisk("test-htmlToPdf2.pdf", ((Html2PdfResult) result).getResult()); } catch (Exception ex) { ex.printStackTrace(); Assert.fail(ex.getMessage()); } }