Search in sources :

Example 66 with InterruptedIOException

use of java.io.InterruptedIOException in project robolectric by robolectric.

the class DefaultRequestDirector method execute.

// non-javadoc, see interface ClientRequestDirector
public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context) throws HttpException, IOException {
    HttpRequest orig = request;
    RequestWrapper origWrapper = wrapRequest(orig);
    origWrapper.setParams(params);
    HttpRoute origRoute = determineRoute(target, origWrapper, context);
    virtualHost = (HttpHost) orig.getParams().getParameter(ClientPNames.VIRTUAL_HOST);
    RoutedRequest roureq = new RoutedRequest(origWrapper, origRoute);
    long timeout = ConnManagerParams.getTimeout(params);
    int execCount = 0;
    boolean reuse = false;
    boolean done = false;
    try {
        HttpResponse response = null;
        while (!done) {
            // In this loop, the RoutedRequest may be replaced by a
            // followup request and route. The request and route passed
            // in the method arguments will be replaced. The original
            // request is still available in 'orig'.
            RequestWrapper wrapper = roureq.getRequest();
            HttpRoute route = roureq.getRoute();
            response = null;
            // See if we have a user token bound to the execution context
            Object userToken = context.getAttribute(ClientContext.USER_TOKEN);
            // Allocate connection if needed
            if (managedConn == null) {
                ClientConnectionRequest connRequest = connManager.requestConnection(route, userToken);
                if (orig instanceof AbortableHttpRequest) {
                    ((AbortableHttpRequest) orig).setConnectionRequest(connRequest);
                }
                try {
                    managedConn = connRequest.getConnection(timeout, TimeUnit.MILLISECONDS);
                } catch (InterruptedException interrupted) {
                    InterruptedIOException iox = new InterruptedIOException();
                    iox.initCause(interrupted);
                    throw iox;
                }
                if (HttpConnectionParams.isStaleCheckingEnabled(params)) {
                    // validate connection
                    if (managedConn.isOpen()) {
                        this.log.debug("Stale connection check");
                        if (managedConn.isStale()) {
                            this.log.debug("Stale connection detected");
                            managedConn.close();
                        }
                    }
                }
            }
            if (orig instanceof AbortableHttpRequest) {
                ((AbortableHttpRequest) orig).setReleaseTrigger(managedConn);
            }
            // Reopen connection if needed
            if (!managedConn.isOpen()) {
                managedConn.open(route, context, params);
            } else {
                managedConn.setSocketTimeout(HttpConnectionParams.getSoTimeout(params));
            }
            try {
                establishRoute(route, context);
            } catch (TunnelRefusedException ex) {
                if (this.log.isDebugEnabled()) {
                    this.log.debug(ex.getMessage());
                }
                response = ex.getResponse();
                break;
            }
            // Reset headers on the request wrapper
            wrapper.resetHeaders();
            // Re-write request URI if needed
            rewriteRequestURI(wrapper, route);
            // Use virtual host if set
            target = virtualHost;
            if (target == null) {
                target = route.getTargetHost();
            }
            HttpHost proxy = route.getProxyHost();
            // Populate the execution context
            context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, target);
            context.setAttribute(ExecutionContext.HTTP_PROXY_HOST, proxy);
            context.setAttribute(ExecutionContext.HTTP_CONNECTION, managedConn);
            context.setAttribute(ClientContext.TARGET_AUTH_STATE, targetAuthState);
            context.setAttribute(ClientContext.PROXY_AUTH_STATE, proxyAuthState);
            // Run request protocol interceptors
            requestExec.preProcess(wrapper, httpProcessor, context);
            boolean retrying = true;
            Exception retryReason = null;
            while (retrying) {
                // Increment total exec count (with redirects)
                execCount++;
                // Increment exec count for this particular request
                wrapper.incrementExecCount();
                if (!wrapper.isRepeatable()) {
                    this.log.debug("Cannot retry non-repeatable request");
                    if (retryReason != null) {
                        throw new NonRepeatableRequestException("Cannot retry request " + "with a non-repeatable request entity.  The cause lists the " + "reason the original request failed: " + retryReason);
                    } else {
                        throw new NonRepeatableRequestException("Cannot retry request " + "with a non-repeatable request entity.");
                    }
                }
                try {
                    if (this.log.isDebugEnabled()) {
                        this.log.debug("Attempt " + execCount + " to execute request");
                    }
                    response = requestExec.execute(wrapper, managedConn, context);
                    retrying = false;
                } catch (IOException ex) {
                    this.log.debug("Closing the connection.");
                    managedConn.close();
                    if (retryHandler.retryRequest(ex, wrapper.getExecCount(), context)) {
                        if (this.log.isInfoEnabled()) {
                            this.log.info("I/O exception (" + ex.getClass().getName() + ") caught when processing request: " + ex.getMessage());
                        }
                        if (this.log.isDebugEnabled()) {
                            this.log.debug(ex.getMessage(), ex);
                        }
                        this.log.info("Retrying request");
                        retryReason = ex;
                    } else {
                        throw ex;
                    }
                    // just re-open connection and re-try the request
                    if (!route.isTunnelled()) {
                        this.log.debug("Reopening the direct connection.");
                        managedConn.open(route, context, params);
                    } else {
                        // otherwise give up
                        this.log.debug("Proxied connection. Need to start over.");
                        retrying = false;
                    }
                }
            }
            if (response == null) {
                // Need to start over
                continue;
            }
            // Run response protocol interceptors
            response.setParams(params);
            requestExec.postProcess(response, httpProcessor, context);
            // The connection is in or can be brought to a re-usable state.
            reuse = reuseStrategy.keepAlive(response, context);
            if (reuse) {
                // Set the idle duration of this connection
                long duration = keepAliveStrategy.getKeepAliveDuration(response, context);
                managedConn.setIdleDuration(duration, TimeUnit.MILLISECONDS);
                if (this.log.isDebugEnabled()) {
                    if (duration >= 0) {
                        this.log.debug("Connection can be kept alive for " + duration + " ms");
                    } else {
                        this.log.debug("Connection can be kept alive indefinitely");
                    }
                }
            }
            RoutedRequest followup = handleResponse(roureq, response, context);
            if (followup == null) {
                done = true;
            } else {
                if (reuse) {
                    // Make sure the response body is fully consumed, if present
                    HttpEntity entity = response.getEntity();
                    if (entity != null) {
                        entity.consumeContent();
                    }
                    // entity consumed above is not an auto-release entity,
                    // need to mark the connection re-usable explicitly
                    managedConn.markReusable();
                } else {
                    managedConn.close();
                }
                // check if we can use the same connection for the followup
                if (!followup.getRoute().equals(roureq.getRoute())) {
                    releaseConnection();
                }
                roureq = followup;
            }
            if (managedConn != null && userToken == null) {
                userToken = userTokenHandler.getUserToken(context);
                context.setAttribute(ClientContext.USER_TOKEN, userToken);
                if (userToken != null) {
                    managedConn.setState(userToken);
                }
            }
        }
        // check for entity, release connection if possible
        if ((response == null) || (response.getEntity() == null) || !response.getEntity().isStreaming()) {
            // connection not needed and (assumed to be) in re-usable state
            if (reuse)
                managedConn.markReusable();
            releaseConnection();
        } else {
            // install an auto-release entity
            HttpEntity entity = response.getEntity();
            entity = new BasicManagedEntity(entity, managedConn, reuse);
            response.setEntity(entity);
        }
        return response;
    } catch (HttpException | RuntimeException | IOException ex) {
        abortConnection();
        throw ex;
    }
}
Also used : HttpRequest(org.apache.http.HttpRequest) BasicHttpRequest(org.apache.http.message.BasicHttpRequest) AbortableHttpRequest(org.apache.http.client.methods.AbortableHttpRequest) AbortableHttpRequest(org.apache.http.client.methods.AbortableHttpRequest) InterruptedIOException(java.io.InterruptedIOException) TunnelRefusedException(org.apache.http.impl.client.TunnelRefusedException) HttpEntity(org.apache.http.HttpEntity) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) HttpResponse(org.apache.http.HttpResponse) ClientConnectionRequest(org.apache.http.conn.ClientConnectionRequest) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) ProtocolException(org.apache.http.ProtocolException) URISyntaxException(java.net.URISyntaxException) HttpException(org.apache.http.HttpException) AuthenticationException(org.apache.http.auth.AuthenticationException) RedirectException(org.apache.http.client.RedirectException) InterruptedIOException(java.io.InterruptedIOException) MalformedChallengeException(org.apache.http.auth.MalformedChallengeException) TunnelRefusedException(org.apache.http.impl.client.TunnelRefusedException) IOException(java.io.IOException) NonRepeatableRequestException(org.apache.http.client.NonRepeatableRequestException) HttpRoute(org.apache.http.conn.routing.HttpRoute) BasicManagedEntity(org.apache.http.conn.BasicManagedEntity) HttpHost(org.apache.http.HttpHost) RequestWrapper(org.apache.http.impl.client.RequestWrapper) EntityEnclosingRequestWrapper(org.apache.http.impl.client.EntityEnclosingRequestWrapper) HttpException(org.apache.http.HttpException) RoutedRequest(org.apache.http.impl.client.RoutedRequest) NonRepeatableRequestException(org.apache.http.client.NonRepeatableRequestException)

Example 67 with InterruptedIOException

use of java.io.InterruptedIOException in project robovm by robovm.

the class FtpURLConnection method connectInternal.

private void connectInternal() throws IOException {
    int port = url.getPort();
    int connectTimeout = getConnectTimeout();
    if (port <= 0) {
        port = FTP_PORT;
    }
    if (currentProxy == null || Proxy.Type.HTTP == currentProxy.type()) {
        controlSocket = new Socket();
    } else {
        controlSocket = new Socket(currentProxy);
    }
    InetSocketAddress addr = new InetSocketAddress(hostName, port);
    controlSocket.connect(addr, connectTimeout);
    connected = true;
    ctrlOutput = controlSocket.getOutputStream();
    ctrlInput = controlSocket.getInputStream();
    login();
    setType();
    if (!getDoInput()) {
        cd();
    }
    try {
        acceptSocket = new ServerSocket(0);
        dataPort = acceptSocket.getLocalPort();
        /* Cannot set REUSEADDR so we need to send a PORT command */
        port();
        if (connectTimeout == 0) {
            // set timeout rather than zero as before
            connectTimeout = 3000;
        }
        acceptSocket.setSoTimeout(getConnectTimeout());
        if (getDoInput()) {
            getFile();
        } else {
            sendFile();
        }
        dataSocket = acceptSocket.accept();
        dataSocket.setSoTimeout(getReadTimeout());
        acceptSocket.close();
    } catch (InterruptedIOException e) {
        throw new IOException("Could not establish data connection");
    }
    if (getDoInput()) {
        inputStream = new FtpURLInputStream(new BufferedInputStream(dataSocket.getInputStream()), controlSocket);
    }
}
Also used : InterruptedIOException(java.io.InterruptedIOException) BufferedInputStream(java.io.BufferedInputStream) InetSocketAddress(java.net.InetSocketAddress) ServerSocket(java.net.ServerSocket) IOException(java.io.IOException) InterruptedIOException(java.io.InterruptedIOException) Socket(java.net.Socket) ServerSocket(java.net.ServerSocket)

Example 68 with InterruptedIOException

use of java.io.InterruptedIOException in project robovm by robovm.

the class OldDatagramSocketTest method test_receiveLjava_net_DatagramPacket.

public void test_receiveLjava_net_DatagramPacket() throws Exception {
    // Test for method void
    // java.net.DatagramSocket.receive(java.net.DatagramPacket)
    receive_oversize_java_net_DatagramPacket();
    final int[] ports = Support_PortManager.getNextPortsForUDP(2);
    final int portNumber = ports[0];
    class TestDGRcv implements Runnable {

        public void run() {
            try {
                InetAddress localHost = InetAddress.getLocalHost();
                Thread.sleep(1000);
                DatagramSocket sds = new DatagramSocket(ports[1]);
                sds.send(new DatagramPacket("Test".getBytes("UTF-8"), "Test".length(), localHost, portNumber));
                sds.send(new DatagramPacket("Longer test".getBytes("UTF-8"), "Longer test".length(), localHost, portNumber));
                sds.send(new DatagramPacket("3 Test".getBytes("UTF-8"), "3 Test".length(), localHost, portNumber));
                sds.send(new DatagramPacket("4 Test".getBytes("UTF-8"), "4 Test".length(), localHost, portNumber));
                sds.send(new DatagramPacket("5".getBytes("UTF-8"), "5".length(), localHost, portNumber));
                sds.close();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
    try {
        new Thread(new TestDGRcv(), "datagram receiver").start();
        ds = new java.net.DatagramSocket(portNumber);
        ds.setSoTimeout(6000);
        byte[] rbuf = new byte[1000];
        DatagramPacket rdp = new DatagramPacket(rbuf, rbuf.length);
        // Receive the first packet.
        ds.receive(rdp);
        assertEquals("Test", new String(rbuf, 0, rdp.getLength()));
        // Check that we can still receive a longer packet (http://code.google.com/p/android/issues/detail?id=24748).
        ds.receive(rdp);
        assertEquals("Longer test", new String(rbuf, 0, rdp.getLength()));
        // See what happens if we manually call DatagramPacket.setLength.
        rdp.setLength(4);
        ds.receive(rdp);
        assertEquals("3 Te", new String(rbuf, 0, rdp.getLength()));
        // And then another.
        ds.receive(rdp);
        assertEquals("4 Te", new String(rbuf, 0, rdp.getLength()));
        // And then a packet shorter than the user-supplied length.
        ds.receive(rdp);
        assertEquals("5", new String(rbuf, 0, rdp.getLength()));
        ds.close();
    } finally {
        ds.close();
    }
    DatagramSocket socket = null;
    try {
        byte[] rbuf = new byte[1000];
        DatagramPacket rdp = new DatagramPacket(rbuf, rbuf.length);
        DatagramChannel channel = DatagramChannel.open();
        channel.configureBlocking(false);
        socket = channel.socket();
        socket.receive(rdp);
        fail("IllegalBlockingModeException was not thrown.");
    } catch (IllegalBlockingModeException expected) {
    } finally {
        socket.close();
    }
    try {
        ds = new java.net.DatagramSocket(portNumber);
        ds.setSoTimeout(1000);
        byte[] rbuf = new byte[1000];
        DatagramPacket rdp = new DatagramPacket(rbuf, rbuf.length);
        ds.receive(rdp);
        fail("SocketTimeoutException was not thrown.");
    } catch (SocketTimeoutException expected) {
    } finally {
        ds.close();
    }
    interrupted = false;
    final DatagramSocket ds = new DatagramSocket();
    ds.setSoTimeout(12000);
    Runnable runnable = new Runnable() {

        public void run() {
            try {
                ds.receive(new DatagramPacket(new byte[1], 1));
            } catch (InterruptedIOException e) {
                interrupted = true;
            } catch (IOException ignored) {
            }
        }
    };
    Thread thread = new Thread(runnable, "DatagramSocket.receive1");
    thread.start();
    do {
        Thread.sleep(500);
    } while (!thread.isAlive());
    ds.close();
    int c = 0;
    do {
        Thread.sleep(500);
        if (interrupted) {
            fail("received interrupt");
        }
        if (++c > 4) {
            fail("read call did not exit");
        }
    } while (thread.isAlive());
    interrupted = false;
    final int portNum = ports[0];
    final DatagramSocket ds2 = new DatagramSocket(ports[1]);
    ds2.setSoTimeout(12000);
    Runnable runnable2 = new Runnable() {

        public void run() {
            try {
                ds2.receive(new DatagramPacket(new byte[1], 1, InetAddress.getLocalHost(), portNum));
            } catch (InterruptedIOException e) {
                interrupted = true;
            } catch (IOException ignored) {
            }
        }
    };
    Thread thread2 = new Thread(runnable2, "DatagramSocket.receive2");
    thread2.start();
    try {
        do {
            Thread.sleep(500);
        } while (!thread2.isAlive());
    } catch (InterruptedException ignored) {
    }
    ds2.close();
    int c2 = 0;
    do {
        Thread.sleep(500);
        if (interrupted) {
            fail("receive2 was interrupted");
        }
        if (++c2 > 4) {
            fail("read2 call did not exit");
        }
    } while (thread2.isAlive());
    interrupted = false;
    DatagramSocket ds3 = new DatagramSocket();
    ds3.setSoTimeout(500);
    Date start = new Date();
    try {
        ds3.receive(new DatagramPacket(new byte[1], 1));
    } catch (InterruptedIOException e) {
        interrupted = true;
    }
    ds3.close();
    assertTrue("receive not interrupted", interrupted);
    int delay = (int) (new Date().getTime() - start.getTime());
    assertTrue("timeout too soon: " + delay, delay >= 490);
}
Also used : InterruptedIOException(java.io.InterruptedIOException) DatagramChannel(java.nio.channels.DatagramChannel) IOException(java.io.IOException) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) BindException(java.net.BindException) InterruptedIOException(java.io.InterruptedIOException) UnknownHostException(java.net.UnknownHostException) SocketException(java.net.SocketException) IllegalBlockingModeException(java.nio.channels.IllegalBlockingModeException) SocketTimeoutException(java.net.SocketTimeoutException) PortUnreachableException(java.net.PortUnreachableException) Date(java.util.Date) DatagramSocket(java.net.DatagramSocket) SocketTimeoutException(java.net.SocketTimeoutException) DatagramSocket(java.net.DatagramSocket) DatagramPacket(java.net.DatagramPacket) IllegalBlockingModeException(java.nio.channels.IllegalBlockingModeException) InetAddress(java.net.InetAddress)

Example 69 with InterruptedIOException

use of java.io.InterruptedIOException in project robovm by robovm.

the class DatagramChannelImpl method receive.

@Override
public SocketAddress receive(ByteBuffer target) throws IOException {
    target.checkWritable();
    checkOpen();
    if (!isBound) {
        return null;
    }
    SocketAddress retAddr = null;
    try {
        begin();
        // receive real data packet, (not peek)
        synchronized (readLock) {
            boolean loop = isBlocking();
            if (!target.isDirect()) {
                retAddr = receiveImpl(target, loop);
            } else {
                retAddr = receiveDirectImpl(target, loop);
            }
        }
    } catch (InterruptedIOException e) {
        // this line used in Linux
        return null;
    } finally {
        end(retAddr != null);
    }
    return retAddr;
}
Also used : InterruptedIOException(java.io.InterruptedIOException) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress)

Example 70 with InterruptedIOException

use of java.io.InterruptedIOException in project spring-boot by spring-projects.

the class HttpTunnelPayload method getPayloadData.

/**
	 * Return the payload data for the given source {@link ReadableByteChannel} or null if
	 * the channel timed out whilst reading.
	 * @param channel the source channel
	 * @return payload data or {@code null}
	 * @throws IOException in case of I/O errors
	 */
public static ByteBuffer getPayloadData(ReadableByteChannel channel) throws IOException {
    ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE);
    try {
        int amountRead = channel.read(buffer);
        Assert.state(amountRead != -1, "Target server connection closed");
        buffer.flip();
        return buffer;
    } catch (InterruptedIOException ex) {
        return null;
    }
}
Also used : InterruptedIOException(java.io.InterruptedIOException) ByteBuffer(java.nio.ByteBuffer)

Aggregations

InterruptedIOException (java.io.InterruptedIOException)274 IOException (java.io.IOException)186 Test (org.junit.Test)39 ArrayList (java.util.ArrayList)27 Socket (java.net.Socket)26 ConnectException (java.net.ConnectException)22 ExecutionException (java.util.concurrent.ExecutionException)22 InputStream (java.io.InputStream)21 InetSocketAddress (java.net.InetSocketAddress)21 ByteBuffer (java.nio.ByteBuffer)21 Path (org.apache.hadoop.fs.Path)20 NoRouteToHostException (java.net.NoRouteToHostException)19 ServletException (javax.servlet.ServletException)17 CountDownLatch (java.util.concurrent.CountDownLatch)16 SocketTimeoutException (java.net.SocketTimeoutException)15 HttpServletRequest (javax.servlet.http.HttpServletRequest)15 HttpServletResponse (javax.servlet.http.HttpServletResponse)15 EOFException (java.io.EOFException)14 SocketException (java.net.SocketException)14 OutputStream (java.io.OutputStream)13