Search in sources :

Example 96 with SocketTimeoutException

use of java.net.SocketTimeoutException in project camel by apache.

the class NettyRedeliveryTest method createServerSocket.

private int createServerSocket(int port) throws IOException {
    final ServerSocket listen = new ServerSocket(port);
    listen.setSoTimeout(100);
    listener.execute(new Runnable() {

        private ExecutorService pool = Executors.newCachedThreadPool();

        @Override
        public void run() {
            try {
                while (alive) {
                    try {
                        pool.execute(new ClosingClientRunnable(listen.accept()));
                    } catch (SocketTimeoutException ignored) {
                    // Allow the server socket to terminate in a timely fashion
                    }
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            } finally {
                try {
                    listen.close();
                } catch (IOException ignored) {
                }
            }
        }
    });
    return listen.getLocalPort();
}
Also used : SocketTimeoutException(java.net.SocketTimeoutException) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ExecutorService(java.util.concurrent.ExecutorService) ServerSocket(java.net.ServerSocket) IOException(java.io.IOException)

Example 97 with SocketTimeoutException

use of java.net.SocketTimeoutException in project camel by apache.

the class NettyRedeliveryTest method createServerSocket.

private int createServerSocket(int port) throws IOException {
    final ServerSocket listen = new ServerSocket(port);
    listen.setSoTimeout(100);
    listener.execute(new Runnable() {

        private ExecutorService pool = Executors.newCachedThreadPool();

        @Override
        public void run() {
            try {
                while (alive) {
                    try {
                        pool.execute(new ClosingClientRunnable(listen.accept()));
                    } catch (SocketTimeoutException ignored) {
                    // Allow the server socket to terminate in a timely fashion
                    }
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            } finally {
                try {
                    listen.close();
                } catch (IOException ignored) {
                }
            }
        }
    });
    return listen.getLocalPort();
}
Also used : SocketTimeoutException(java.net.SocketTimeoutException) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ExecutorService(java.util.concurrent.ExecutorService) ServerSocket(java.net.ServerSocket) IOException(java.io.IOException)

Example 98 with SocketTimeoutException

use of java.net.SocketTimeoutException in project okhttp by square.

the class CallTest method expect100ContinueTimesOutWithoutContinue.

@Test
public void expect100ContinueTimesOutWithoutContinue() throws Exception {
    server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.NO_RESPONSE));
    client = client.newBuilder().readTimeout(500, TimeUnit.MILLISECONDS).build();
    Request request = new Request.Builder().url(server.url("/")).header("Expect", "100-continue").post(RequestBody.create(MediaType.parse("text/plain"), "abc")).build();
    Call call = client.newCall(request);
    try {
        call.execute();
        fail();
    } catch (SocketTimeoutException expected) {
    }
    RecordedRequest recordedRequest = server.takeRequest();
    assertEquals("", recordedRequest.getBody().readUtf8());
}
Also used : RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MockResponse(okhttp3.mockwebserver.MockResponse) SocketTimeoutException(java.net.SocketTimeoutException) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) Test(org.junit.Test)

Example 99 with SocketTimeoutException

use of java.net.SocketTimeoutException in project okhttp by square.

the class OutputStreamRequestBody method initOutputStream.

protected void initOutputStream(final BufferedSink sink, final long expectedContentLength) {
    this.timeout = sink.timeout();
    this.expectedContentLength = expectedContentLength;
    // An output stream that writes to sink. If expectedContentLength is not -1, then this expects
    // exactly that many bytes to be written.
    this.outputStream = new OutputStream() {

        private long bytesReceived;

        @Override
        public void write(int b) throws IOException {
            write(new byte[] { (byte) b }, 0, 1);
        }

        @Override
        public void write(byte[] source, int offset, int byteCount) throws IOException {
            // Not IllegalStateException!
            if (closed)
                throw new IOException("closed");
            if (expectedContentLength != -1L && bytesReceived + byteCount > expectedContentLength) {
                throw new ProtocolException("expected " + expectedContentLength + " bytes but received " + bytesReceived + byteCount);
            }
            bytesReceived += byteCount;
            try {
                sink.write(source, offset, byteCount);
            } catch (InterruptedIOException e) {
                throw new SocketTimeoutException(e.getMessage());
            }
        }

        @Override
        public void flush() throws IOException {
            // Weird, but consistent with historical behavior.
            if (closed)
                return;
            sink.flush();
        }

        @Override
        public void close() throws IOException {
            closed = true;
            if (expectedContentLength != -1L && bytesReceived < expectedContentLength) {
                throw new ProtocolException("expected " + expectedContentLength + " bytes but received " + bytesReceived);
            }
            sink.close();
        }
    };
}
Also used : ProtocolException(java.net.ProtocolException) InterruptedIOException(java.io.InterruptedIOException) SocketTimeoutException(java.net.SocketTimeoutException) OutputStream(java.io.OutputStream) IOException(java.io.IOException) InterruptedIOException(java.io.InterruptedIOException)

Example 100 with SocketTimeoutException

use of java.net.SocketTimeoutException in project bazel by bazelbuild.

the class HttpConnector method connect.

URLConnection connect(URL originalUrl, ImmutableMap<String, String> requestHeaders) throws IOException {
    if (Thread.interrupted()) {
        throw new InterruptedIOException();
    }
    URL url = originalUrl;
    if (HttpUtils.isProtocol(url, "file")) {
        return url.openConnection();
    }
    List<Throwable> suppressions = new ArrayList<>();
    int retries = 0;
    int redirects = 0;
    int connectTimeout = MIN_CONNECT_TIMEOUT_MS;
    while (true) {
        HttpURLConnection connection = null;
        try {
            connection = (HttpURLConnection) url.openConnection(proxyHelper.createProxyIfNeeded(url));
            boolean isAlreadyCompressed = COMPRESSED_EXTENSIONS.contains(HttpUtils.getExtension(url.getPath())) || COMPRESSED_EXTENSIONS.contains(HttpUtils.getExtension(originalUrl.getPath()));
            for (Map.Entry<String, String> entry : requestHeaders.entrySet()) {
                if (isAlreadyCompressed && Ascii.equalsIgnoreCase(entry.getKey(), "Accept-Encoding")) {
                    // appears to be compressed.
                    continue;
                }
                connection.setRequestProperty(entry.getKey(), entry.getValue());
            }
            connection.setConnectTimeout(connectTimeout);
            // The read timeout is always large because it stays in effect after this method.
            connection.setReadTimeout(READ_TIMEOUT_MS);
            // Java tries to abstract HTTP error responses for us. We don't want that. So we're going
            // to try and undo any IOException that doesn't appear to be a legitimate I/O exception.
            int code;
            try {
                connection.connect();
                code = connection.getResponseCode();
            } catch (FileNotFoundException ignored) {
                code = connection.getResponseCode();
            } catch (UnknownHostException e) {
                String message = "Unknown host: " + e.getMessage();
                eventHandler.handle(Event.progress(message));
                throw new UnrecoverableHttpException(message);
            } catch (IllegalArgumentException e) {
                // This will happen if the user does something like specify a port greater than 2^16-1.
                throw new UnrecoverableHttpException(e.getMessage());
            } catch (IOException e) {
                // message.
                if (e.getMessage() == null) {
                    throw new UnrecoverableHttpException("Failed to even get an error message from " + url);
                }
                if (!e.getMessage().startsWith("Server returned")) {
                    throw e;
                }
                code = connection.getResponseCode();
            }
            // 206 means partial content and only happens if caller specified Range. See RFC7233 § 4.1.
            if (code == 200 || code == 206) {
                return connection;
            } else if (code == 301 || code == 302 || code == 307) {
                readAllBytesAndClose(connection.getInputStream());
                if (++redirects == MAX_REDIRECTS) {
                    eventHandler.handle(Event.progress("Redirect loop detected in " + originalUrl));
                    throw new UnrecoverableHttpException("Redirect loop detected");
                }
                url = HttpUtils.getLocation(connection);
                if (code == 301) {
                    originalUrl = url;
                }
            } else if (code == 403) {
                // jart@ has noticed BitBucket + Amazon AWS downloads frequently flake with this code.
                throw new IOException(describeHttpResponse(connection));
            } else if (code == 408) {
                // that request on a new connection. Quoth RFC7231 § 6.5.7
                throw new IOException(describeHttpResponse(connection));
            } else if (// 4xx means client seems to have erred quoth RFC7231 § 6.5
            code < 500 || // Server doesn't support function quoth RFC7231 § 6.6.2
            code == 501 || // Host not configured on server cf. RFC7231 § 6.6.3
            code == 502 || code == 505) {
                // Server refuses to support version quoth RFC7231 § 6.6.6
                // This is a permanent error so we're not going to retry.
                readAllBytesAndClose(connection.getErrorStream());
                throw new UnrecoverableHttpException(describeHttpResponse(connection));
            } else {
                // However we will retry on some 5xx errors, particularly 500 and 503.
                throw new IOException(describeHttpResponse(connection));
            }
        } catch (UnrecoverableHttpException e) {
            throw e;
        } catch (IOException e) {
            if (connection != null) {
                // If we got here, it means we might not have consumed the entire payload of the
                // response, if any. So we're going to force this socket to disconnect and not be
                // reused. This is particularly important if multiple threads end up establishing
                // connections to multiple mirrors simultaneously for a large file. We don't want to
                // download that large file twice.
                connection.disconnect();
            }
            // We don't respect the Retry-After header (RFC7231 § 7.1.3) because it's rarely used and
            // tends to be too conservative when it is. We're already being good citizens by using
            // exponential backoff. Furthermore RFC law didn't use the magic word "MUST".
            int timeout = IntMath.pow(2, retries) * MIN_RETRY_DELAY_MS;
            if (e instanceof SocketTimeoutException) {
                eventHandler.handle(Event.progress("Timeout connecting to " + url));
                connectTimeout = Math.min(connectTimeout * 2, MAX_CONNECT_TIMEOUT_MS);
                // If we got connect timeout, we're already doing exponential backoff, so no point
                // in sleeping too.
                timeout = 1;
            } else if (e instanceof InterruptedIOException) {
                // Please note that SocketTimeoutException is a subtype of InterruptedIOException.
                throw e;
            }
            if (++retries == MAX_RETRIES) {
                if (!(e instanceof SocketTimeoutException)) {
                    eventHandler.handle(Event.progress(format("Error connecting to %s: %s", url, e.getMessage())));
                }
                for (Throwable suppressed : suppressions) {
                    e.addSuppressed(suppressed);
                }
                throw e;
            }
            // Java 7 allows us to create a tree of all errors that led to the ultimate failure.
            suppressions.add(e);
            eventHandler.handle(Event.progress(format("Failed to connect to %s trying again in %,dms", url, timeout)));
            url = originalUrl;
            try {
                sleeper.sleepMillis(timeout);
            } catch (InterruptedException translated) {
                throw new InterruptedIOException();
            }
        } catch (RuntimeException e) {
            if (connection != null) {
                connection.disconnect();
            }
            eventHandler.handle(Event.progress(format("Unknown error connecting to %s: %s", url, e)));
            throw e;
        }
    }
}
Also used : InterruptedIOException(java.io.InterruptedIOException) UnknownHostException(java.net.UnknownHostException) ArrayList(java.util.ArrayList) FileNotFoundException(java.io.FileNotFoundException) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) URL(java.net.URL) HttpURLConnection(java.net.HttpURLConnection) SocketTimeoutException(java.net.SocketTimeoutException) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap)

Aggregations

SocketTimeoutException (java.net.SocketTimeoutException)721 IOException (java.io.IOException)420 Test (org.junit.Test)139 Socket (java.net.Socket)103 SocketException (java.net.SocketException)99 ServerSocket (java.net.ServerSocket)79 InputStream (java.io.InputStream)77 ConnectException (java.net.ConnectException)70 UnknownHostException (java.net.UnknownHostException)64 InetSocketAddress (java.net.InetSocketAddress)60 URL (java.net.URL)51 EOFException (java.io.EOFException)48 HttpURLConnection (java.net.HttpURLConnection)47 ConnectTimeoutException (org.apache.http.conn.ConnectTimeoutException)42 InterruptedIOException (java.io.InterruptedIOException)40 ArrayList (java.util.ArrayList)40 MalformedURLException (java.net.MalformedURLException)38 InputStreamReader (java.io.InputStreamReader)37 HashMap (java.util.HashMap)36 OutputStream (java.io.OutputStream)35