Example usage for java.net SocketTimeoutException SocketTimeoutException

List of usage examples for java.net SocketTimeoutException SocketTimeoutException

Introduction

In this page you can find the example usage for java.net SocketTimeoutException SocketTimeoutException.

Prototype

public SocketTimeoutException(String msg) 

Source Link

Document

Constructs a new SocketTimeoutException with a detail message.

Usage

From source file:com.taobao.adfs.distributed.rpc.Client.java

/**
 * Take an IOException and the address we were trying to connect to and return an IOException with the input exception
 * as the cause. The new exception provides the stack trace of the place where the exception is thrown and some extra
 * diagnostics information. If the exception is ConnectException or SocketTimeoutException, return a new one of the
 * same type; Otherwise return an IOException.
 * // w  ww . java 2 s .  co m
 * @param addr
 *          target address
 * @param exception
 *          the relevant exception
 * @return an exception to throw
 */
private IOException wrapException(InetSocketAddress addr, IOException exception) {
    if (exception instanceof ConnectException) {
        // connection refused; include the host:port in the error
        return (ConnectException) new ConnectException(
                "Call to " + addr + " failed on connection exception: " + exception).initCause(exception);
    } else if (exception instanceof SocketTimeoutException) {
        return (SocketTimeoutException) new SocketTimeoutException(
                "Call to " + addr + " failed on socket timeout exception: " + exception).initCause(exception);
    } else {
        return (IOException) new IOException("Call to " + addr + " failed on local exception: " + exception)
                .initCause(exception);

    }
}

From source file:org.esigate.DriverTest.java

/**
 * 0000141: Socket read timeout causes a stacktrace and may leak connection
 * http://www.esigate.org/mantisbt/view.php?id=141
 * /*ww  w . ja va  2 s .c o  m*/
 * The warning will not be fixed in HttpClient but the leak is fixed.
 * 
 * @throws Exception
 */
public void testSocketReadTimeoutWithCacheAndGzipDoesNotLeak() throws Exception {
    Properties properties = new Properties();
    properties.put(Parameters.REMOTE_URL_BASE, "http://localhost/");
    properties.put(Parameters.USE_CACHE, "true");

    BasicHttpResponse response = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_OK,
            "Ok");
    response.addHeader("Date", DateUtils.formatDate(new Date()));
    response.addHeader("Cache-control", "public, max-age=1000");
    response.addHeader("Content-Encoding", "gzip");
    response.setEntity(new InputStreamEntity(new InputStream() {
        @Override
        public int read() throws IOException {
            throw new SocketTimeoutException("Read timed out");
        }
    }, 1000));
    mockConnectionManager.setResponse(response);

    Driver driver = createMockDriver(properties, mockConnectionManager);

    request = TestUtils.createIncomingRequest("http://test.mydomain.fr/");
    request.addHeader("Accept-Encoding", "gzip, deflate");

    try {
        driver.proxy("/", request.build());
        fail("We should have had a SocketTimeoutException");
    } catch (HttpErrorPage e) {
        // That is what we expect
        assertEquals(HttpStatus.SC_GATEWAY_TIMEOUT, e.getHttpResponse().getStatusLine().getStatusCode());
    }
    assertFalse("All the connections should have been closed", mockConnectionManager.isOpen());
}

From source file:ipc.Client.java

/**
 * Take an IOException and the address we were trying to connect to
 * and return an IOException with the input exception as the cause.
 * The new exception provides the stack trace of the place where 
 * the exception is thrown and some extra diagnostics information.
 * If the exception is ConnectException or SocketTimeoutException, 
 * return a new one of the same type; Otherwise return an IOException.
 * /*  www .j  ava2 s .  c  om*/
 * @param addr target address
 * @param exception the relevant exception
 * @return an exception to throw
 */
private IOException wrapException(InetSocketAddress addr, IOException exception) {
    if (exception instanceof ConnectException) {
        //connection refused; include the host:port in the error
        return (ConnectException) new ConnectException(
                "Call to " + addr + " failed on connection exception: " + exception).initCause(exception);
    } else if (exception instanceof SocketTimeoutException) {
        return (SocketTimeoutException) new SocketTimeoutException(
                "Call to " + addr + " failed on socket timeout exception: " + exception).initCause(exception);
    } else {
        return (IOException) new IOException("Call to " + addr + " failed on local exception: " + exception)
                .initCause(exception);

    }
}

From source file:com.hortonworks.hbase.replication.bridge.HBaseClient.java

/**
 * Take an IOException and the address we were trying to connect to
 * and return an IOException with the input exception as the cause.
 * The new exception provides the stack trace of the place where
 * the exception is thrown and some extra diagnostics information.
 * If the exception is ConnectException or SocketTimeoutException,
 * return a new one of the same type; Otherwise return an IOException.
 *
 * @param addr target address//from   w w w.  j a  v  a 2  s. c  o  m
 * @param exception the relevant exception
 * @return an exception to throw
 */
@SuppressWarnings({ "ThrowableInstanceNeverThrown" })
protected IOException wrapException(InetSocketAddress addr, IOException exception) {
    if (exception instanceof ConnectException) {
        //connection refused; include the host:port in the error
        return (ConnectException) new ConnectException(
                "Call to " + addr + " failed on connection exception: " + exception).initCause(exception);
    } else if (exception instanceof SocketTimeoutException) {
        return (SocketTimeoutException) new SocketTimeoutException(
                "Call to " + addr + " failed on socket timeout exception: " + exception).initCause(exception);
    } else {
        return (IOException) new IOException("Call to " + addr + " failed on local exception: " + exception)
                .initCause(exception);

    }
}

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

/**
 * Retries if invocation fails./*from  w w w  .  ja v a  2  s . c om*/
 * @param callTimeout Timeout for this call
 * @param callable The {@link RetryingCallable} to run.
 * @return an object of type T
 * @throws IOException if a remote or network exception occurs
 * @throws RuntimeException other unspecified error
 */
public T callWithRetries(RetryingCallable<T> callable, int callTimeout) throws IOException, RuntimeException {
    List<RetriesExhaustedException.ThrowableWithExtraContext> exceptions = new ArrayList<RetriesExhaustedException.ThrowableWithExtraContext>();
    this.globalStartTime = EnvironmentEdgeManager.currentTimeMillis();
    for (int tries = 0;; tries++) {
        long expectedSleep;
        try {
            callable.prepare(tries != 0); // if called with false, check table status on ZK
            return callable.call(getRemainingTime(callTimeout));
        } catch (Throwable t) {
            ExceptionUtil.rethrowIfInterrupt(t);
            if (LOG.isTraceEnabled()) {
                LOG.trace(
                        "Call exception, tries=" + tries + ", retries=" + retries + ", retryTime="
                                + (EnvironmentEdgeManager.currentTimeMillis() - this.globalStartTime) + "ms",
                        t);
            }
            // translateException throws exception when should not retry: i.e. when request is bad.
            t = translateException(t);
            callable.throwable(t, retries != 1);
            RetriesExhaustedException.ThrowableWithExtraContext qt = new RetriesExhaustedException.ThrowableWithExtraContext(
                    t, EnvironmentEdgeManager.currentTimeMillis(), toString());
            exceptions.add(qt);
            if (tries >= retries - 1) {
                throw new RetriesExhaustedException(tries, exceptions);
            }
            // If the server is dead, we need to wait a little before retrying, to give
            //  a chance to the regions to be
            // tries hasn't been bumped up yet so we use "tries + 1" to get right pause time
            expectedSleep = callable.sleep(pause, tries + 1);

            // If, after the planned sleep, there won't be enough time left, we stop now.
            long duration = singleCallDuration(expectedSleep);
            if (duration > callTimeout) {
                String msg = "callTimeout=" + callTimeout + ", callDuration=" + duration + ": "
                        + callable.getExceptionMessageAdditionalDetail();
                throw (SocketTimeoutException) (new SocketTimeoutException(msg).initCause(t));
            }
        }
        try {
            Thread.sleep(expectedSleep);
        } catch (InterruptedException e) {
            throw new InterruptedIOException("Interrupted after " + tries + " tries  on " + retries);
        }
    }
}

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

@Override
public T callWithRetries(RetryingCallable<T> callable, int callTimeout) throws IOException, RuntimeException {
    List<RetriesExhaustedException.ThrowableWithExtraContext> exceptions = new ArrayList<RetriesExhaustedException.ThrowableWithExtraContext>();
    this.globalStartTime = EnvironmentEdgeManager.currentTime();
    context.clear();/*from   w ww .  j  a  v a2 s . c  o  m*/
    for (int tries = 0;; tries++) {
        long expectedSleep;
        try {
            callable.prepare(tries != 0); // if called with false, check table status on ZK
            interceptor.intercept(context.prepare(callable, tries));
            return callable.call(getRemainingTime(callTimeout));
        } catch (PreemptiveFastFailException e) {
            throw e;
        } catch (Throwable t) {
            ExceptionUtil.rethrowIfInterrupt(t);
            if (tries > startLogErrorsCnt) {
                LOG.info("Call exception, tries=" + tries + ", retries=" + retries + ", started="
                        + (EnvironmentEdgeManager.currentTime() - this.globalStartTime) + " ms ago, "
                        + "cancelled=" + cancelled.get() + ", msg="
                        + callable.getExceptionMessageAdditionalDetail());
            }

            // translateException throws exception when should not retry: i.e. when request is bad.
            interceptor.handleFailure(context, t);
            t = translateException(t);
            callable.throwable(t, retries != 1);
            RetriesExhaustedException.ThrowableWithExtraContext qt = new RetriesExhaustedException.ThrowableWithExtraContext(
                    t, EnvironmentEdgeManager.currentTime(), toString());
            exceptions.add(qt);
            if (tries >= retries - 1) {
                throw new RetriesExhaustedException(tries, exceptions);
            }
            // If the server is dead, we need to wait a little before retrying, to give
            //  a chance to the regions to be
            // tries hasn't been bumped up yet so we use "tries + 1" to get right pause time
            expectedSleep = callable.sleep(pause, tries + 1);

            // If, after the planned sleep, there won't be enough time left, we stop now.
            long duration = singleCallDuration(expectedSleep);
            if (duration > callTimeout) {
                String msg = "callTimeout=" + callTimeout + ", callDuration=" + duration + ": "
                        + callable.getExceptionMessageAdditionalDetail();
                throw (SocketTimeoutException) (new SocketTimeoutException(msg).initCause(t));
            }
        } finally {
            interceptor.updateFailureInfo(context);
        }
        try {
            if (expectedSleep > 0) {
                synchronized (cancelled) {
                    if (cancelled.get())
                        return null;
                    cancelled.wait(expectedSleep);
                }
            }
            if (cancelled.get())
                return null;
        } catch (InterruptedException e) {
            throw new InterruptedIOException("Interrupted after " + tries + " tries  on " + retries);
        }
    }
}

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

/**
 * Run this instance with retries, timed waits,
 * and refinds of missing regions./*from   w ww . ja  v  a 2  s.c  o  m*/
 *
 * @return an object of type T
 * @throws IOException if a remote or network exception occurs
 * @throws RuntimeException other unspecified error
 */
public T withRetries() throws IOException, RuntimeException {
    Configuration c = getConnection().getConfiguration();
    final long pause = c.getLong(HConstants.HBASE_CLIENT_PAUSE, HConstants.DEFAULT_HBASE_CLIENT_PAUSE);
    final int numRetries = c.getInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER,
            HConstants.DEFAULT_HBASE_CLIENT_RETRIES_NUMBER);
    List<RetriesExhaustedException.ThrowableWithExtraContext> exceptions = new ArrayList<RetriesExhaustedException.ThrowableWithExtraContext>();
    this.globalStartTime = EnvironmentEdgeManager.currentTimeMillis();
    for (int tries = 0;; tries++) {
        long expectedSleep = 0;
        try {
            beforeCall();
            prepare(tries != 0); // if called with false, check table status on ZK
            return call();
        } catch (Throwable t) {
            LOG.warn("Call exception, tries=" + tries + ", numRetries=" + numRetries, t);

            t = translateException(t);
            // translateException throws an exception when we should not retry, i.e. when it's the
            //  request that is bad.

            if (t instanceof SocketTimeoutException || t instanceof ConnectException
                    || t instanceof RetriesExhaustedException
                    || (location != null && getConnection().isDeadServer(location.getServerName()))) {
                // if thrown these exceptions, we clear all the cache entries that
                // map to that slow/dead server; otherwise, let cache miss and ask
                // .META. again to find the new location
                getConnection().clearCaches(location.getServerName());
            } else if (t instanceof NotServingRegionException && numRetries == 1) {
                // Purge cache entries for this specific region from META cache
                // since we don't call connect(true) when number of retries is 1.
                getConnection().deleteCachedRegionLocation(location);
            }

            RetriesExhaustedException.ThrowableWithExtraContext qt = new RetriesExhaustedException.ThrowableWithExtraContext(
                    t, EnvironmentEdgeManager.currentTimeMillis(), toString());
            exceptions.add(qt);
            if (tries >= numRetries - 1) {
                throw new RetriesExhaustedException(tries, exceptions);
            }

            // If the server is dead, we need to wait a little before retrying, to give
            //  a chance to the regions to be
            // tries hasn't been bumped up yet so we use "tries + 1" to get right pause time
            expectedSleep = ConnectionUtils.getPauseTime(pause, tries + 1);
            if (expectedSleep < MIN_WAIT_DEAD_SERVER
                    && (location == null || getConnection().isDeadServer(location.getServerName()))) {
                expectedSleep = ConnectionUtils.addJitter(MIN_WAIT_DEAD_SERVER, 0.10f);
            }

            // If, after the planned sleep, there won't be enough time left, we stop now.
            long duration = singleCallDuration(expectedSleep);
            if (duration > this.callTimeout) {
                throw (SocketTimeoutException) new SocketTimeoutException(
                        "Call to access row '" + Bytes.toString(row) + "' on table '"
                                + Bytes.toString(tableName) + "' failed on timeout. " + " callTimeout="
                                + this.callTimeout + ", callDuration=" + duration).initCause(t);
            }
        } finally {
            afterCall();
        }
        try {
            Thread.sleep(expectedSleep);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new IOException("Interrupted after " + tries + " tries  on " + numRetries, e);
        }
    }
}

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

@Test
public void testExceptionsIdentifiedByInterceptor() throws IOException {
    Throwable[] networkexceptions = new Throwable[] { new ConnectException("Mary is unwell"),
            new SocketTimeoutException("Mike is too late"), new ClosedChannelException(),
            new SyncFailedException("Dave is not on the same page"), new TimeoutException("Mike is late again"),
            new EOFException("This is the end... "), new ConnectionClosingException("Its closing") };
    final String INDUCED = "Induced";
    Throwable[] nonNetworkExceptions = new Throwable[] { new IOException("Bob died"),
            new RemoteException("Bob's cousin died", null), new NoSuchMethodError(INDUCED),
            new NullPointerException(INDUCED), new DoNotRetryIOException(INDUCED), new Error(INDUCED) };

    Configuration conf = HBaseConfiguration.create();
    long CLEANUP_TIMEOUT = 0;
    long FAST_FAIL_THRESHOLD = 1000000;
    conf.setBoolean(HConstants.HBASE_CLIENT_FAST_FAIL_MODE_ENABLED, true);
    conf.setLong(HConstants.HBASE_CLIENT_FAST_FAIL_CLEANUP_MS_DURATION_MS, CLEANUP_TIMEOUT);
    conf.setLong(HConstants.HBASE_CLIENT_FAST_FAIL_THREASHOLD_MS, FAST_FAIL_THRESHOLD);
    for (Throwable e : networkexceptions) {
        PreemptiveFastFailInterceptor interceptor = TestFastFailWithoutTestUtil
                .createPreemptiveInterceptor(conf);
        FastFailInterceptorContext context = (FastFailInterceptorContext) interceptor.createEmptyContext();

        RetryingCallable<?> callable = getDummyRetryingCallable(getSomeServerName());
        context.prepare(callable, 0);//from w w  w .ja va  2  s .  c o  m
        interceptor.intercept(context);
        interceptor.handleFailure(context, e);
        interceptor.updateFailureInfo(context);
        assertTrue("The call shouldn't have been successful if there was a ConnectException",
                context.getCouldNotCommunicateWithServer().booleanValue());
    }
    for (Throwable e : nonNetworkExceptions) {
        try {
            PreemptiveFastFailInterceptor interceptor = TestFastFailWithoutTestUtil
                    .createPreemptiveInterceptor(conf);
            FastFailInterceptorContext context = (FastFailInterceptorContext) interceptor.createEmptyContext();

            RetryingCallable<?> callable = getDummyRetryingCallable(getSomeServerName());
            context.prepare(callable, 0);
            interceptor.intercept(context);
            interceptor.handleFailure(context, e);
            interceptor.updateFailureInfo(context);
            assertFalse("The call shouldn't have been successful if there was a ConnectException",
                    context.getCouldNotCommunicateWithServer().booleanValue());
        } catch (NoSuchMethodError t) {
            assertTrue("Exception not induced", t.getMessage().contains(INDUCED));
        } catch (NullPointerException t) {
            assertTrue("Exception not induced", t.getMessage().contains(INDUCED));
        } catch (DoNotRetryIOException t) {
            assertTrue("Exception not induced", t.getMessage().contains(INDUCED));
        } catch (Error t) {
            assertTrue("Exception not induced", t.getMessage().contains(INDUCED));
        }
    }
}

From source file:org.apache.hadoop.hbase.ipc.RpcClient.java

/**
 * Take an IOException and the address we were trying to connect to
 * and return an IOException with the input exception as the cause.
 * The new exception provides the stack trace of the place where
 * the exception is thrown and some extra diagnostics information.
 * If the exception is ConnectException or SocketTimeoutException,
 * return a new one of the same type; Otherwise return an IOException.
 *
 * @param addr target address//from   www  .jav a2 s .  c om
 * @param exception the relevant exception
 * @return an exception to throw
 */
protected IOException wrapException(InetSocketAddress addr, IOException exception) {
    if (exception instanceof ConnectException) {
        //connection refused; include the host:port in the error
        return (ConnectException) new ConnectException(
                "Call to " + addr + " failed on connection exception: " + exception).initCause(exception);
    } else if (exception instanceof SocketTimeoutException) {
        return (SocketTimeoutException) new SocketTimeoutException(
                "Call to " + addr + " failed because " + exception).initCause(exception);
    } else {
        return (IOException) new IOException("Call to " + addr + " failed on local exception: " + exception)
                .initCause(exception);
    }
}

From source file:org.apache.hadoop.hbase.ipc.RpcClientImpl.java

/**
 * Take an IOException and the address we were trying to connect to
 * and return an IOException with the input exception as the cause.
 * The new exception provides the stack trace of the place where
 * the exception is thrown and some extra diagnostics information.
 * If the exception is ConnectException or SocketTimeoutException,
 * return a new one of the same type; Otherwise return an IOException.
 *
 * @param addr target address/*www  . ja  v  a2 s.c o m*/
 * @param exception the relevant exception
 * @return an exception to throw
 */
protected IOException wrapException(InetSocketAddress addr, IOException exception) {
    if (exception instanceof ConnectException) {
        //connection refused; include the host:port in the error
        return (ConnectException) new ConnectException(
                "Call to " + addr + " failed on connection exception: " + exception).initCause(exception);
    } else if (exception instanceof SocketTimeoutException) {
        return (SocketTimeoutException) new SocketTimeoutException(
                "Call to " + addr + " failed because " + exception).initCause(exception);
    } else if (exception instanceof ConnectionClosingException) {
        return (ConnectionClosingException) new ConnectionClosingException(
                "Call to " + addr + " failed on local exception: " + exception).initCause(exception);
    } else {
        return (IOException) new IOException("Call to " + addr + " failed on local exception: " + exception)
                .initCause(exception);
    }
}