Example usage for java.util.concurrent TimeUnit MILLISECONDS

List of usage examples for java.util.concurrent TimeUnit MILLISECONDS

Introduction

In this page you can find the example usage for java.util.concurrent TimeUnit MILLISECONDS.

Prototype

TimeUnit MILLISECONDS

To view the source code for java.util.concurrent TimeUnit MILLISECONDS.

Click Source Link

Document

Time unit representing one thousandth of a second.

Usage

From source file:com.bia.gmailjava.EmailService.java

/**
 *
 * @param toAddress/*from w  ww . ja v  a 2s.c o  m*/
 * @param subject
 * @param body
 * @return true email send, false invalid input
 */
public boolean sendEmail(String toAddress, String subject, String body) {
    if (!isValidEmail(toAddress) || !isValidSubject(subject)) {
        return false;
    }

    String[] to = { toAddress };
    // Aysnc send email
    Runnable emailServiceAsync = new EmailServiceAsync(to, subject, body);
    this.executor.schedule(emailServiceAsync, 1, TimeUnit.MILLISECONDS);

    return true;
}

From source file:com.twitter.distributedlog.client.proxy.TestProxyClientManager.java

private static ProxyClientManager createProxyClientManager(ProxyClient.Builder builder,
        HostProvider hostProvider, long periodicHandshakeIntervalMs) {
    ClientConfig clientConfig = new ClientConfig();
    clientConfig.setPeriodicHandshakeIntervalMs(periodicHandshakeIntervalMs);
    clientConfig.setPeriodicOwnershipSyncIntervalMs(-1);
    HashedWheelTimer dlTimer = new HashedWheelTimer(
            new ThreadFactoryBuilder().setNameFormat("TestProxyClientManager-timer-%d").build(),
            clientConfig.getRedirectBackoffStartMs(), TimeUnit.MILLISECONDS);
    return new ProxyClientManager(clientConfig, builder, dlTimer, hostProvider,
            new ClientStats(NullStatsReceiver.get(), false, new DefaultRegionResolver()));
}

From source file:com.googlecode.ehcache.annotations.integration.PartialCacheKeyTest.java

@Test
public void testSharedPartialKeyGeneration() {
    assertEquals(0, this.partialCacheKeyTestInterface.cacheableMethodOneCount());

    this.partialCacheKeyTestInterface.cacheableMethodOne("b", 1, 12, TimeUnit.MILLISECONDS);
    assertEquals(1, this.partialCacheKeyTestInterface.cacheableMethodOneCount());

    assertEquals(0, this.partialCacheKeyTestInterface.cacheableMethodThreeCount());

    this.partialCacheKeyTestInterface.cacheableMethodThree("b", 1, 12);
    assertEquals(0, this.partialCacheKeyTestInterface.cacheableMethodThreeCount());

    this.partialCacheKeyTestInterface.cacheableMethodThree("c", 1, 12);
    assertEquals(1, this.partialCacheKeyTestInterface.cacheableMethodThreeCount());

    this.partialCacheKeyTestInterface.cacheableMethodThree("c", 1, 12);
    assertEquals(1, this.partialCacheKeyTestInterface.cacheableMethodThreeCount());

    assertEquals(0, this.partialCacheKeyTestInterface.cacheableMethodTwoCount());

    this.partialCacheKeyTestInterface.cacheableMethodTwo(1, 12);
    assertEquals(1, this.partialCacheKeyTestInterface.cacheableMethodTwoCount());

    this.partialCacheKeyTestInterface.cacheableMethodTwo(1, 12);
    assertEquals(1, this.partialCacheKeyTestInterface.cacheableMethodTwoCount());
}

From source file:com.baasbox.controllers.Root.java

@With(RootCredentialWrapFilter.class)
public static Result timers() throws JsonProcessingException {
    if (!BaasBoxMetric.isActivate())
        return status(SERVICE_UNAVAILABLE, "The metrics service are disabled");
    ObjectMapper mapper = new ObjectMapper()
            .registerModule(new MetricsModule(TimeUnit.SECONDS, TimeUnit.MILLISECONDS, false));
    return ok(mapper.writeValueAsString(BaasBoxMetric.registry.getTimers()));
}

From source file:com.couchbase.client.http.ViewPool.java

/**
 * Closes the underlying connections for the given {@link HttpHost}.
 *
 * Since on a rebalance out, all connections to this view node need to
 * be closed, regardless if they are currently available or leased.
 *
 * @param host the host to shutdown connections for.
 *///from  ww w. j  a  v  a 2s .  co  m
public void closeConnectionsForHost(final HttpHost host) {
    // In-flight operations will be cancelled and retried in other parts of
    // the codebase.
    enumAvailable(new PoolEntryCallback<HttpHost, NHttpClientConnection>() {
        @Override
        public void process(PoolEntry<HttpHost, NHttpClientConnection> entry) {
            if (entry.getRoute().equals(host)) {
                entry.updateExpiry(0, TimeUnit.MILLISECONDS);
            }
        }
    });

    enumLeased(new PoolEntryCallback<HttpHost, NHttpClientConnection>() {
        @Override
        public void process(PoolEntry<HttpHost, NHttpClientConnection> entry) {
            if (entry.getRoute().equals(host)) {
                entry.updateExpiry(0, TimeUnit.MILLISECONDS);
            }
        }
    });

    closeExpired();
}

From source file:com.mkhorie.okvolley.restclient.OkHttp3Stack.java

@Override
public HttpResponse performRequest(com.android.volley.Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {

    OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
    int timeoutMs = request.getTimeoutMs();

    clientBuilder.connectTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    clientBuilder.readTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    clientBuilder.writeTimeout(timeoutMs, TimeUnit.MILLISECONDS);

    okhttp3.Request.Builder okHttpRequestBuilder = new okhttp3.Request.Builder();
    okHttpRequestBuilder.url(request.getUrl());

    Map<String, String> headers = request.getHeaders();
    for (final String name : headers.keySet()) {
        okHttpRequestBuilder.addHeader(name, headers.get(name));
    }// w  ww  . j a  v  a  2 s. c o m
    for (final String name : additionalHeaders.keySet()) {
        okHttpRequestBuilder.addHeader(name, additionalHeaders.get(name));
    }

    setConnectionParametersForRequest(okHttpRequestBuilder, request);

    OkHttpClient client = clientBuilder.build();
    okhttp3.Request okHttpRequest = okHttpRequestBuilder.build();
    Call okHttpCall = client.newCall(okHttpRequest);
    Response okHttpResponse = okHttpCall.execute();

    StatusLine responseStatus = new BasicStatusLine(parseProtocol(okHttpResponse.protocol()),
            okHttpResponse.code(), okHttpResponse.message());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromOkHttpResponse(okHttpResponse));

    Headers responseHeaders = okHttpResponse.headers();
    for (int i = 0, len = responseHeaders.size(); i < len; i++) {
        final String name = responseHeaders.name(i), value = responseHeaders.value(i);
        if (name != null) {
            response.addHeader(new BasicHeader(name, value));
        }
    }

    return response;
}

From source file:com.crossbusiness.resiliency.aspect.AnnotationTimeout2AspectTest.java

@Test
public void method_that_takes_1000ms_and_annotated_with_timeout2_of_2000ms_will_succeed()
        throws TimeoutException {
    doAnswer(new Answer<Object>() {
        public Object answer(InvocationOnMock invocation) throws InterruptedException {
            Object[] args = invocation.getArguments();
            TimeUnit.MILLISECONDS.sleep(1000);
            return args[0] + " back";
        }//from w w w  .  jav a2 s.co  m
    }).when(delegateMock).mockedMethod(anyString());

    String result = testService.timeout2_2000ms("testArg");

    assertEquals("testArg back", result);
    verify(delegateMock).mockedMethod("testArg");
    verifyZeroInteractions(delegateMock);
}

From source file:com.jayway.restassured.module.mockmvc.AsyncTest.java

@Test
public void exception_will_be_thrown_if_async_data_has_not_been_provided_in_defined_time_with_config_in_given() {
    // given// w ww .  j  ava 2 s  .  c  o m
    Exception exception = null;

    // when
    try {
        given().config(newConfig().asyncConfig(withTimeout(0, TimeUnit.MILLISECONDS))).body("a string").when()
                .async().post("/tooLongAwaiting").then().body(equalTo("a string"));
    } catch (IllegalStateException e) {
        exception = e;
    }

    // then
    assertThat(exception).isNotNull().hasMessageContaining("was not set during the specified timeToWait=0");
}

From source file:me.lazerka.gae.jersey.oauth2.facebook.FacebookFetcher.java

String fetch(URL url) throws IOException, InvalidKeyException {
    logger.trace("Requesting endpoint to validate token");

    HTTPRequest httpRequest = new HTTPRequest(url, GET, validateCertificate());

    Stopwatch stopwatch = Stopwatch.createStarted();
    HTTPResponse response = urlFetchService.fetch(httpRequest);
    logger.debug("Remote call took {}ms", stopwatch.elapsed(TimeUnit.MILLISECONDS));

    int responseCode = response.getResponseCode();
    String content = new String(response.getContent(), UTF_8);

    if (responseCode != 200) {
        logger.warn("{}: {}", responseCode, content);

        String msg = "Endpoint response code " + responseCode;

        // Something is wrong with our request.
        // If signature is invalid, then response code is 403.
        if (responseCode >= 400 && responseCode < 500) {
            try {
                JsonNode tree = jackson.readTree(content);
                JsonNode error = tree.findPath("error");
                if (!error.isMissingNode()) {
                    msg += ": " + error.findPath("message").textValue();
                }//from w  w  w  .j  a  v  a  2s .  c  o  m
            } catch (IOException e) {
                logger.warn("Cannot parse response as error");
            }
        }

        throw new InvalidKeyException(msg);
    }

    return content;
}

From source file:de.uni_freiburg.informatik.ultimate.licence_manager.authors.SvnAuthorProvider.java

private static boolean isSvnAvailable() {
    final ProcessBuilder pbuilder = new ProcessBuilder("svn", "--version");
    try {/*ww  w .  j av a2  s  .co  m*/
        final Process process = pbuilder.start();
        if (process.waitFor(1000, TimeUnit.MILLISECONDS)) {
            final List<String> lines = IOUtils.readLines(process.getInputStream(), Charset.defaultCharset());
            if (lines == null || lines.isEmpty()) {
                return false;
            }
            sSvnVersion = lines.get(0);
            return true;
        }
    } catch (IOException | InterruptedException e) {
        System.err.println("Could not find 'svn' executable, disabling author provider");
        return false;
    }
    return false;
}