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");
}
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);
}
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);
}
}
}
}
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());
}
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) {
}
}
Aggregations