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:org.sonatype.nexus.apachehttpclient.EvictingThread.java

@Override
public void run() {
    LOGGER.debug("Starting '{}' (delay {} millis)", getName(), delay);
    try {/*from w  w  w  . j  av a  2 s . c o  m*/
        while (true) {
            synchronized (this) {
                wait(delay);
                try {
                    httpClientConnectionManager.closeExpiredConnections();
                } catch (final Exception e) {
                    LOGGER.warn("Failed to close expired connections", e);
                }
                try {
                    httpClientConnectionManager.closeIdleConnections(idleTimeMillis, TimeUnit.MILLISECONDS);
                } catch (final Exception e) {
                    LOGGER.warn("Failed to close expired connections", e);
                }
            }
        }
    } catch (InterruptedException e) {
        // bye bye
    }
    LOGGER.debug("Stopped '{}'", getName());
}

From source file:tech.niuchuang.xzlibrary.net.okhttp.OkHttp3Stack.java

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

    int timeoutMs = request.getTimeoutMs();
    // okhttp 3.0?OkHttpClientBuilder
    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 . ja v  a2 s  .c  o m
    for (final String name : additionalHeaders.keySet()) {
        // header??name???
        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:com.offbynull.portmapper.natpmp.NatPmpPortMapper.java

/**
 * Constructs a {@link NatPmpPortMapper} object.
 * @param gatewayAddress gateway address
 * @param listener event listener/*from w w  w .j ava2 s.c  om*/
 * @throws NullPointerException if any argument is {@code null}
 * @throws IOException if problems initializing UDP channels
 */
public NatPmpPortMapper(InetAddress gatewayAddress, final PortMapperEventListener listener) throws IOException {
    Validate.notNull(gatewayAddress);
    Validate.notNull(listener);

    controller = new NatPmpController(gatewayAddress, new NatPmpControllerListener() {
        private boolean lastAvailable;
        private long lastEpoch;
        private long lastRecvTime;

        @Override
        public void incomingResponse(CommunicationType type, NatPmpResponse response) {
            if (closed) {
                return;
            }

            if (type == CommunicationType.MULTICAST && response instanceof ExternalAddressNatPmpResponse) {
                listener.resetRequired("Mappings may have been lost via external IP address change.");
                return;
            }

            // As described in section 3.6 of the RFC
            if (!lastAvailable) {
                lastRecvTime = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());
                lastEpoch = response.getSecondsSinceStartOfEpoch();
                lastAvailable = true;
            } else {
                long recvTime = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());
                long epoch = response.getSecondsSinceStartOfEpoch();

                long elapsedTime = Math.max(0L, recvTime - lastRecvTime); // max just in case
                long epochWindow = elapsedTime * 7L / 8L;

                long minEpoch = (lastEpoch + epochWindow - 2L) & 0xFFFFFFFFL; // add and truncate top 32bits

                if (epoch < minEpoch) {
                    listener.resetRequired("Mappings may have been lost via device reset.");
                    return;
                }

                lastRecvTime = recvTime;
                lastEpoch = epoch;
            }
        }
    });
}

From source file:com.ryantenney.metrics.spring.reporter.AbstractScheduledReporterFactoryBean.java

/**
 * Parses and converts to nanoseconds a string representing
 * a duration, ie: 500ms, 30s, 5m, 1h, etc
 * @param duration a string representing a duration
 * @return the duration in nanoseconds/*from   w w  w  .  j av  a 2  s  .  co m*/
 */
protected long convertDurationString(String duration) {
    final Matcher m = DURATION_STRING_PATTERN.matcher(duration);
    if (!m.matches()) {
        throw new IllegalArgumentException("Invalid duration string format");
    }

    final long sourceDuration = Long.parseLong(m.group(1));
    final String sourceUnitString = m.group(2);
    final TimeUnit sourceUnit;
    if ("ns".equalsIgnoreCase(sourceUnitString)) {
        sourceUnit = TimeUnit.NANOSECONDS;
    } else if ("us".equalsIgnoreCase(sourceUnitString)) {
        sourceUnit = TimeUnit.MICROSECONDS;
    } else if ("ms".equalsIgnoreCase(sourceUnitString)) {
        sourceUnit = TimeUnit.MILLISECONDS;
    } else if ("s".equalsIgnoreCase(sourceUnitString)) {
        sourceUnit = TimeUnit.SECONDS;
    } else if ("m".equalsIgnoreCase(sourceUnitString)) {
        sourceUnit = TimeUnit.MINUTES;
    } else if ("h".equalsIgnoreCase(sourceUnitString)) {
        sourceUnit = TimeUnit.HOURS;
    } else if ("d".equalsIgnoreCase(sourceUnitString)) {
        sourceUnit = TimeUnit.DAYS;
    } else {
        sourceUnit = TimeUnit.MILLISECONDS;
    }

    return sourceUnit.toNanos(sourceDuration);
}

From source file:locksdemo.RedisLockService.java

@Override
public Lock create(String name) {
    String stored = getValue(name);
    if (stored != null) {
        throw new LockExistsException();
    }// w  ww . ja  v a  2 s . co  m
    String value = UUID.randomUUID().toString();
    String key = keyForName(name);
    if (!redisOperations.opsForValue().setIfAbsent(key, value)) {
        throw new LockExistsException();
    }
    redisOperations.expire(key, expiry, TimeUnit.MILLISECONDS);
    Date expires = new Date(System.currentTimeMillis() + expiry);
    return new Lock(name, value, expires);
}

From source file:org.eurekaclinical.scribeupext.provider.GlobusProvider.java

@Override
protected String sendRequestForData(Token accessToken, String dataUrl) throws HttpException {
    System.out.println("Access token is " + accessToken.getSecret() + "; " + accessToken.getToken());
    String dataUrlCompleted = String.format(dataUrl, ((GlobusOAuth20ServiceImpl) this.service).getUsername());
    System.out.println("dataUrlCompleted: " + dataUrlCompleted);
    final ProxyOAuthRequest request = new ProxyOAuthRequest(Verb.GET, dataUrlCompleted, this.proxyHost,
            this.proxyPort);
    if (this.connectTimeout != 0) {
        request.setConnectTimeout(this.connectTimeout, TimeUnit.MILLISECONDS);
    }//from  ww w .  j a v a 2s .com
    if (this.readTimeout != 0) {
        request.setReadTimeout(this.readTimeout, TimeUnit.MILLISECONDS);
    }
    this.service.signRequest(accessToken, request);
    request.addHeader("Content-Type", "application/json");
    final Response response = request.send();
    final int code = response.getCode();
    final String body = response.getBody();
    if (code != 200) {
        throw new HttpException(code, body);
    }
    return body;
}

From source file:net.pterodactylus.sone.web.ajax.GetTimesAjaxPage.java

/**
 * {@inheritDoc}//from   w  w w  . j  a v  a 2 s. com
 */
@Override
protected JsonReturnObject createJsonObject(FreenetRequest request) {
    String allIds = request.getHttpRequest().getParam("posts");
    ObjectNode postTimes = new ObjectNode(instance);
    if (allIds.length() > 0) {
        String[] ids = allIds.split(",");
        for (String id : ids) {
            Optional<Post> post = webInterface.getCore().getPost(id);
            if (!post.isPresent()) {
                continue;
            }
            ObjectNode postTime = new ObjectNode(instance);
            Time time = getTime(post.get().getTime());
            postTime.put("timeText", time.getText());
            postTime.put("refreshTime", TimeUnit.MILLISECONDS.toSeconds(time.getRefresh()));
            synchronized (dateFormat) {
                postTime.put("tooltip", dateFormat.format(new Date(post.get().getTime())));
            }
            postTimes.put(id, postTime);
        }
    }
    ObjectNode replyTimes = new ObjectNode(instance);
    allIds = request.getHttpRequest().getParam("replies");
    if (allIds.length() > 0) {
        String[] ids = allIds.split(",");
        for (String id : ids) {
            Optional<PostReply> reply = webInterface.getCore().getPostReply(id);
            if (!reply.isPresent()) {
                continue;
            }
            ObjectNode replyTime = new ObjectNode(instance);
            Time time = getTime(reply.get().getTime());
            replyTime.put("timeText", time.getText());
            replyTime.put("refreshTime", TimeUnit.MILLISECONDS.toSeconds(time.getRefresh()));
            synchronized (dateFormat) {
                replyTime.put("tooltip", dateFormat.format(new Date(reply.get().getTime())));
            }
            replyTimes.put(id, replyTime);
        }
    }
    return createSuccessJsonObject().put("postTimes", postTimes).put("replyTimes", replyTimes);
}

From source file:com.ydh.gva.util.net.volley.toolbox.OkHttpStack.java

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

    OkHttpClient client = mClient.clone();
    int timeoutMs = request.getTimeoutMs();
    client.setConnectTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setReadTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setWriteTimeout(timeoutMs, TimeUnit.MILLISECONDS);

    com.squareup.okhttp.Request.Builder okHttpRequestBuilder = new com.squareup.okhttp.Request.Builder();
    okHttpRequestBuilder.url(request.getUrl());

    Map<String, String> headers = request.getHeaders();
    okHttpRequestBuilder.addHeader("clientos", "101");
    okHttpRequestBuilder.addHeader("osversion", SystemVal.sdk + "");
    okHttpRequestBuilder.addHeader("clientphone", SystemVal.model + "");
    okHttpRequestBuilder.addHeader("weiLeversion", SystemVal.versionCode + "");

    for (final String name : headers.keySet()) {
        okHttpRequestBuilder.addHeader(name, headers.get(name));
    }/*from www .  j a v a2  s  .co  m*/

    for (final String name : additionalHeaders.keySet()) {
        okHttpRequestBuilder.addHeader(name, additionalHeaders.get(name));
    }

    setConnectionParametersForRequest(okHttpRequestBuilder, request);

    com.squareup.okhttp.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:rmblworx.tools.timey.SimpleTimer.java

@Override
public Boolean resetStopwatch() {
    boolean isRunningAtTheMoment = false;
    if (this.scheduler != null && !this.scheduler.isTerminated()) {
        isRunningAtTheMoment = true;/*  www  . j  a v  a 2 s  . com*/
        this.stopStopwatch();
    }
    this.timePassed = 0;
    this.timeDescriptor.setMilliSeconds(0);
    if (isRunningAtTheMoment) {
        this.startStopwatch(1, TimeUnit.MILLISECONDS);
    }
    return isRunningAtTheMoment;
}

From source file:com.netflix.suro.sink.notice.QueueNotice.java

@Override
public E recv() {
    try {/* ww w  .j a  v a 2 s .c o m*/
        return queue.poll(timeout, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
        return null;
    }
}