Example usage for java.io InterruptedIOException printStackTrace

List of usage examples for java.io InterruptedIOException printStackTrace

Introduction

In this page you can find the example usage for java.io InterruptedIOException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

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

Usage

From source file:framework.httpclient.nio.NHttpClient.java

public static void main(String[] args) throws Exception {
    // Create HTTP protocol processing chain
    HttpProcessor httpproc = HttpProcessorBuilder.create()
            // Use standard client-side protocol interceptors
            .add(new RequestContent()).add(new RequestTargetHost()).add(new RequestConnControl())
            .add(new RequestUserAgent("LinkedHashSetVsTreeSet/1.1")).add(new RequestExpectContinue(true))
            .build();/*  ww  w.  j ava  2  s.c  om*/

    // Create client-side HTTP protocol handler
    HttpAsyncRequestExecutor protocolHandler = new HttpAsyncRequestExecutor();

    // Create client-side I/O event dispatch
    //   IO 
    final IOEventDispatch ioEventDispatch = new DefaultHttpClientIODispatch(protocolHandler,
            ConnectionConfig.DEFAULT);

    // Create client-side I/O reactor
    //   IO reactor
    final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor();

    // Create HTTP connection pool
    //  HTTP 
    BasicNIOConnPool pool = new BasicNIOConnPool(ioReactor, ConnectionConfig.DEFAULT);

    // Limit total number of connections to just two
    pool.setDefaultMaxPerRoute(2);
    pool.setMaxTotal(2);

    // Run the I/O reactor in a separate thread
    Thread t = new Thread(new Runnable() {

        public void run() {
            try {
                // Ready to go!
                ioReactor.execute(ioEventDispatch);
            } catch (InterruptedIOException ex) {
                System.err.println("Interrupted");
            } catch (IOException e) {
                System.err.println("I/O error: " + e.getMessage());
            }
            System.out.println("Shutdown");
        }

    });
    // Start the client thread
    t.start();

    // Create HTTP requester
    //  HTTP 
    HttpAsyncRequester requester = new HttpAsyncRequester(httpproc);

    // Execute HTTP GETs to the following hosts and
    HttpHost[] targets = new HttpHost[] { new HttpHost("www.baidu.org", -1, "https"),
            //            new HttpHost("www.zhihu.com", -1, "https"),
            new HttpHost("www.bilibili.com", -1, "https") };

    final CountDownLatch latch = new CountDownLatch(targets.length);

    for (final HttpHost target : targets) {
        BasicHttpRequest request = new BasicHttpRequest("GET", "/");
        HttpCoreContext coreContext = HttpCoreContext.create();
        requester.execute(new BasicAsyncRequestProducer(target, request), new BasicAsyncResponseConsumer(),
                pool, coreContext,
                // Handle HTTP response from a callback
                new FutureCallback<HttpResponse>() {

                    public void completed(final HttpResponse response) {
                        latch.countDown();
                        System.out.println(target + "->" + response.getStatusLine());
                    }

                    public void failed(final Exception ex) {
                        latch.countDown();
                        System.err.println(target + "->" + ex);
                        ex.printStackTrace();
                    }

                    public void cancelled() {
                        latch.countDown();
                        System.out.println(target + " cancelled");
                    }

                });
    }
    latch.await();
    System.out.println("Shutting down I/O reactor");
    ioReactor.shutdown();
    System.out.println("Done");
}

From source file:com.ultrahook.test.utils.TestServer.java

public void start() throws Exception {
    HttpProcessor httpproc = HttpProcessorBuilder.create().add(new ResponseDate())
            .add(new ResponseServer("Test/1.1")).add(new ResponseContent()).add(new ResponseConnControl())
            .build();//from   w  ww.j av  a  2  s  . c  o m
    UriHttpAsyncRequestHandlerMapper reqistry = new UriHttpAsyncRequestHandlerMapper();
    reqistry.register("*", new HttpHandler());
    HttpAsyncService protocolHandler = new HttpAsyncService(httpproc, reqistry);
    NHttpConnectionFactory<DefaultNHttpServerConnection> connFactory;
    connFactory = new DefaultNHttpServerConnectionFactory(ConnectionConfig.DEFAULT);
    final IOEventDispatch ioEventDispatch = new DefaultHttpServerIODispatch(protocolHandler, connFactory);
    IOReactorConfig config = IOReactorConfig.custom().setIoThreadCount(1).setSoTimeout(3000)
            .setConnectTimeout(3000).build();
    ioReactor = new DefaultListeningIOReactor(config);
    ioReactor.listen(new InetSocketAddress(port));
    new Thread() {
        public void run() {
            try {
                ioReactor.execute(ioEventDispatch);
            } catch (InterruptedIOException e) {
                e.printStackTrace();
            } catch (IOReactorException e) {
                e.printStackTrace();
            }
        };

    }.start();
}

From source file:cw.kop.autobackground.files.DownloadThread.java

private Bitmap getImage(String url) {

    if (Patterns.WEB_URL.matcher(url).matches()) {
        try {/*from   w w  w . j ava2  s  . com*/
            int minWidth = AppSettings.getImageWidth();
            int minHeight = AppSettings.getImageHeight();
            System.gc();
            URL imageUrl = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) imageUrl.openConnection();
            connection.connect();
            InputStream input = connection.getInputStream();

            if (!connection.getHeaderField("Content-Type").startsWith("image/")
                    && !AppSettings.forceDownload()) {
                Log.i(TAG, "Not an image: " + url);
                return null;
            }

            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inPreferredConfig = Bitmap.Config.ARGB_8888;
            options.inJustDecodeBounds = true;
            if (!AppSettings.useHighQuality()) {
                options.inPreferredConfig = Bitmap.Config.RGB_565;
            }

            BitmapFactory.decodeStream(input, null, options);

            input.close();

            int bitWidth = options.outWidth;
            int bitHeight = options.outHeight;
            options.inJustDecodeBounds = false;

            Log.i(TAG, "bitWidth: " + bitWidth + " bitHeight: " + bitHeight);

            if (bitWidth + 10 < minWidth || bitHeight + 10 < minHeight) {
                return null;
            }

            int sampleSize = 1;

            if (!AppSettings.useFullResolution()) {

                if (bitHeight > minHeight || bitWidth > minWidth) {

                    final int halfHeight = bitHeight / 2;
                    final int halfWidth = bitWidth / 2;
                    while ((halfHeight / sampleSize) > minHeight && (halfWidth / sampleSize) > minWidth) {
                        sampleSize *= 2;
                    }
                }
            }

            options.inSampleSize = sampleSize;

            connection = (HttpURLConnection) imageUrl.openConnection();
            connection.setConnectTimeout(5000);
            connection.setConnectTimeout(30000);
            connection.connect();
            input = connection.getInputStream();

            Bitmap bitmap = BitmapFactory.decodeStream(input, null, options);

            if (bitmap == null) {
                Log.i(TAG, "Null bitmap");
                return null;
            }
            return bitmap;

        } catch (InterruptedIOException e) {
            this.interrupt();
            Log.i(TAG, "Interrupted");
        } catch (OutOfMemoryError | IOException e) {
            interrupt();
            e.printStackTrace();
        }
    }
    Log.i(TAG, "Possible malformed URL");
    return null;
}

From source file:org.apache.hadoop.hbase.client.SpeculativeMutater.java

public Boolean mutate(final long waitToSendFailover, final long waitToSendFailoverWithException,
        final HBaseTableFunction<Void> function, final HTableInterface primaryTable,
        final Collection<HTableInterface> failoverTables, final AtomicLong lastPrimaryFail,
        final int waitTimeFromLastPrimaryFail) {
    ExecutorCompletionService<Boolean> exeS = new ExecutorCompletionService<Boolean>(exe);

    ArrayList<Callable<Boolean>> callables = new ArrayList<Callable<Boolean>>();

    final AtomicBoolean isPrimarySuccess = new AtomicBoolean(false);
    final long startTime = System.currentTimeMillis();
    final long lastPrimaryFinalFail = lastPrimaryFail.get();

    if (System.currentTimeMillis() - lastPrimaryFinalFail > 5000) {
        callables.add(new Callable<Boolean>() {
            public Boolean call() throws Exception {
                try {
                    LOG.info(" --- CallingPrimary.1:" + isPrimarySuccess.get() + ", "
                            + (System.currentTimeMillis() - startTime));
                    function.call(primaryTable);
                    LOG.info(" --- CallingPrimary.2:" + isPrimarySuccess.get() + ", "
                            + (System.currentTimeMillis() - startTime));
                    isPrimarySuccess.set(true);
                    return true;
                } catch (java.io.InterruptedIOException e) {
                    Thread.currentThread().interrupt();
                } catch (Exception e) {
                    lastPrimaryFail.set(System.currentTimeMillis());
                    Thread.currentThread().interrupt();
                }//w ww .j  a  v  a2 s.  c o m
                return null;
            }
        });
    }

    for (final HTableInterface failoverTable : failoverTables) {
        callables.add(new Callable<Boolean>() {

            public Boolean call() throws Exception {
                long waitToRequest = (System.currentTimeMillis() - lastPrimaryFinalFail > 5000)
                        ? waitToSendFailover - (System.currentTimeMillis() - startTime)
                        : waitToSendFailoverWithException - (System.currentTimeMillis() - startTime);

                LOG.info(" --- waitToRequest:" + waitToRequest + ","
                        + (System.currentTimeMillis() - lastPrimaryFinalFail) + ","
                        + (waitToSendFailover - (System.currentTimeMillis() - startTime)) + ","
                        + (waitToSendFailoverWithException - (System.currentTimeMillis() - startTime)));

                if (waitToRequest > 0) {
                    Thread.sleep(waitToRequest);
                }
                LOG.info(" --- isPrimarySuccess.get():" + isPrimarySuccess.get());
                if (isPrimarySuccess.get() == false) {
                    LOG.info(" --- CallingFailOver.1:" + isPrimarySuccess.get() + ", "
                            + (System.currentTimeMillis() - startTime));
                    function.call(failoverTable);
                    LOG.info(" --- CallingFailOver.2:" + isPrimarySuccess.get() + ", "
                            + (System.currentTimeMillis() - startTime));
                }

                return false;
            }
        });
    }
    try {

        for (Callable<Boolean> call : callables) {
            exeS.submit(call);
        }
        Boolean result = exeS.take().get();
        return result;
    } catch (InterruptedException e) {
        e.printStackTrace();
        LOG.error(e);
    } catch (ExecutionException e) {
        e.printStackTrace();
        LOG.error(e);
    }
    return null;
}

From source file:org.apache.hadoop.hbase.client.SpeculativeRequester.java

public ResultWrapper<T> request(final HBaseTableFunction<T> function, final HTableInterface primaryTable,
        final Collection<HTableInterface> failoverTables) {

    ExecutorCompletionService<ResultWrapper<T>> exeS = new ExecutorCompletionService<ResultWrapper<T>>(exe);

    final AtomicBoolean isPrimarySuccess = new AtomicBoolean(false);
    final long startTime = System.currentTimeMillis();

    ArrayList<Callable<ResultWrapper<T>>> callables = new ArrayList<Callable<ResultWrapper<T>>>();

    if (System.currentTimeMillis() - lastPrimaryFail.get() > waitTimeFromLastPrimaryFail) {
        callables.add(new Callable<ResultWrapper<T>>() {
            public ResultWrapper<T> call() throws Exception {
                try {
                    T t = function.call(primaryTable);
                    isPrimarySuccess.set(true);
                    return new ResultWrapper(true, t);
                } catch (java.io.InterruptedIOException e) {
                    Thread.currentThread().interrupt();
                } catch (Exception e) {
                    lastPrimaryFail.set(System.currentTimeMillis());
                    Thread.currentThread().interrupt();
                }/*from   w  w w.  j  a v a  2 s  . com*/
                return null;
            }
        });
    }

    for (final HTableInterface failoverTable : failoverTables) {
        callables.add(new Callable<ResultWrapper<T>>() {

            public ResultWrapper<T> call() throws Exception {

                long waitToRequest = (System.currentTimeMillis()
                        - lastPrimaryFail.get() > waitTimeFromLastPrimaryFail)
                                ? waitTimeBeforeRequestingFailover - (System.currentTimeMillis() - startTime)
                                : 0;

                if (waitToRequest > 0) {
                    Thread.sleep(waitToRequest);
                }
                if (isPrimarySuccess.get() == false) {
                    T t = function.call(failoverTable);

                    long waitToAccept = (System.currentTimeMillis()
                            - lastPrimaryFail.get() > waitTimeFromLastPrimaryFail)
                                    ? waitTimeBeforeAcceptingResults - (System.currentTimeMillis() - startTime)
                                    : 0;
                    if (isPrimarySuccess.get() == false) {
                        if (waitToAccept > 0) {
                            Thread.sleep(waitToAccept);
                        }
                    }

                    return new ResultWrapper(false, t);
                } else {
                    throw new RuntimeException("Not needed");
                }

            }
        });
    }
    try {

        //ResultWrapper<T> t = exe.invokeAny(callables);
        for (Callable<ResultWrapper<T>> call : callables) {
            exeS.submit(call);
        }

        ResultWrapper<T> result = exeS.take().get();
        //exe.shutdownNow();

        return result;
    } catch (InterruptedException e) {
        e.printStackTrace();
        LOG.error(e);
    } catch (ExecutionException e) {
        e.printStackTrace();
        LOG.error(e);
    }
    return null;

}