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:library.util.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);

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

    Map<String, String> headers = request.getHeaders();
    for (final String name : headers.keySet()) {
        okHttpRequestBuilder.addHeader(name, headers.get(name));
    }// www.j  a  va2s .  c o  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:org.esupportail.nfctagdroid.logback.HttpAppender.java

private void doPost(final String event) {

    LogBean nfctagdroidlog = new LogBean();
    nfctagdroidlog.setNumeroId(LocalStorage.getValue("numeroId"));
    nfctagdroidlog.setErrorLevel(event.split("]")[0].replace("[", ""));
    nfctagdroidlog.setErrorReport(event.split("]")[1].trim());
    ObjectMapper mapper = new ObjectMapper();
    String jsonInString = null;/*from w  w w .ja va2s.  com*/
    try {
        jsonInString = mapper.writeValueAsString(nfctagdroidlog);
    } catch (JsonProcessingException e) {
        throw new NfcTagDroidException("", e);
    }
    final String[] params = new String[2];
    params[0] = getEndpoint();
    params[1] = jsonInString;
    LogHttpRequestAsync task = new LogHttpRequestAsync();
    try {
        task.execute(params).get(time, TimeUnit.MILLISECONDS);
    } catch (TimeoutException e) {
        throw new NfcTagDroidException("Time out Log", e);
    } catch (InterruptedException e) {
        throw new NfcTagDroidException("InterruptedException", e);
    } catch (ExecutionException e) {
        throw new NfcTagDroidException("ExecutionException", e);
    }

}

From source file:io.watchcat.node.reporting.LinuxMetricsCollector.java

@PostConstruct
public void postConstruct() {
    scheduledExecutorService.scheduleAtFixedRate(loadAverage, 1000, 1000, TimeUnit.MILLISECONDS);
    scheduledExecutorService.scheduleAtFixedRate(memoryUsage, 1000, 1000, TimeUnit.MILLISECONDS);
    scheduledExecutorService.scheduleAtFixedRate(diskUsage, 1000, 1000, TimeUnit.MILLISECONDS);
    scheduledExecutorService.scheduleAtFixedRate(bandwidth, 1000, 1000, TimeUnit.MILLISECONDS);
    scheduledExecutorService.scheduleAtFixedRate(processes, 1000, 1000, TimeUnit.MILLISECONDS);
    scheduledExecutorService.scheduleAtFixedRate(networkConnections, 1000, 1000, TimeUnit.MILLISECONDS);
}

From source file:com.sm.transport.netty.EchoClientHandler.java

public void sendObject(Object request, Channel channel) {
    if (!channel.isConnected())
        throw new ConnectionException("broken connection");
    lock.lock();//from   w  w w  .  j  av  a2 s.  c  o  m
    try {
        channel.write(request);
        ready = false;
        try {
            boolean flag = notReady.await(timeout, TimeUnit.MILLISECONDS);
            if (!flag) {
                cleanUp();
                channel.disconnect();
                throw new ConnectionException(timeout + " seconds time out from " + channel.getRemoteAddress());
            }
            // return response
            else {

                logger.info("complete " + request.toString().length());
            }
        } catch (Exception ex) {
            cleanUp();
            logger.error(ex.getMessage(), ex);
        }
    } finally {
        lock.unlock();
    }
}

From source file:com.mgmtp.perfload.core.client.util.concurrent.DelayingExecutorServiceTest.java

@Test
public void testWithoutDelay() throws InterruptedException, BrokenBarrierException {
    DelayingExecutorService execSrv = new DelayingExecutorService();

    final StopWatch sw = new StopWatch();

    final CyclicBarrier stopBarrier = new CyclicBarrier(11, new Runnable() {
        @Override//  w ww  . j  a  v a2  s.  c o  m
        public void run() {
            sw.stop();
        }
    });

    sw.start();

    for (int i = 0; i < 10; ++i) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1L);
                    stopBarrier.await();
                } catch (Exception ex) {
                    throw new AssertionError(ex);
                }
            }
        };

        ScheduledFuture<?> future = execSrv.schedule(r, 0L, TimeUnit.NANOSECONDS);

        // compare with epsilon to make up for bad accuracy
        assertTrue(abs(future.getDelay(TimeUnit.MILLISECONDS)) < EPSILON);
    }

    stopBarrier.await();

    assertTrue(sw.getTime() < EPSILON);
}

From source file:com.apachecon.camel.filesplit.FileSplitTest.java

@Test
public void testFileSplitParallelProc() throws Exception {
    PropertiesComponent props = context.getRegistry().lookup("properties", PropertiesComponent.class);
    int count = Integer.parseInt(props.parseUri("{{demo.message.count}}"));
    CountDownLatch trigger = new CountDownLatch(count);

    SplitCounterProcessor splitCounter = context.getRegistry().lookup("splitCounter",
            SplitCounterProcessor.class);
    splitCounter.setCounter(trigger);/* w ww .  j  av  a 2  s. c  o m*/

    // file poller starts automatically when the route starts
    // since we created the 'fetch' route with autoStartup=false
    // polling won't start until we start the route
    log.info("Expecting to process {} messages", count);
    context.startRoute("fetch");

    // set a timeout larger than the expected processing time
    int timeout = 10 * 1000;
    boolean success = trigger.await(timeout, TimeUnit.MILLISECONDS);
    long delta = success ? System.currentTimeMillis() - splitCounter.getTimeStarted() : timeout;
    String outcome = success ? "finished in" : "timed out after";
    log.info("Processing {} {} millis", outcome, delta);

    assertTrue(success);
}

From source file:cn.scala.es.HeartBeat.java

HeartBeat(final Progressable progressable, Configuration cfg, TimeValue lead, final Log log) {
    Assert.notNull(progressable, "a valid progressable is required to report status to Hadoop");
    TimeValue tv = HadoopCfgUtils.getTaskTimeout(cfg);

    Assert.isTrue(tv.getSeconds() <= 0 || tv.getSeconds() > lead.getSeconds(),
            "Hadoop timeout is shorter than the heartbeat");

    this.progressable = progressable;
    long cfgMillis = (tv.getMillis() > 0 ? tv.getMillis() : 0);
    // the task is simple hence the delay = timeout - lead, that is when to start the notification right before the timeout
    this.delay = new TimeValue(Math.abs(cfgMillis - lead.getMillis()), TimeUnit.MILLISECONDS);
    this.log = log;

    String taskId;//from   w  w  w  . j  a va  2s  .c  o  m
    TaskID taskID = HadoopCfgUtils.getTaskID(cfg);

    if (taskID == null) {
        log.warn("Cannot determine task id...");
        taskId = "<unknown>";
        if (log.isTraceEnabled()) {
            log.trace("Current configuration is " + HadoopCfgUtils.asProperties(cfg));
        }
    } else {
        taskId = "" + taskID;
    }

    id = taskId;
}

From source file:cn.wanghaomiao.seimi.http.okhttp.OkHttpDownloader.java

@Override
public Response process(Request request) throws Exception {
    currentRequest = request;/*from ww  w .  j av  a 2  s  .  c  om*/
    OkHttpClient.Builder hcBuilder = OkHttpClientBuilderProvider.getInstance();
    if (crawlerModel.isUseCookie()) {
        hcBuilder.cookieJar(CookiesMgrProvider.getInstance());
    }
    if (crawlerModel.getStdProxy() != null) {
        hcBuilder.proxy(crawlerModel.getStdProxy());
    }
    hcBuilder.readTimeout(crawlerModel.getHttpTimeOut(), TimeUnit.MILLISECONDS);
    okHttpClient = hcBuilder.build();
    currentRequestBuilder = OkHttpRequestGenerator.getOkHttpRequesBuilder(request, crawlerModel);
    lastResponse = okHttpClient.newCall(currentRequestBuilder.build()).execute();
    return renderResponse(lastResponse, request);
}

From source file:com.tongbanjie.tarzan.server.client.ClientManager.java

public HashMap<String, HashMap<Channel, ClientChannelInfo>> getGroupChannelTable() {
    HashMap<String, HashMap<Channel, ClientChannelInfo>> newGroupChannelTable = new HashMap<String, HashMap<Channel, ClientChannelInfo>>();
    try {/*from  w w  w .j a  v  a  2  s.  c om*/
        if (this.groupChannelLock.tryLock(LOCK_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)) {
            try {
                newGroupChannelTable.putAll(groupChannelTable);
            } finally {
                groupChannelLock.unlock();
            }
        }
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        LOGGER.error("", e);
    }
    return newGroupChannelTable;
}

From source file:com.adaptris.core.fs.TraversingFsConsumerTest.java

public void testConsume() throws Exception {
    String subDir = new GuidGenerator().safeUUID();
    MockMessageListener stub = new MockMessageListener(10);
    FsConsumer fs = createConsumer(subDir);
    fs.setReacquireLockBetweenMessages(true);
    fs.setPoller(new FixedIntervalPoller(new TimeInterval(300L, TimeUnit.MILLISECONDS)));
    StandaloneConsumer sc = new StandaloneConsumer(fs);
    sc.registerAdaptrisMessageListener(stub);
    int count = 10;
    File parentDir = FsHelper/*from ww w.  j a va  2s.com*/
            .createFileReference(FsHelper.createUrlFromString(PROPERTIES.getProperty(BASE_KEY), true));
    try {
        File baseDir = new File(parentDir, subDir);
        start(sc);
        createFiles(baseDir, ".xml", count);
        waitForMessages(stub, count);
        assertMessages(stub.getMessages(), count);
    } finally {
        stop(sc);
        FileUtils.deleteQuietly(new File(parentDir, subDir));
    }
}