Search in sources :

Example 91 with SocketTimeoutException

use of java.net.SocketTimeoutException in project openhab1-addons by openhab.

the class TACmiBinding method execute.

/**
     * @{inheritDoc
     */
@Override
protected void execute() {
    logger.trace("execute() method is called!");
    try {
        clientSocket.setBroadcast(true);
        clientSocket.setSoTimeout(120000);
        byte[] receiveData = new byte[14];
        DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
        clientSocket.receive(receivePacket);
        byte[] data = receivePacket.getData();
        Message message;
        if (data[1] > 0) {
            logger.debug("Processing analog message");
            message = new AnalogMessage(data);
        } else if (data[1] == 0) {
            logger.debug("Processing digital message");
            message = new DigitalMessage(data);
        } else {
            logger.debug("Invalid message received");
            return;
        }
        logger.debug(message.toString());
        for (TACmiBindingProvider provider : providers) {
            for (String itemName : provider.getItemNames()) {
                logger.debug("Processing item: " + itemName);
                int portNumber = provider.getPortNumber(itemName);
                if (provider.getCanNode(itemName) == message.canNode && provider.getPortType(itemName).equals(message.getType().toString().toLowerCase())) {
                    if (message.hasPortnumber(portNumber)) {
                        if (message.getType() == MessageType.A) {
                            AnalogValue value = ((AnalogMessage) message).getAnalogValue(portNumber);
                            if (value.value != null) {
                                logger.debug("Updating item: " + itemName + " with value: " + value.value);
                                eventPublisher.postUpdate(itemName, new DecimalType(value.value));
                            }
                        } else {
                            OnOffType state = ((DigitalMessage) message).getPortStateAsOnOffType(portNumber);
                            logger.debug("Updating item {} with state {}", itemName, state);
                            eventPublisher.postUpdate(itemName, state);
                        }
                    } else {
                        logger.debug("Portnumber {} not included in message", portNumber);
                    }
                } else {
                    logger.debug("CAN Node does not match");
                }
            }
        }
    } catch (SocketTimeoutException te) {
        logger.info("Receive timeout on CoE socket, retrying ...");
    } catch (Exception e) {
        logger.error("Error in execute: ", e);
    }
    logger.trace("TACmi execute() finished");
}
Also used : AnalogMessage(org.openhab.binding.tacmi.internal.message.AnalogMessage) Message(org.openhab.binding.tacmi.internal.message.Message) DigitalMessage(org.openhab.binding.tacmi.internal.message.DigitalMessage) DigitalMessage(org.openhab.binding.tacmi.internal.message.DigitalMessage) AnalogValue(org.openhab.binding.tacmi.internal.message.AnalogValue) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) SocketException(java.net.SocketException) SocketTimeoutException(java.net.SocketTimeoutException) AnalogMessage(org.openhab.binding.tacmi.internal.message.AnalogMessage) SocketTimeoutException(java.net.SocketTimeoutException) TACmiBindingProvider(org.openhab.binding.tacmi.TACmiBindingProvider) OnOffType(org.openhab.core.library.types.OnOffType) DatagramPacket(java.net.DatagramPacket) DecimalType(org.openhab.core.library.types.DecimalType)

Example 92 with SocketTimeoutException

use of java.net.SocketTimeoutException in project j2objc by google.

the class PlainSocketImpl method accept.

@Override
protected void accept(SocketImpl newImpl) throws IOException {
    if (usingSocks()) {
        ((PlainSocketImpl) newImpl).socksBind();
        ((PlainSocketImpl) newImpl).socksAccept();
        return;
    }
    try {
        InetSocketAddress peerAddress = new InetSocketAddress();
        FileDescriptor clientFd = NetworkOs.accept(fd, peerAddress);
        // TODO: we can't just set newImpl.fd to clientFd because a nio SocketChannel may
        // be sharing the FileDescriptor. http://b//4452981.
        newImpl.fd.setInt$(clientFd.getInt$());
        newImpl.address = peerAddress.getAddress();
        newImpl.port = peerAddress.getPort();
    } catch (ErrnoException errnoException) {
        if (errnoException.errno == EAGAIN) {
            throw new SocketTimeoutException(errnoException);
        }
        throw new SocketException(errnoException.getMessage(), errnoException);
    }
    // Reset the client's inherited read timeout to the Java-specified default of 0.
    newImpl.setOption(SocketOptions.SO_TIMEOUT, Integer.valueOf(0));
    newImpl.localport = NetworkBridge.getSocketLocalPort(newImpl.fd);
}
Also used : SocketException(java.net.SocketException) ErrnoException(libcore.io.ErrnoException) SocketTimeoutException(java.net.SocketTimeoutException) InetSocketAddress(java.net.InetSocketAddress) FileDescriptor(java.io.FileDescriptor)

Example 93 with SocketTimeoutException

use of java.net.SocketTimeoutException in project iosched by google.

the class BasicNetwork method performRequest.

@Override
public NetworkResponse performRequest(Request<?> request) throws VolleyError {
    long requestStart = SystemClock.elapsedRealtime();
    while (true) {
        HttpResponse httpResponse = null;
        byte[] responseContents = null;
        Map<String, String> responseHeaders = new HashMap<String, String>();
        try {
            // Gather headers.
            Map<String, String> headers = new HashMap<String, String>();
            addCacheHeaders(headers, request.getCacheEntry());
            httpResponse = mHttpStack.performRequest(request, headers);
            StatusLine statusLine = httpResponse.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            responseHeaders = convertHeaders(httpResponse.getAllHeaders());
            // Handle cache validation.
            if (statusCode == HttpStatus.SC_NOT_MODIFIED) {
                return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED, request.getCacheEntry() == null ? null : request.getCacheEntry().data, responseHeaders, true);
            }
            // Some responses such as 204s do not have content.  We must check.
            if (httpResponse.getEntity() != null) {
                responseContents = entityToBytes(httpResponse.getEntity());
            } else {
                // Add 0 byte response as a way of honestly representing a
                // no-content request.
                responseContents = new byte[0];
            }
            // if the request is slow, log it.
            long requestLifetime = SystemClock.elapsedRealtime() - requestStart;
            logSlowRequests(requestLifetime, request, responseContents, statusLine);
            if (statusCode < 200 || statusCode > 299) {
                throw new IOException();
            }
            return new NetworkResponse(statusCode, responseContents, responseHeaders, false);
        } catch (SocketTimeoutException e) {
            attemptRetryOnException("socket", request, new TimeoutError());
        } catch (ConnectTimeoutException e) {
            attemptRetryOnException("connection", request, new TimeoutError());
        } catch (MalformedURLException e) {
            throw new RuntimeException("Bad URL " + request.getUrl(), e);
        } catch (IOException e) {
            int statusCode = 0;
            NetworkResponse networkResponse = null;
            if (httpResponse != null) {
                statusCode = httpResponse.getStatusLine().getStatusCode();
            } else {
                throw new NoConnectionError(e);
            }
            VolleyLog.e("Unexpected response code %d for %s", statusCode, request.getUrl());
            if (responseContents != null) {
                networkResponse = new NetworkResponse(statusCode, responseContents, responseHeaders, false);
                if (statusCode == HttpStatus.SC_UNAUTHORIZED || statusCode == HttpStatus.SC_FORBIDDEN) {
                    attemptRetryOnException("auth", request, new AuthFailureError(networkResponse));
                } else {
                    // TODO: Only throw ServerError for 5xx status codes.
                    throw new ServerError(networkResponse);
                }
            } else {
                throw new NetworkError(networkResponse);
            }
        }
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) HashMap(java.util.HashMap) ServerError(com.android.volley.ServerError) HttpResponse(org.apache.http.HttpResponse) AuthFailureError(com.android.volley.AuthFailureError) NetworkError(com.android.volley.NetworkError) NoConnectionError(com.android.volley.NoConnectionError) IOException(java.io.IOException) TimeoutError(com.android.volley.TimeoutError) StatusLine(org.apache.http.StatusLine) SocketTimeoutException(java.net.SocketTimeoutException) NetworkResponse(com.android.volley.NetworkResponse) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException)

Example 94 with SocketTimeoutException

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

the class HttpOverHttp2Test method readResponseHeaderTimeout.

@Test
public void readResponseHeaderTimeout() throws Exception {
    server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.NO_RESPONSE));
    server.enqueue(new MockResponse().setBody("A"));
    client = client.newBuilder().readTimeout(1000, MILLISECONDS).build();
    // Make a call expecting a timeout reading the response headers.
    Call call1 = client.newCall(new Request.Builder().url(server.url("/")).build());
    try {
        call1.execute();
        fail("Should have timed out!");
    } catch (SocketTimeoutException expected) {
        assertEquals("timeout", expected.getMessage());
    }
    // Confirm that a subsequent request on the same connection is not impacted.
    Call call2 = client.newCall(new Request.Builder().url(server.url("/")).build());
    Response response2 = call2.execute();
    assertEquals("A", response2.body().string());
    // Confirm that the connection was reused.
    assertEquals(0, server.takeRequest().getSequenceNumber());
    assertEquals(1, server.takeRequest().getSequenceNumber());
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) Response(okhttp3.Response) MockResponse(okhttp3.mockwebserver.MockResponse) Call(okhttp3.Call) SocketTimeoutException(java.net.SocketTimeoutException) Request(okhttp3.Request) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) Test(org.junit.Test)

Example 95 with SocketTimeoutException

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

the class URLConnectionTest method writeTimeouts.

/** Confirm that an unacknowledged write times out. */
@Test
public void writeTimeouts() throws IOException {
    MockWebServer server = new MockWebServer();
    // Sockets on some platforms can have large buffers that mean writes do not block when
    // required. These socket factories explicitly set the buffer sizes on sockets created.
    final int SOCKET_BUFFER_SIZE = 4 * 1024;
    server.setServerSocketFactory(new DelegatingServerSocketFactory(ServerSocketFactory.getDefault()) {

        @Override
        protected ServerSocket configureServerSocket(ServerSocket serverSocket) throws IOException {
            serverSocket.setReceiveBufferSize(SOCKET_BUFFER_SIZE);
            return serverSocket;
        }
    });
    urlFactory.setClient(urlFactory.client().newBuilder().socketFactory(new DelegatingSocketFactory(SocketFactory.getDefault()) {

        @Override
        protected Socket configureSocket(Socket socket) throws IOException {
            socket.setReceiveBufferSize(SOCKET_BUFFER_SIZE);
            socket.setSendBufferSize(SOCKET_BUFFER_SIZE);
            return socket;
        }
    }).writeTimeout(500, TimeUnit.MILLISECONDS).build());
    server.start();
    server.enqueue(new MockResponse().throttleBody(1, 1, // Prevent the server from reading!
    TimeUnit.SECONDS));
    connection = urlFactory.open(server.url("/").url());
    connection.setDoOutput(true);
    connection.setChunkedStreamingMode(0);
    OutputStream out = connection.getOutputStream();
    try {
        // 2 MiB.
        byte[] data = new byte[2 * 1024 * 1024];
        out.write(data);
        fail();
    } catch (SocketTimeoutException expected) {
    }
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) SocketTimeoutException(java.net.SocketTimeoutException) OutputStream(java.io.OutputStream) MockWebServer(okhttp3.mockwebserver.MockWebServer) ServerSocket(java.net.ServerSocket) IOException(java.io.IOException) SSLSocket(javax.net.ssl.SSLSocket) ServerSocket(java.net.ServerSocket) Socket(java.net.Socket) Test(org.junit.Test)

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