List of usage examples for java.net SocketTimeoutException SocketTimeoutException
public SocketTimeoutException(String msg)
From source file:org.apache.hadoop.mapreduce.task.reduce.TestFetcher.java
@Test(timeout = 30000) public void testCopyFromHostConnectionTimeout() throws Exception { when(connection.getInputStream()).thenThrow(new SocketTimeoutException("This is a fake timeout :)")); Fetcher<Text, Text> underTest = new FakeFetcher<Text, Text>(job, id, ss, mm, r, metrics, except, key, connection);/*from w w w . j a va 2 s . c o m*/ underTest.copyFromHost(host); verify(connection).addRequestProperty(SecureShuffleUtils.HTTP_HEADER_URL_HASH, encHash); verify(allErrs).increment(1); verify(ss).copyFailed(map1ID, host, false, false); verify(ss).copyFailed(map2ID, host, false, false); verify(ss).putBackKnownMapOutput(any(MapHost.class), eq(map1ID)); verify(ss).putBackKnownMapOutput(any(MapHost.class), eq(map2ID)); }
From source file:org.apache.hadoop.mapreduce.task.reduce.TestFetcher.java
@SuppressWarnings("unchecked") @Test(timeout = 10000)/* w w w.j a va 2 s. co m*/ public void testCopyFromHostWithRetryThenTimeout() throws Exception { InMemoryMapOutput<Text, Text> immo = mock(InMemoryMapOutput.class); Fetcher<Text, Text> underTest = new FakeFetcher<Text, Text>(jobWithRetry, id, ss, mm, r, metrics, except, key, connection); String replyHash = SecureShuffleUtils.generateHash(encHash.getBytes(), key); when(connection.getResponseCode()).thenReturn(200).thenThrow(new SocketTimeoutException("forced timeout")); when(connection.getHeaderField(SecureShuffleUtils.HTTP_HEADER_REPLY_URL_HASH)).thenReturn(replyHash); ShuffleHeader header = new ShuffleHeader(map1ID.toString(), 10, 10, 1); ByteArrayOutputStream bout = new ByteArrayOutputStream(); header.write(new DataOutputStream(bout)); ByteArrayInputStream in = new ByteArrayInputStream(bout.toByteArray()); when(connection.getInputStream()).thenReturn(in); when(connection.getHeaderField(ShuffleHeader.HTTP_HEADER_NAME)) .thenReturn(ShuffleHeader.DEFAULT_HTTP_HEADER_NAME); when(connection.getHeaderField(ShuffleHeader.HTTP_HEADER_VERSION)) .thenReturn(ShuffleHeader.DEFAULT_HTTP_HEADER_VERSION); when(mm.reserve(any(TaskAttemptID.class), anyLong(), anyInt())).thenReturn(immo); doThrow(new IOException("forced error")).when(immo).shuffle(any(MapHost.class), any(InputStream.class), anyLong(), anyLong(), any(ShuffleClientMetrics.class), any(Reporter.class)); underTest.copyFromHost(host); verify(allErrs).increment(1); verify(ss).copyFailed(map1ID, host, false, false); }
From source file:org.apache.hama.util.SocketIOWithTimeout.java
/** * Performs one IO and returns number of bytes read or written. It waits up to * the specified timeout. If the channel is not read before the timeout, * SocketTimeoutException is thrown.//from w w w. j ava2 s.co m * * @param buf buffer for IO * @param ops Selection Ops used for waiting. Suggested values: * SelectionKey.OP_READ while reading and SelectionKey.OP_WRITE while * writing. * * @return number of bytes read or written. negative implies end of stream. * @throws IOException */ int doIO(ByteBuffer buf, int ops) throws IOException { /* * For now only one thread is allowed. If user want to read or write from * multiple threads, multiple streams could be created. In that case * multiple threads work as well as underlying channel supports it. */ if (!buf.hasRemaining()) { throw new IllegalArgumentException("Buffer has no data left."); // or should we just return 0? } while (buf.hasRemaining()) { if (closed) { return -1; } try { int n = performIO(buf); if (n != 0) { // successful io or an error. return n; } } catch (IOException e) { if (!channel.isOpen()) { closed = true; } throw e; } // now wait for socket to be ready. int count = 0; try { count = selector.select(channel, ops, timeout); } catch (IOException e) { // unexpected IOException. closed = true; throw e; } if (count == 0) { throw new SocketTimeoutException(timeoutExceptionString(channel, timeout, ops)); } // otherwise the socket should be ready for io. } return 0; // does not reach here. }
From source file:org.apache.nifi.processor.util.put.sender.SocketChannelSender.java
@Override public void open() throws IOException { if (channel == null) { channel = SocketChannel.open(); channel.configureBlocking(false); if (maxSendBufferSize > 0) { channel.setOption(StandardSocketOptions.SO_SNDBUF, maxSendBufferSize); final int actualSendBufSize = channel.getOption(StandardSocketOptions.SO_SNDBUF); if (actualSendBufSize < maxSendBufferSize) { logger.warn("Attempted to set Socket Send Buffer Size to " + maxSendBufferSize + " bytes but could only set to " + actualSendBufSize + "bytes. You may want to " + "consider changing the Operating System's maximum receive buffer"); }//from w w w .ja v a 2s .c o m } } if (!channel.isConnected()) { final long startTime = System.currentTimeMillis(); final InetSocketAddress socketAddress = new InetSocketAddress(InetAddress.getByName(host), port); if (!channel.connect(socketAddress)) { while (!channel.finishConnect()) { if (System.currentTimeMillis() > startTime + timeout) { throw new SocketTimeoutException("Timed out connecting to " + host + ":" + port); } try { Thread.sleep(50L); } catch (final InterruptedException e) { } } } socketChannelOutput = new SocketChannelOutputStream(channel); socketChannelOutput.setTimeout(timeout); } }
From source file:org.apache98.hadoop.hbase.ipc.RpcClient.java
/** * Take an IOException and the address we were trying to connect to * and return an IOException with the input exception as the cause. * The new exception provides the stack trace of the place where * the exception is thrown and some extra diagnostics information. * If the exception is ConnectException or SocketTimeoutException, * return a new one of the same type; Otherwise return an IOException. * /* w w w . ja va 2s . co m*/ * @param addr * target address * @param exception * the relevant exception * @return an exception to throw */ protected IOException wrapException(InetSocketAddress addr, IOException exception) { if (exception instanceof ConnectException) { // connection refused; include the host:port in the error return (ConnectException) new ConnectException( "Call to " + addr + " failed on connection exception: " + exception).initCause(exception); } else if (exception instanceof SocketTimeoutException) { return (SocketTimeoutException) new SocketTimeoutException( "Call to " + addr + " failed because " + exception).initCause(exception); } else { return (IOException) new IOException("Call to " + addr + " failed on local exception: " + exception) .initCause(exception); } }
From source file:org.archive.modules.fetcher.HeritrixProtocolSocketFactory.java
/** * Attempts to get a new socket connection to the given host within the * given time limit.//from w ww .j av a 2 s .c o m * <p> * This method employs several techniques to circumvent the limitations * of older JREs that do not support connect timeout. When running in * JRE 1.4 or above reflection is used to call * Socket#connect(SocketAddress endpoint, int timeout) method. When * executing in older JREs a controller thread is executed. The * controller thread attempts to create a new socket within the given * limit of time. If socket constructor does not return until the * timeout expires, the controller terminates and throws an * {@link ConnectTimeoutException} * </p> * * @param host the host name/IP * @param port the port on the host * @param localAddress the local host name/IP to bind the socket to * @param localPort the port on the local machine * @param params {@link HttpConnectionParams Http connection parameters} * * @return Socket a new socket * * @throws IOException if an I/O error occurs while creating the socket * @throws UnknownHostException if the IP address of the host cannot be * @throws IOException if an I/O error occurs while creating the socket * @throws UnknownHostException if the IP address of the host cannot be * determined * @throws ConnectTimeoutException if socket cannot be connected within the * given time limit * * @since 3.0 */ public Socket createSocket(final String host, final int port, final InetAddress localAddress, final int localPort, final HttpConnectionParams params) throws IOException, UnknownHostException, ConnectTimeoutException { // Below code is from the DefaultSSLProtocolSocketFactory#createSocket // method only it has workarounds to deal with pre-1.4 JVMs. I've // cut these out. if (params == null) { throw new IllegalArgumentException("Parameters may not be null"); } Socket socket = null; int timeout = params.getConnectionTimeout(); if (timeout == 0) { socket = createSocket(host, port, localAddress, localPort); } else { socket = new Socket(); InetAddress hostAddress; Thread current = Thread.currentThread(); if (current instanceof HostResolver) { HostResolver resolver = (HostResolver) current; hostAddress = resolver.resolve(host); } else { hostAddress = null; } InetSocketAddress address = (hostAddress != null) ? new InetSocketAddress(hostAddress, port) : new InetSocketAddress(host, port); socket.bind(new InetSocketAddress(localAddress, localPort)); try { socket.connect(address, timeout); } catch (SocketTimeoutException e) { // Add timeout info. to the exception. throw new SocketTimeoutException( e.getMessage() + ": timeout set at " + Integer.toString(timeout) + "ms."); } assert socket.isConnected() : "Socket not connected " + host; } return socket; }
From source file:org.archive.modules.fetcher.HeritrixSSLProtocolSocketFactory.java
public synchronized Socket createSocket(String host, int port, InetAddress localAddress, int localPort, HttpConnectionParams params) throws IOException, UnknownHostException { // Below code is from the DefaultSSLProtocolSocketFactory#createSocket // method only it has workarounds to deal with pre-1.4 JVMs. I've // cut these out. if (params == null) { throw new IllegalArgumentException("Parameters may not be null"); }/* ww w. ja v a2 s . co m*/ Socket socket = null; int timeout = params.getConnectionTimeout(); if (timeout == 0) { socket = createSocket(host, port, localAddress, localPort); } else { SSLSocketFactory factory = (SSLSocketFactory) params.getParameter(FetchHTTP.SSL_FACTORY_KEY); SSLSocketFactory f = (factory != null) ? factory : this.sslDefaultFactory; socket = f.createSocket(); Thread current = Thread.currentThread(); InetAddress hostAddress; if (current instanceof HostResolver) { HostResolver resolver = (HostResolver) current; hostAddress = resolver.resolve(host); } else { hostAddress = null; } InetSocketAddress address = (hostAddress != null) ? new InetSocketAddress(hostAddress, port) : new InetSocketAddress(host, port); socket.bind(new InetSocketAddress(localAddress, localPort)); try { socket.connect(address, timeout); } catch (SocketTimeoutException e) { // Add timeout info. to the exception. throw new SocketTimeoutException( e.getMessage() + ": timeout set at " + Integer.toString(timeout) + "ms."); } assert socket.isConnected() : "Socket not connected " + host; } return socket; }
From source file:org.cloudata.core.common.ipc.CClient.java
/** * Make a call, passing <code>param</code>, to the IPC server running at * <code>address</code>, returning the value. Throws exceptions if there are * network problems or if the remote code threw an exception. *//* w w w . j a v a 2 s . c o m*/ public CWritable call(CWritable param, InetSocketAddress address) throws InterruptedException, IOException { Connection connection = getConnection(address); Call call = new Call(param); int retryCount = 0; while (true) { try { connection.sendParam(call); break; } catch (IOException e) { if (retryCount > 5) { LOG.error("SendParam error:" + address + "," + e.getMessage(), e); throw e; } LOG.error("SendParam error:" + address + "," + e.getMessage() + ", but retry:" + retryCount); retryCount++; closeThisConnection(address, connection); // close on error connection = getConnection(address); } } try { int id; try { id = connection.in.readInt(); // try to read an id } catch (SocketTimeoutException e) { throw new SocketTimeoutException( "timed out waiting for rpc response[" + address + "]" + new Date(call.lastActivity)); } boolean isError = connection.in.readBoolean(); // read if error if (isError) { String exceptionClassName = CWritableUtils.readString(connection.in); String exceptionMessage = CWritableUtils.readString(connection.in); this.returnToConnections(address, connection); throw new CRemoteException(exceptionClassName, exceptionMessage); } else { CWritable value = (CWritable) ReflectionUtils.newInstance(valueClass, conf); value.readFields(connection.in); // read value this.returnToConnections(address, connection); return value; } } catch (EOFException eof) { //LOG.warn("EOFException: id : " + connection + ", socket : " + connection.socket, eof); closeThisConnection(address, connection); throw new IOException(eof.getMessage(), eof); } catch (CRemoteException e) { throw e; } catch (SocketTimeoutException e) { throw e; } catch (Exception e) { LOG.error("Error while call:" + connection.address + "," + e.getMessage(), e); IOException err = new IOException(e.getMessage()); err.initCause(e); closeThisConnection(address, connection); throw err; } // try { // synchronized (call) { // connection.sendParam(call); // send the parameter // long wait = timeout; // do { // call.wait(wait); // wait for the result // wait = timeout - (System.currentTimeMillis() - call.lastActivity); // } while (!call.done && wait > 0); // // if (call.error != null) { // throw new NRemoteException(call.errorClass, call.error); // } else if (!call.done) { // // FIXME timeout? ? ? timeout? ? // throw new SocketTimeoutException("timed out waiting for rpc response[" // + address + "]" + new Date(call.lastActivity)); // } else { // return call.value; // } // } // } finally { // connection.decrementRef(); // returnToConnections(address, connection); // } }
From source file:org.everrest.websockets.client.WSClient.java
/** * Connect to remote server.//from www . j a v a2 s .co m * * @param timeout * connection timeout value in seconds * @throws IOException * if connection failed * @throws IllegalArgumentException * if <code>timeout</code> zero or negative */ public synchronized void connect(long timeout) throws IOException { if (timeout < 1) { throw new IllegalArgumentException(String.format("Invalid timeout: %d", timeout)); } if (connected) { throw new IOException("Already connected."); } try { executor.submit(new Runnable() { @Override public void run() { try { int port = target.getPort(); if (port == -1) { port = 80; } socket = new Socket(target.getHost(), port); in = socket.getInputStream(); out = socket.getOutputStream(); out.write(getHandshake()); validateResponseHeaders(); inputBuffer = ByteBuffer.allocate(DEFAULT_BUFFER_SIZE); connected = true; } catch (IOException e) { throw new RuntimeException(e); } } }).get(timeout, TimeUnit.SECONDS); // Wait for connection. } catch (InterruptedException e) { // throw new IOException(e.getMessage(), e); } catch (ExecutionException e) { // It is RuntimeException for sure. RuntimeException re = (RuntimeException) e.getCause(); Throwable cause = re.getCause(); if (cause instanceof IOException) { throw (IOException) cause; } throw re; } catch (TimeoutException e) { // Connection time out reached. throw new SocketTimeoutException("Connection timeout. "); } finally { if (!connected) { executor.shutdown(); } } // Start reading from socket. executor.submit(new Runnable() { @Override public void run() { try { read(); } catch (ConnectionException e) { LOG.error(e.getMessage(), e); onClose(e.status, e.getMessage()); } catch (Exception e) { // All unexpected errors represents as protocol error, status: 1002. LOG.error(e.getMessage(), e); onClose(1002, e.getMessage()); } } }); // Notify listeners about connection open. onOpen(); }
From source file:org.opennms.sms.reflector.smsservice.MobileMsgCallbackAdapter.java
/** {@inheritDoc} */ @Override/*from www . j a v a 2 s . c o m*/ public void handleTimeout(final MobileMsgRequest request) { getCb().handleException(new SocketTimeoutException("timed out processing request " + request)); }