Example usage for java.util.concurrent TimeoutException printStackTrace

List of usage examples for java.util.concurrent TimeoutException printStackTrace

Introduction

In this page you can find the example usage for java.util.concurrent TimeoutException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:UnitTest4.java

public static void execute()
        throws ClientProtocolException, IOException, InterruptedException, ExecutionException {
    /*/*from  w w w .ja  va2 s  .  co  m*/
      CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
      try {
    httpclient.start();
    HttpGet request = new HttpGet("http://www.apache.org/");
    Future<HttpResponse> future = httpclient.execute(request, null);
    HttpResponse response = future.get();
    System.out.println("Response: " + response.getStatusLine());
    System.out.println("Shutting down");
      } finally {
    httpclient.close();
      }
      System.out.println("Done");
    */

    /*
    try (CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault()) {
        httpclient.start();
        HttpPost request = new HttpPost(addr);
        StringEntity entity = new StringEntity(event, ContentType.create("application/json", Consts.UTF_8));
        request.setEntity(entity);
        httpclient.execute(request, null);
    } catch (Exception e) {
        LOG.error("Failed to sending event", e);
    }
    */
    //Asserts a;
    CloseableHttpAsyncClient m_httpClient = HttpAsyncClients.createDefault();

    m_httpClient.start();

    HttpHost m_target = new HttpHost("localhost", 5000, "http");
    //HttpPost postRequest = new HttpPost("http://localhost:5000/hello");
    HttpPost postRequest = new HttpPost("/");

    StringEntity params = new StringEntity("");

    postRequest.addHeader("content-type", "application/json");
    postRequest.setEntity(params);

    log.debug("execute() executing request to " + m_target);

    //HttpAsyncRequestConsumer<HttpRequest> gh;

    // works HttpResponse httpResponse = httpClient.execute(target, getRequest);
    Future<HttpResponse> future = m_httpClient.execute(m_target, postRequest, null);
    //Future<HttpResponse> future = m_httpClient.execute(postRequest, null);
    //HttpResponse httpResponse = future.get();
    while (future.isDone() == false) {
        log.debug("Inside while");
    }
    HttpResponse httpResponse = null;
    try {
        httpResponse = future.get(100, TimeUnit.NANOSECONDS);
    } catch (TimeoutException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    HttpEntity entity = httpResponse.getEntity();

    log.debug("execute()----------------------------------------");
    log.debug("execute() {}", httpResponse.getStatusLine());
    Header[] headers = httpResponse.getAllHeaders();
    for (int i = 0; i < headers.length; i++) {
        log.debug("execute() {}", headers[i]);
    }
    log.debug("execute()----------------------------------------");

    String jsonString = null;
    if (entity != null) {
        jsonString = EntityUtils.toString(entity);
        log.debug("execute() {}", jsonString);
    }

}

From source file:org.openmrs.module.amqpmodule.utils.impl.PublisherServiceImpl.java

@Override
public boolean PublisherCreateConnection() throws java.io.IOException {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("192.168.43.123");
    factory.setPort(5672);// ww  w .  j  ava 2s .co m
    factory.setUsername("chs");
    factory.setPassword("chs123");
    Connection connection = null;
    try {
        connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.exchangeDeclare(EXCHANGE_NAME, "direct", true);

        channel.basicPublish(EXCHANGE_NAME, topic, MessageProperties.PERSISTENT_TEXT_PLAIN, msg.getBytes());
        System.out.println(" [x] Sent '" + msg + "'");

        channel.close();

    } catch (TimeoutException e) {
        System.out.println("Connection Timed out");
        e.printStackTrace();
    }

    connection.close();

    return true;
}

From source file:com.tk.httpClientErp.headmandraw.DrawsListActivity.java

/**
 * /*from  w  w w . j  a  v a2 s  .c  o m*/
 */
@SuppressWarnings("unchecked")
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    super.onOptionsItemSelected(item);
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    switch (item.getItemId()) // Id
    {
    case R.id.menu_item_buslist_yes:
        HashMap<String, Object> hashMapsYES = MyStore.subAndDel(MyStore.drawList);
        List<JSONObject> submitJsonArrayYES = (List<JSONObject>) hashMapsYES.get("submitJsonArray");
        List<HashMap<String, Object>> delListYES = (List<HashMap<String, Object>>) hashMapsYES.get("delList");
        params.add(new BasicNameValuePair("submitJsonArray", submitJsonArrayYES.toString()));
        String reultString = null;
        try {
            reultString = HttpClientUtil.postRequest("/android.do?method=updateDraws", params,
                    MyStore.sessionID);
        } catch (TimeoutException e) {
            e.printStackTrace();
            DrawsListActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(DrawsListActivity.this, MyStore.TIMEOUTLOGIN, Toast.LENGTH_SHORT).show();
                }
            });
        }
        reultString = HttpClientUtil.callBackSuccOrFail(reultString, "resualt");
        if (HttpClientUtil.reSUCCorFAILE)
            MyStore.drawList.removeAll(delListYES);
        final String MSG = reultString;
        DrawsListActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(DrawsListActivity.this, MSG, Toast.LENGTH_SHORT).show();
            }
        });
        ((MySimpleAdapter) getListAdapter()).notifyDataSetChanged();
        break;
    case R.id.menu_item_buslist_selectec_or_cancle:
        MyStore.selectORcancle(mResult, "mResult", MyStore.drawList);
        mResult = mResult == true ? false : true;
        ((MySimpleAdapter) getListAdapter()).notifyDataSetChanged();
        break;
    }
    return true;
}

From source file:com.tk.httpClientErp.buscheck.BusListActivity.java

/**
 * //from w w  w.  j  ava 2s.c om
 */
@SuppressWarnings("unchecked")
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    super.onOptionsItemSelected(item);
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    switch (item.getItemId()) {
    //   
    case R.id.menu_item_buslist_yes:
        HashMap<String, Object> busListHashMaps = MyStore.subAndDel(MyStore.busList);
        List<JSONObject> submitJsonArray = (List<JSONObject>) busListHashMaps.get("submitJsonArray");
        List<HashMap<String, Object>> delList = (List<HashMap<String, Object>>) busListHashMaps.get("delList");
        params.add(new BasicNameValuePair("submitJsonArray", submitJsonArray.toString()));
        String reultString = null;
        try {
            reultString = HttpClientUtil.postRequest("/android.do?method=checkBusList", params,
                    MyStore.sessionID);
        } catch (TimeoutException e) {
            e.printStackTrace();
            BusListActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(BusListActivity.this, MyStore.TIMEOUTLOGIN, Toast.LENGTH_SHORT).show();
                }
            });
        }
        if (HttpClientUtil.reSUCCorFAILE && delList.size() != 0)
            MyStore.busList.removeAll(delList);
        reultString = HttpClientUtil.callBackSuccOrFail(reultString, "resualt");
        final String MSG = reultString;
        BusListActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(BusListActivity.this, MSG, Toast.LENGTH_SHORT).show();
            }
        });
        ((SimpleAdapter) getListAdapter()).notifyDataSetChanged();
        break;
    //   /
    case R.id.menu_item_buslist_selectec_or_cancle:
        MyStore.selectORcancle(mResult, "mResult", MyStore.busList);
        mResult = mResult == true ? false : true;
        ((SimpleAdapter) getListAdapter()).notifyDataSetChanged();
        break;
    }
    return true;
}

From source file:com.tk.httpClientErp.headmancheck.HeadmancheckDetailActivity.java

/**
 * =====================================
 */// ww w .  java2  s.c om
@SuppressWarnings("unchecked")
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    super.onOptionsItemSelected(item);
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    String reultString = null;
    switch (item.getItemId()) {
    case R.id.menu_item_headmanchecklist_check_yes:
        HashMap<String, Object> hashMapsYES = MyStore.subAndDel(MyStore.headManCheckList);
        List<JSONObject> submitJsonArrayYES = (List<JSONObject>) hashMapsYES.get("submitJsonArray");
        List<HashMap<String, Object>> delListYES = (List<HashMap<String, Object>>) hashMapsYES.get("delList");
        params.add(new BasicNameValuePair("submitJsonArray", submitJsonArrayYES.toString()));
        try {
            reultString = HttpClientUtil.postRequest("/android.do?method=updateHeadmancheckYES", params,
                    MyStore.sessionID);
        } catch (TimeoutException e) {
            e.printStackTrace();
            HeadmancheckDetailActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(HeadmancheckDetailActivity.this, MyStore.TIMEOUTLOGIN, Toast.LENGTH_SHORT)
                            .show();
                }
            });
        }
        reultString = HttpClientUtil.callBackSuccOrFail(reultString, "resualt");
        if (HttpClientUtil.reSUCCorFAILE && delListYES.size() != 0) {
            MyStore.headManCheckList.removeAll(delListYES);
            headmancheckDetail.removeAll(delListYES);
        }
        final String MSG = reultString;
        HeadmancheckDetailActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(HeadmancheckDetailActivity.this, MSG, Toast.LENGTH_SHORT).show();
            }
        });
        if (headmancheckDetail.size() == 0) {
            MyStore.deletBeanById(gd_no, "gd_no", MyStore.headManCheckFenzu);
            HeadmancheckDetailActivity.this.finish(); // Activity
        }
        ((MySimpleAdapter) getListAdapter()).notifyDataSetChanged();
        break;
    case R.id.menu_item_headmanchecklist_check_no:
        HashMap<String, Object> hashMapsNO = MyStore.subAndDel(MyStore.headManCheckList);
        List<JSONObject> submitJsonArrayNO = (List<JSONObject>) hashMapsNO.get("submitJsonArray");
        List<HashMap<String, Object>> delListNO = (List<HashMap<String, Object>>) hashMapsNO.get("delList");
        params.add(new BasicNameValuePair("submitJsonArray", submitJsonArrayNO.toString()));
        try {
            reultString = HttpClientUtil.postRequest("/android.do?method=updateHeadmancheckNO", params,
                    MyStore.sessionID);
        } catch (TimeoutException e) {
            e.printStackTrace();
            HeadmancheckDetailActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(HeadmancheckDetailActivity.this, MyStore.TIMEOUTLOGIN, Toast.LENGTH_SHORT)
                            .show();
                }
            });
        }
        reultString = HttpClientUtil.callBackSuccOrFail(reultString, "resualt");
        if (HttpClientUtil.reSUCCorFAILE && delListNO.size() != 0) {
            MyStore.headManCheckList.removeAll(delListNO);
            headmancheckDetail.removeAll(delListNO);
        }
        final String MSG2 = reultString;
        HeadmancheckDetailActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(HeadmancheckDetailActivity.this, MSG2, Toast.LENGTH_SHORT).show();
            }
        });
        if (headmancheckDetail.size() == 0) {
            MyStore.deletBeanById(gd_no, "gd_no", MyStore.headManCheckFenzu);
            HeadmancheckDetailActivity.this.finish(); // Activity
        }
        ((MySimpleAdapter) getListAdapter()).notifyDataSetChanged();
        break;
    case R.id.menu_item_headmanchecklist_selectec_or_cancle:
        MyStore.selectORcancle(mResult, "mResult", headmancheckDetail);
        mResult = mResult == true ? false : true;
        ((MySimpleAdapter) getListAdapter()).notifyDataSetChanged();
        break;
    }
    return true;
}

From source file:com.tk.httpClientErp.headmancheck.Headmancheckqianshuzhi.java

/**
 * =====================================
 *///from   w ww .  j av  a  2  s  .c  om
@SuppressWarnings("unchecked")
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    super.onOptionsItemSelected(item);
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    String reultString = null;
    switch (item.getItemId()) {
    case R.id.menu_item_buslist_yes:
        HashMap<String, Object> hashMapsYES = MyStore.subAndDel(MyStore.headManCheckFenzu);
        List<JSONObject> submitJsonArrayYES = (List<JSONObject>) hashMapsYES.get("submitJsonArray");
        params.add(new BasicNameValuePair("submitJsonArray", submitJsonArrayYES.toString()));
        try {
            reultString = HttpClientUtil.postRequest("/android.do?method=qianshuzhi", params,
                    MyStore.sessionID);
        } catch (TimeoutException e) {
            e.printStackTrace();
            Headmancheckqianshuzhi.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(Headmancheckqianshuzhi.this, MyStore.TIMEOUTLOGIN, Toast.LENGTH_SHORT)
                            .show();
                }
            });
        }
        reultString = HttpClientUtil.callBackSuccOrFail(reultString, "resualt");
        final String MSG = reultString;
        Headmancheckqianshuzhi.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(Headmancheckqianshuzhi.this, MSG, Toast.LENGTH_SHORT).show();
            }
        });
    case R.id.menu_item_buslist_selectec_or_cancle:
        MyStore.selectORcancle(mResult, "mResult", MyStore.headManCheckFenzu);
        mResult = mResult == true ? false : true;
        ((MySimpleAdapter) getListAdapter()).notifyDataSetChanged();
        break;
    }
    return true;
}

From source file:org.openbaton.plugin.utils.PluginCaller.java

public Serializable executeRPC(String methodName, Collection<Serializable> args, Type returnType)
        throws IOException, InterruptedException, PluginException {

    Channel channel = connection.createChannel();
    String replyQueueName = channel.queueDeclare().getQueue();
    String exchange = "plugin-exchange";
    channel.queueBind(replyQueueName, exchange, replyQueueName);
    QueueingConsumer consumer = new QueueingConsumer(channel);
    String consumerTag = channel.basicConsume(replyQueueName, true, consumer);

    //Check if plugin is still up
    if (!RabbitManager.getQueues(brokerIp, username, password, managementPort).contains(pluginId))
        throw new PluginException("Plugin with id: " + pluginId + " not existing anymore...");

    String response;/*  w w w.  j av a 2 s.com*/
    String corrId = UUID.randomUUID().toString();
    PluginMessage pluginMessage = new PluginMessage();
    pluginMessage.setMethodName(methodName);
    pluginMessage.setParameters(args);
    String message = gson.toJson(pluginMessage);

    BasicProperties props = new Builder().correlationId(corrId).replyTo(replyQueueName).build();

    channel.basicPublish(exchange, pluginId, props, message.getBytes());

    if (returnType != null) {

        while (true) {
            Delivery delivery = consumer.nextDelivery();
            if (delivery.getProperties().getCorrelationId().equals(corrId)) {
                response = new String(delivery.getBody());
                log.trace("received: " + response);
                break;
            } else {
                log.error("Received Message with wrong correlation id");
                throw new PluginException(
                        "Received Message with wrong correlation id. This should not happen, if it does please call us.");
            }
        }

        channel.queueDelete(replyQueueName);
        try {
            channel.close();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
        JsonObject jsonObject = gson.fromJson(response, JsonObject.class);

        JsonElement exceptionJson = jsonObject.get("exception");
        if (exceptionJson == null) {
            JsonElement answerJson = jsonObject.get("answer");

            Serializable ret = null;

            if (answerJson.isJsonPrimitive()) {
                ret = gson.fromJson(answerJson.getAsJsonPrimitive(), returnType);
            } else if (answerJson.isJsonArray()) {
                ret = gson.fromJson(answerJson.getAsJsonArray(), returnType);
            } else
                ret = gson.fromJson(answerJson.getAsJsonObject(), returnType);

            log.trace("answer is: " + ret);
            return ret;
        } else {
            PluginException pluginException;
            try {
                pluginException = new PluginException(
                        gson.fromJson(exceptionJson.getAsJsonObject(), VimDriverException.class));
                log.debug("Got Vim Driver Exception with server: "
                        + ((VimDriverException) pluginException.getCause()).getServer());
            } catch (Exception ignored) {
                pluginException = new PluginException(
                        gson.fromJson(exceptionJson.getAsJsonObject(), Throwable.class));
            }
            throw pluginException;
        }
    } else
        return null;
}

From source file:org.apache.tinkerpop.gremlin.driver.util.ProfilingApplication.java

public long execute() throws Exception {
    final AtomicInteger tooSlow = new AtomicInteger(0);

    final Client client = cluster.connect();
    final String executionId = "[" + executionName + "]";
    try {/*from w ww .j  a  v  a  2 s . c o  m*/
        final CountDownLatch latch = new CountDownLatch(requests);
        client.init();

        final long start = System.nanoTime();
        IntStream.range(0, requests).forEach(i -> client.submitAsync(script).thenAcceptAsync(r -> {
            try {
                r.all().get(tooSlowThreshold, TimeUnit.MILLISECONDS);
            } catch (TimeoutException ex) {
                tooSlow.incrementAndGet();
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                latch.countDown();
            }
        }, executor));

        // finish once all requests are accounted for
        latch.await();

        final long end = System.nanoTime();
        final long total = end - start;
        final double totalSeconds = total / 1000000000d;
        final long requestCount = requests;
        final long reqSec = Math.round(requestCount / totalSeconds);
        System.out.println(String.format(
                StringUtils.rightPad(executionId, 10)
                        + " requests: %s | time(s): %s | req/sec: %s | too slow: %s",
                requestCount, StringUtils.rightPad(String.valueOf(totalSeconds), 14),
                StringUtils.rightPad(String.valueOf(reqSec), 7), tooSlow.get()));
        return reqSec;
    } catch (Exception ex) {
        ex.printStackTrace();
        throw new RuntimeException(ex);
    } finally {
        client.close();
    }
}

From source file:at.alladin.rmbt.client.v2.task.TracerouteTask.java

/**
 * /*  w w  w  . j a  v a  2s .  c o  m*/
 */
public QoSTestResult call() throws Exception {
    final QoSTestResult testResult = initQoSTestResult(QoSTestResultEnum.TRACEROUTE);

    testResult.getResultMap().put(RESULT_HOST, host);
    testResult.getResultMap().put(RESULT_TIMEOUT, timeout);
    testResult.getResultMap().put(RESULT_MAX_HOPS, maxHops);

    try {
        onStart(testResult);
        final TracerouteService pingTool = getQoSTest().getTestSettings().getTracerouteServiceClazz()
                .newInstance();
        pingTool.setHost(host);
        pingTool.setMaxHops(maxHops);

        final Future<List<HopDetail>> traceFuture = RMBTClient.getCommonThreadPool().submit(pingTool);
        try {
            final List<HopDetail> pingDetailList = traceFuture.get(timeout, TimeUnit.NANOSECONDS);
            if (!pingTool.hasMaxHopsExceeded()) {
                testResult.getResultMap().put(RESULT_STATUS, "OK");
                testResult.getResultMap().put(RESULT_HOPS, pingDetailList.size());
            } else {
                testResult.getResultMap().put(RESULT_STATUS, "MAX_HOPS_EXCEEDED");
                testResult.getResultMap().put(RESULT_HOPS, maxHops);
            }
            JSONArray resultArray = new JSONArray();
            for (final HopDetail p : pingDetailList) {
                JSONObject json = p.toJson();
                if (json != null) {
                    resultArray.put(json);
                }
            }
            testResult.getResultMap().put(RESULT_DETAILS, resultArray);
        } catch (TimeoutException e) {
            testResult.getResultMap().put(RESULT_STATUS, "TIMEOUT");
        }
    } catch (Exception e) {
        e.printStackTrace();
        testResult.getResultMap().put(RESULT_STATUS, "ERROR");
    } finally {
        onEnd(testResult);
    }

    return testResult;
}

From source file:com.mrfeinberg.translation.AbstractTranslationService.java

public Runnable translate(final String phrase, final LanguagePair lp, final TranslationListener listener) {
    final Language b = lp.b();

    final HttpClient httpClient = new HttpClient();
    if (proxyPrefs.getUseProxy()) {
        httpClient.getHostConfiguration().setProxy(proxyPrefs.getProxyHost(), proxyPrefs.getProxyPort());
    }// w w  w  .j av  a  2  s  .c om

    final HttpMethod httpMethod = getHttpMethod(phrase, lp);
    final Callable<String> callable = new Callable<String>() {
        public String call() throws Exception {
            int result = httpClient.executeMethod(httpMethod);
            if (result != 200) {
                throw new Exception("Got " + result + " status for " + httpMethod.getURI());
            }
            final BufferedReader in = new BufferedReader(
                    new InputStreamReader(httpMethod.getResponseBodyAsStream(), "utf8"));
            try {
                final StringBuilder sb = new StringBuilder();
                String line;
                while ((line = in.readLine()) != null)
                    sb.append(line);
                return sb.toString();
            } finally {
                in.close();
                httpMethod.releaseConnection();
            }
        }
    };
    final FutureTask<String> tc = new FutureTask<String>(callable);
    return new Runnable() {
        public void run() {
            try {
                executor.execute(tc);
                final String result = tc.get(timeout, TimeUnit.MILLISECONDS);
                String found = findTranslatedText(result);
                if (found == null) {
                    listener.error("Cannot find translated text in result.");
                } else {
                    found = found.replaceAll("\\s+", " ");
                    listener.result(found, b);
                }
            } catch (final TimeoutException e) {
                listener.timedOut();
            } catch (final InterruptedException e) {
                listener.cancelled();
            } catch (final Exception e) {
                e.printStackTrace();
                listener.error(e.toString());
            }
        }
    };
}