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.objectivetruth.uoitlibrarybooking.app.networking.OkHttp3Stack.java

@Override
public HttpResponse performRequest(com.android.volley.Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {
    String USER_AGENT_KEY_NAME = "User-Agent";

    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);
    //clientBuilder.followRedirects(false);
    clientBuilder.cookieJar(cookieJar);/*from  ww  w.jav a2s.  com*/

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

    Map<String, String> headers = request.getHeaders();
    for (final String name : headers.keySet()) {
        String outgoingHeaderValue = headers.get(name);
        okHttpRequestBuilder.addHeader(name, outgoingHeaderValue);
        Timber.v("Outgoing Header:" + name + ": " + outgoingHeaderValue);
    }
    for (final String name : additionalHeaders.keySet()) {
        okHttpRequestBuilder.addHeader(name, additionalHeaders.get(name));
        Timber.v("Outgoing Additional Header:" + name + ": " + additionalHeaders.get(name));
    }

    Timber.d("Injecting User-Agent into request(will overwrite any other user-agent headers placed)");
    okHttpRequestBuilder.addHeader(USER_AGENT_KEY_NAME, USER_AGENT_VALUE);
    Timber.v("Outgoing Header:" + USER_AGENT_KEY_NAME + ": " + USER_AGENT_VALUE);

    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) {
            Timber.v("Incoming Header:" + name + ": " + value);
            response.addHeader(new BasicHeader(name, value));
        }
    }
    return response;
}

From source file:com.worldline.easycukes.selenium.utils.SeleniumHelper.java

/**
 * @return// w w  w.  ja  v  a  2s. co m
 */
public static void waitUntilElementIsHidden(@NonNull final WebDriver driver, @NonNull final By by) {
    // Waiting for an element to be present on the page, checking for its
    // presence once every second.
    final FluentWait<WebDriver> wait = new FluentWait<>(driver)
            .withTimeout(WAITING_TIME_OUT_IN_SECONDS, TimeUnit.SECONDS)
            .pollingEvery(POLLING_INTERVAL_IN_MILLIS, TimeUnit.MILLISECONDS).ignoring(TimeoutException.class);

    wait.until(new ExpectedCondition<Boolean>() {
        @Override
        public Boolean apply(WebDriver webDriver) {
            try {
                log.debug("waiting for hidden " + by);
                final List<WebElement> list = webDriver.findElements(by);
                for (final WebElement webElement : list)
                    if (webElement.isDisplayed()) {
                        log.debug("Still displayed !");// TODO
                        return false;
                    }
                return true;
            } catch (final StaleElementReferenceException e) {
                return true;
            } catch (final NoSuchElementException e) {
                return true;
            }
        }
    });
}

From source file:jp.realglobe.util.uploader.DelayedWatcherTest.java

/**
 * ?????//from w ww  .j  a va2s  . com
 * @throws Exception 
 */
@Test
public void testCreateEmpty() throws Exception {
    final long delay = 1_000L;
    final DelayedWatcher watcher = new DelayedWatcher(this.directory, delay, false, path -> {
        this.detected.offer(path);
    });
    this.executor.submit(watcher);
    Thread.sleep(1_000L);

    final int n = 10;
    for (int i = 0; i < n; i++) {
        Files.createFile(this.directory.resolve("" + i));
    }
    for (int i = 0; i < n; i++) {
        Assert.assertEquals(this.directory.resolve("" + i),
                this.detected.poll(1_000L + delay, TimeUnit.MILLISECONDS));
    }
    Assert.assertNull(this.detected.poll(1_000L, TimeUnit.MILLISECONDS));
}

From source file:io.seldon.memcache.ExceptionSwallowingMemcachedClient.java

@Override
public Object get(String key) {
    Object myObj = null;/*  w ww .j  a v a2  s  . c o  m*/
    Future<Object> f = super.asyncGet(hashKey(key));
    try {
        myObj = f.get(500, TimeUnit.MILLISECONDS);
    } catch (TimeoutException e) {
        logger.warn("Timeout exception in get ", e);
        f.cancel(false);
    } catch (InterruptedException e) {
        logger.error("Interrupted in get ", e);
        f.cancel(false);
    } catch (ExecutionException e) {
        logger.error("Execution exception in get ", e);
        f.cancel(false);
    }
    return myObj;
}

From source file:co.cask.cdap.gateway.handlers.metrics.MetricsHandlerTestRun.java

private static void setupMetrics() throws Exception {
    // Adding metrics for app "WordCount1" in namespace "myspace", "WCount1" in "yourspace"
    MetricsContext collector = collectionService
            .getContext(getFlowletContext("myspace", "WordCount1", "WordCounter", "run1", "splitter"));
    collector.increment("reads", 1);
    collector.increment("writes", 1);
    collector = collectionService//w w  w.j  a va 2 s .  c om
            .getContext(getFlowletContext("yourspace", "WCount1", "WordCounter", "run1", "splitter"));
    collector.increment("reads", 1);
    collector = collectionService
            .getContext(getFlowletContext("yourspace", "WCount1", "WCounter", "run1", "splitter"));
    emitTs = System.currentTimeMillis();
    // we want to emit in two different seconds
    // todo : figure out why we need this
    TimeUnit.SECONDS.sleep(1);
    collector.increment("reads", 1);
    TimeUnit.MILLISECONDS.sleep(2000);
    collector.increment("reads", 2);

    collector = collectionService
            .getContext(getFlowletContext("yourspace", "WCount1", "WCounter", "run1", "counter"));
    collector.increment("reads", 1);
    collector = collectionService.getContext(getMapReduceTaskContext("yourspace", "WCount1", "ClassicWordCount",
            MapReduceMetrics.TaskType.Mapper, "run1", "task1"));
    collector.increment("reads", 1);
    collector = collectionService.getContext(getMapReduceTaskContext("yourspace", "WCount1", "ClassicWordCount",
            MapReduceMetrics.TaskType.Reducer, "run1", "task2"));
    collector.increment("reads", 1);
    collector = collectionService
            .getContext(getFlowletContext("myspace", "WordCount1", "WordCounter", "run1", "splitter"));
    collector.increment("reads", 1);
    collector.increment("writes", 1);

    collector = collectionService
            .getContext(getFlowletContext("myspace", "WordCount1", "WordCounter", "run1", "collector"));
    collector.increment("aa", 1);
    collector.increment("zz", 1);
    collector.increment("ab", 1);

    collector = collectionService
            .getContext(getWorkerContext("yourspace", "WCount1", "WorkerWordCount", "run1", "task1"));

    collector.increment("workerreads", 5);
    collector.increment("workerwrites", 6);

    collector = collectionService
            .getContext(getWorkerContext("yourspace", "WCount1", "WorkerWordCount", "run2", "task1"));

    collector.increment("workerreads", 5);
    collector.increment("workerwrites", 6);

    // also: user metrics
    Metrics userMetrics = new ProgramUserMetrics(collectionService
            .getContext(getFlowletContext("myspace", "WordCount1", "WordCounter", "run1", "splitter")));
    userMetrics.count("reads", 1);
    userMetrics.count("writes", 2);

    collector = collectionService.getContext(new HashMap<String, String>());
    collector.increment("resources.total.storage", 10);

    // need a better way to do this
    TimeUnit.SECONDS.sleep(2);
}

From source file:org.mitre.oauth2.introspectingfilter.OAuth2AccessTokenImpl.java

@Override
public int getExpiresIn() {
    if (expireDate != null) {
        return (int) TimeUnit.MILLISECONDS.toSeconds(expireDate.getTime() - (new Date()).getTime());
    }/*from www .  j a  v  a  2 s.  c o m*/
    return 0;
}

From source file:com.arpnetworking.metrics.proxy.actors.Connection.java

/**
 * Public constructor.//  w  w  w . j  av a  2  s  . c o  m
 *
 * @param metricsFactory Instance of <code>MetricsFactory</code>.
 * @param processorsFactory Factory for producing the protocol's <code>MessagesProcessor</code>
 */
public Connection(final MetricsFactory metricsFactory, final MessageProcessorsFactory processorsFactory) {
    _metricsFactory = metricsFactory;
    _instrument = context().system().scheduler().schedule(new FiniteDuration(0, TimeUnit.SECONDS), // Initial delay
            new FiniteDuration(500, TimeUnit.MILLISECONDS), // Interval
            getSelf(), "instrument", ExecutionContexts.global(), getSelf());
    _messageProcessors = processorsFactory.create(this);
    _metrics = createMetrics();
}

From source file:tw.showang.apiabstrationframework.support.volley.OkHttp3Stack.java

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

    int timeoutMs = request.getTimeoutMs();
    OkHttpClient.Builder builder = mClient.newBuilder();
    builder.connectTimeout(timeoutMs, TimeUnit.MILLISECONDS).readTimeout(timeoutMs, TimeUnit.MILLISECONDS)
            .writeTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    OkHttpClient client = builder.build();

    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 w w .j a v a 2  s .c om*/
    for (final String name : additionalHeaders.keySet()) {
        okHttpRequestBuilder.header(name, additionalHeaders.get(name));
    }

    setConnectionParametersForRequest(okHttpRequestBuilder, request);

    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:org.jetbrains.webdemo.authorization.AuthorizationGoogleHelper.java

@Override
@Nullable/*from   ww  w .j  av  a 2s .co m*/
public UserInfo verify(String oauthVerifier) {
    UserInfo userInfo = null;
    try {
        Verifier verifier = new Verifier(oauthVerifier);
        Token accessToken = googleService.getAccessToken(EMPTY_TOKEN, verifier);
        OAuthRequest request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL);
        request.setConnectTimeout(TIMEOUT, TimeUnit.MILLISECONDS);
        googleService.signRequest(accessToken, request);
        Response response = request.send();
        userInfo = new UserInfo();
        JsonNode object = new ObjectMapper().readTree(response.getBody());
        String firstName = object.has("given_name") ? object.get("given_name").asText() : "";
        String lastName = object.has("family_name") ? object.get("family_name").asText() : "";
        String id = object.get("id").textValue();

        userInfo.login(firstName + " " + lastName, id, TYPE);

    } catch (Throwable e) {
        ErrorWriter.ERROR_WRITER.writeExceptionToExceptionAnalyzer(e,
                SessionInfo.TypeOfRequest.AUTHORIZATION.name(), "unknown", "google: " + oauthVerifier);
    }
    return userInfo;
}