Search in sources :

Example 81 with SocketTimeoutException

use of java.net.SocketTimeoutException in project robovm by robovm.

the class SSLSocketTest method test_SSLSocket_setSoWriteTimeout.

public void test_SSLSocket_setSoWriteTimeout() throws Exception {
    if (StandardNames.IS_RI) {
        // RI does not support write timeout on sockets
        return;
    }
    final TestSSLContext c = TestSSLContext.create();
    SSLSocket client = (SSLSocket) c.clientContext.getSocketFactory().createSocket();
    // Try to make the client SO_SNDBUF size as small as possible
    // (it can default to 512k or even megabytes).  Note that
    // socket(7) says that the kernel will double the request to
    // leave room for its own book keeping and that the minimal
    // value will be 2048. Also note that tcp(7) says the value
    // needs to be set before connect(2).
    int sendBufferSize = 1024;
    client.setSendBufferSize(sendBufferSize);
    sendBufferSize = client.getSendBufferSize();
    // In jb-mr2 it was found that we need to also set SO_RCVBUF
    // to a minimal size or the write would not block. While
    // tcp(2) says the value has to be set before listen(2), it
    // seems fine to set it before accept(2).
    final int recvBufferSize = 128;
    c.serverSocket.setReceiveBufferSize(recvBufferSize);
    client.connect(new InetSocketAddress(c.host, c.port));
    final SSLSocket server = (SSLSocket) c.serverSocket.accept();
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Future<Void> future = executor.submit(new Callable<Void>() {

        @Override
        public Void call() throws Exception {
            server.startHandshake();
            return null;
        }
    });
    executor.shutdown();
    client.startHandshake();
    // Reflection is used so this can compile on the RI
    String expectedClassName = "com.android.org.conscrypt.OpenSSLSocketImpl";
    Class actualClass = client.getClass();
    assertEquals(expectedClassName, actualClass.getName());
    Method setSoWriteTimeout = actualClass.getMethod("setSoWriteTimeout", new Class[] { Integer.TYPE });
    setSoWriteTimeout.invoke(client, 1);
    try {
        // Add extra space to the write to exceed the send buffer
        // size and cause the write to block.
        final int extra = 1;
        client.getOutputStream().write(new byte[sendBufferSize + extra]);
        fail();
    } catch (SocketTimeoutException expected) {
    }
    future.get();
    client.close();
    server.close();
    c.close();
}
Also used : InetSocketAddress(java.net.InetSocketAddress) SSLSocket(javax.net.ssl.SSLSocket) Method(java.lang.reflect.Method) SocketException(java.net.SocketException) SocketTimeoutException(java.net.SocketTimeoutException) SSLProtocolException(javax.net.ssl.SSLProtocolException) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) SSLException(javax.net.ssl.SSLException) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) SocketTimeoutException(java.net.SocketTimeoutException) ExecutorService(java.util.concurrent.ExecutorService)

Example 82 with SocketTimeoutException

use of java.net.SocketTimeoutException 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 83 with SocketTimeoutException

use of java.net.SocketTimeoutException in project robovm by robovm.

the class URLConnectionTest method testReadTimeouts.

public void testReadTimeouts() throws IOException {
    /*
         * This relies on the fact that MockWebServer doesn't close the
         * connection after a response has been sent. This causes the client to
         * try to read more bytes than are sent, which results in a timeout.
         */
    MockResponse timeout = new MockResponse().setBody("ABC").clearHeaders().addHeader("Content-Length: 4");
    server.enqueue(timeout);
    // to keep the server alive
    server.enqueue(new MockResponse().setBody("unused"));
    server.play();
    URLConnection urlConnection = server.getUrl("/").openConnection();
    urlConnection.setReadTimeout(1000);
    InputStream in = urlConnection.getInputStream();
    assertEquals('A', in.read());
    assertEquals('B', in.read());
    assertEquals('C', in.read());
    try {
        // if Content-Length was accurate, this would return -1 immediately
        in.read();
        fail();
    } catch (SocketTimeoutException expected) {
    }
}
Also used : MockResponse(com.google.mockwebserver.MockResponse) SocketTimeoutException(java.net.SocketTimeoutException) GZIPInputStream(java.util.zip.GZIPInputStream) InputStream(java.io.InputStream) HttpURLConnection(java.net.HttpURLConnection) URLConnection(java.net.URLConnection) HttpsURLConnection(javax.net.ssl.HttpsURLConnection)

Example 84 with SocketTimeoutException

use of java.net.SocketTimeoutException in project blade by biezhi.

the class ManagedSelector method processConnect.

private Runnable processConnect(SelectionKey key, final Connect connect) {
    SelectableChannel channel = key.channel();
    try {
        key.attach(connect.attachment);
        boolean connected = _selectorManager.doFinishConnect(channel);
        if (LOG.isDebugEnabled())
            LOG.debug("Connected {} {}", connected, channel);
        if (connected) {
            if (connect.timeout.cancel()) {
                key.interestOps(0);
                return new CreateEndPoint(channel, key) {

                    @Override
                    protected void failed(Throwable failure) {
                        super.failed(failure);
                        connect.failed(failure);
                    }
                };
            } else {
                throw new SocketTimeoutException("Concurrent Connect Timeout");
            }
        } else {
            throw new ConnectException();
        }
    } catch (Throwable x) {
        connect.failed(x);
        return null;
    }
}
Also used : SocketTimeoutException(java.net.SocketTimeoutException) SelectableChannel(java.nio.channels.SelectableChannel) ConnectException(java.net.ConnectException)

Example 85 with SocketTimeoutException

use of java.net.SocketTimeoutException in project Rutgers-Course-Tracker by tevjef.

the class SubjectFragment method showError.

@Override
public void showError(Throwable t) {
    String message;
    Resources resources = getContext().getResources();
    if (t instanceof UnknownHostException) {
        message = resources.getString(R.string.no_internet);
    } else if (t instanceof JsonParseException || t instanceof RutgersServerIOException) {
        message = resources.getString(R.string.server_down);
    } else if (t instanceof RutgersDataIOException) {
        notifySectionNotOpen();
        getParentActivity().onBackPressed();
        return;
    } else if (t instanceof SocketTimeoutException) {
        message = resources.getString(R.string.timed_out);
    } else {
        message = t.getMessage();
    }
    //error message finalized, now save it.
    mViewState.errorMessage = message;
    // Redirects the message that would usually be in the snackbar, to error layout.
    if (!adapterHasItems()) {
        showLayout(LayoutType.ERROR);
        TextView textViewMessage = ButterKnife.findById(mErrorView, R.id.text);
        textViewMessage.setText(message);
    } else {
        showSnackBar(message);
    }
}
Also used : RutgersDataIOException(com.tevinjeffrey.rutgersct.rutgersapi.exceptions.RutgersDataIOException) SocketTimeoutException(java.net.SocketTimeoutException) UnknownHostException(java.net.UnknownHostException) RutgersServerIOException(com.tevinjeffrey.rutgersct.rutgersapi.exceptions.RutgersServerIOException) TextView(android.widget.TextView) Resources(android.content.res.Resources) JsonParseException(com.google.gson.JsonParseException)

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