List of usage examples for java.net Socket setSoTimeout
public synchronized void setSoTimeout(int timeout) throws SocketException
From source file:com.eviware.soapui.impl.wsdl.support.http.SoapUISSLSocketFactory.java
/** * @since 4.1//w ww. ja v a 2s . co m */ @Override public Socket connectSocket(final Socket socket, final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException { if (remoteAddress == null) { throw new IllegalArgumentException("Remote address may not be null"); } if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } Socket sock = socket != null ? socket : new Socket(); if (localAddress != null) { sock.setReuseAddress(HttpConnectionParams.getSoReuseaddr(params)); sock.bind(localAddress); } int connTimeout = HttpConnectionParams.getConnectionTimeout(params); int soTimeout = HttpConnectionParams.getSoTimeout(params); try { sock.setSoTimeout(soTimeout); sock.connect(remoteAddress, connTimeout); } catch (SocketTimeoutException ex) { throw new ConnectTimeoutException( "Connect to " + remoteAddress.getHostName() + "/" + remoteAddress.getAddress() + " timed out"); } SSLSocket sslsock; // Setup SSL layering if necessary if (sock instanceof SSLSocket) { sslsock = (SSLSocket) sock; } else { sslsock = (SSLSocket) getSocketFactory().createSocket(sock, remoteAddress.getHostName(), remoteAddress.getPort(), true); sslsock = enableSocket(sslsock); } // do we need it? trust all hosts // if( getHostnameVerifier() != null ) // { // try // { // getHostnameVerifier().verify( remoteAddress.getHostName(), sslsock ); // // verifyHostName() didn't blowup - good! // } // catch( IOException iox ) // { // // close the socket before re-throwing the exception // try // { // sslsock.close(); // } // catch( Exception x ) // { /* ignore */ // } // throw iox; // } // } return sslsock; }
From source file:com.zimbra.cs.mailclient.MailConnection.java
private Socket newSocket() throws IOException { SocketFactory sf = config.getSecurity() != MailConfig.Security.SSL ? getSocketFactory() : getSSLSocketFactory();// w w w .j a va 2s. c o m Socket sock = sf.createSocket(); int connectTimeout = (int) Math.min(config.getConnectTimeout() * 1000L, Integer.MAX_VALUE); int readTimeout = (int) Math.min(config.getReadTimeout() * 1000L, Integer.MAX_VALUE); sock.setSoTimeout(readTimeout > 0 ? readTimeout : Integer.MAX_VALUE); sock.connect(new InetSocketAddress(config.getHost(), config.getPort()), connectTimeout > 0 ? connectTimeout : Integer.MAX_VALUE); return sock; }
From source file:hudson.TcpSlaveAgentListener.java
/** * Initiates the shuts down of the listener. *//*from ww w. j av a 2s .co m*/ public void shutdown() { shuttingDown = true; try { SocketAddress localAddress = serverSocket.getLocalAddress(); if (localAddress instanceof InetSocketAddress) { InetSocketAddress address = (InetSocketAddress) localAddress; Socket client = new Socket(address.getHostName(), address.getPort()); client.setSoTimeout(1000); // waking the acceptor loop should be quick new PingAgentProtocol().connect(client); } } catch (IOException e) { LOGGER.log(Level.FINE, "Failed to send Ping to wake acceptor loop", e); } try { serverSocket.close(); } catch (IOException e) { LOGGER.log(Level.WARNING, "Failed to close down TCP port", e); } }
From source file:org.apache.hadoop.hdfs.server.namenode.JspHelper.java
public void streamBlockInAscii(InetSocketAddress addr, long blockId, Token<BlockTokenIdentifier> accessToken, long genStamp, long blockSize, long offsetIntoBlock, long chunkSizeToView, JspWriter out, Configuration conf) throws IOException { if (chunkSizeToView == 0) return;//from w w w. j a v a 2 s . c o m Socket s = new Socket(); s.connect(addr, HdfsConstants.READ_TIMEOUT); s.setSoTimeout(HdfsConstants.READ_TIMEOUT); long amtToRead = Math.min(chunkSizeToView, blockSize - offsetIntoBlock); // Use the block name for file name. DFSClient.BlockReader blockReader = DFSClient.BlockReader.newBlockReader(s, addr.toString() + ":" + blockId, blockId, accessToken, genStamp, offsetIntoBlock, amtToRead, conf.getInt("io.file.buffer.size", 4096)); byte[] buf = new byte[(int) amtToRead]; int readOffset = 0; int retries = 2; while (amtToRead > 0) { int numRead; try { numRead = blockReader.readAll(buf, readOffset, (int) amtToRead); } catch (IOException e) { retries--; if (retries == 0) throw new IOException("Could not read data from datanode"); continue; } amtToRead -= numRead; readOffset += numRead; } blockReader = null; s.close(); out.print(HtmlQuoting.quoteHtmlChars(new String(buf))); }
From source file:org.apache.axis2.transport.http.server.AxisHttpConnectionImpl.java
public AxisHttpConnectionImpl(final Socket socket, final HttpParams params) throws IOException { super();//from w ww . j a v a2s .com if (socket == null) { throw new IllegalArgumentException("Socket may not be null"); } if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } socket.setTcpNoDelay(HttpConnectionParams.getTcpNoDelay(params)); socket.setSoTimeout(HttpConnectionParams.getSoTimeout(params)); int linger = HttpConnectionParams.getLinger(params); if (linger >= 0) { socket.setSoLinger(linger > 0, linger); } int buffersize = HttpConnectionParams.getSocketBufferSize(params); this.socket = socket; this.outbuffer = new SocketOutputBuffer(socket, buffersize, params); this.inbuffer = new SocketInputBuffer(socket, buffersize, params); this.contentLenStrategy = new StrictContentLengthStrategy(); this.requestParser = new HttpRequestParser(this.inbuffer, null, new DefaultHttpRequestFactory(), params); this.responseWriter = new HttpResponseWriter(this.outbuffer, null, params); }
From source file:mamo.vanillaVotifier.VotifierServer.java
public synchronized void start() throws IOException { if (isRunning()) { throw new IllegalStateException("Server is already running!"); }// w w w . java 2 s. com notifyListeners(new ServerStartingEvent()); serverSocket = new ServerSocket(); serverSocket.bind(votifier.getConfig().getInetSocketAddress()); running = true; notifyListeners(new ServerStartedEvent()); new Thread(new Runnable() { @Override public void run() { ExecutorService executorService = Executors.newSingleThreadExecutor(); while (isRunning()) { try { final Socket socket = serverSocket.accept(); executorService.execute(new Runnable() { @Override public void run() { try { notifyListeners(new ConnectionEstablishedEvent(socket)); socket.setSoTimeout(SocketOptions.SO_TIMEOUT); // SocketException: handled by try/catch. BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())); writer.write("VOTIFIER 2.9\n"); writer.flush(); BufferedInputStream in = new BufferedInputStream(socket.getInputStream()); // IOException: handled by try/catch. byte[] request = new byte[((RSAPublicKey) votifier.getConfig().getKeyPair() .getPublic()).getModulus().bitLength() / Byte.SIZE]; in.read(request); // IOException: handled by try/catch. notifyListeners(new EncryptedInputReceivedEvent(socket, new String(request))); request = RsaUtils .getDecryptCipher(votifier.getConfig().getKeyPair().getPrivate()) .doFinal(request); // IllegalBlockSizeException: can't happen. String requestString = new String(request); notifyListeners(new DecryptedInputReceivedEvent(socket, requestString)); String[] requestArray = requestString.split("\n"); if ((requestArray.length == 5 || requestArray.length == 6) && requestArray[0].equals("VOTE")) { notifyListeners(new VoteEventVotifier(socket, new Vote(requestArray[1], requestArray[2], requestArray[3], requestArray[4]))); for (VoteAction voteAction : votifier.getConfig().getVoteActions()) { String[] params = new String[4]; try { for (int i = 0; i < params.length; i++) { params[i] = SubstitutionUtils.applyRegexReplacements( requestArray[i + 1], voteAction.getRegexReplacements()); } } catch (PatternSyntaxException e) { notifyListeners(new RegularExpressionPatternErrorException(e)); params = new String[] { requestArray[1], requestArray[2], requestArray[3], requestArray[4] }; } if (voteAction.getCommandSender() instanceof RconCommandSender) { RconCommandSender commandSender = (RconCommandSender) voteAction .getCommandSender(); StrSubstitutor substitutor = SubstitutionUtils.buildStrSubstitutor( new SimpleEntry<String, Object>("service-name", params[0]), new SimpleEntry<String, Object>("user-name", params[1]), new SimpleEntry<String, Object>("address", params[2]), new SimpleEntry<String, Object>("timestamp", params[3])); for (String command : voteAction.getCommands()) { String theCommand = substitutor.replace(command); notifyListeners(new SendingRconCommandEvent( commandSender.getRconConnection(), theCommand)); try { notifyListeners(new RconCommandResponseEvent( commandSender.getRconConnection(), commandSender .sendCommand(theCommand).getPayload())); } catch (Exception e) { notifyListeners(new RconExceptionEvent( commandSender.getRconConnection(), e)); } } } if (voteAction.getCommandSender() instanceof ShellCommandSender) { ShellCommandSender commandSender = (ShellCommandSender) voteAction .getCommandSender(); HashMap<String, String> environment = new HashMap<String, String>(); environment.put("voteServiceName", params[0]); environment.put("voteUserName", params[1]); environment.put("voteAddress", params[2]); environment.put("voteTimestamp", params[3]); for (String command : voteAction.getCommands()) { notifyListeners(new SendingShellCommandEvent(command)); try { commandSender.sendCommand(command, environment); notifyListeners(new ShellCommandSentEvent()); } catch (Exception e) { notifyListeners(new ShellCommandExceptionEvent(e)); } } } } } else { notifyListeners(new InvalidRequestEvent(socket, requestString)); } } catch (SocketTimeoutException e) { notifyListeners(new ReadTimedOutExceptionEvent(socket, e)); } catch (BadPaddingException e) { notifyListeners(new DecryptInputExceptionEvent(socket, e)); } catch (Exception e) { notifyListeners(new CommunicationExceptionEvent(socket, e)); } try { socket.close(); notifyListeners(new ConnectionClosedEvent(socket)); } catch (Exception e) { // IOException: catching just in case. Continue even if socket doesn't close. notifyListeners(new ConnectionCloseExceptionEvent(socket, e)); } } }); } catch (Exception e) { if (running) { // Show errors only while running, to hide error while stopping. notifyListeners(new ConnectionEstablishExceptionEvent(e)); } } } executorService.shutdown(); if (!executorService.isTerminated()) { notifyListeners(new ServerAwaitingTaskCompletionEvent()); try { executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS); } catch (Exception e) { // InterruptedException: can't happen. } } notifyListeners(new ServerStoppedEvent()); } }).start(); }
From source file:org.apache.jcs.auxiliary.remote.RemoteCache.java
/** * Constructor for the RemoteCache object. This object communicates with a remote cache server. * One of these exists for each region. This also holds a reference to a listener. The same * listener is used for all regions for one remote server. Holding a reference to the listener * allows this object to know the listener id assigned by the remote cache. * <p>/*w w w. jav a 2 s . c o m*/ * @param cattr * @param remote * @param listener */ public RemoteCache(IRemoteCacheAttributes cattr, IRemoteCacheService remote, IRemoteCacheListener listener) { this.irca = cattr; this.cacheName = cattr.getCacheName(); this.remote = remote; this.listener = listener; if (log.isDebugEnabled()) { log.debug("Construct> cacheName=" + cattr.getCacheName()); log.debug("irca = " + irca); log.debug("remote = " + remote); log.debug("listener = " + listener); } // use a pool if it is greater than 0 if (log.isDebugEnabled()) { log.debug("GetTimeoutMillis() = " + irca.getGetTimeoutMillis()); } if (irca.getGetTimeoutMillis() > 0) { pool = ThreadPoolManager.getInstance().getPool(irca.getThreadPoolName()); if (log.isDebugEnabled()) { log.debug("Thread Pool = " + pool); } if (pool != null) { usePoolForGet = true; } } try { // Don't set a socket factory if the setting is -1 if (irca.getRmiSocketFactoryTimeoutMillis() > 0) { // TODO make configurable. // use this socket factory to add a timeout. RMISocketFactory.setSocketFactory(new RMISocketFactory() { public Socket createSocket(String host, int port) throws IOException { Socket socket = new Socket(host, port); socket.setSoTimeout(irca.getRmiSocketFactoryTimeoutMillis()); socket.setSoLinger(false, 0); return socket; } public ServerSocket createServerSocket(int port) throws IOException { return new ServerSocket(port); } }); } } catch (Exception e) { // TODO change this so that we only try to do it once. Otherwise we // genreate errors for each region on construction. log.info(e.getMessage()); } }
From source file:com.sshtools.j2ssh.agent.SshAgentConnection.java
SshAgentConnection(KeyStore keystore, Socket socket) throws IOException { this.keystore = keystore; this.in = socket.getInputStream(); this.out = socket.getOutputStream(); this.socket = socket; socket.setSoTimeout(5000); thread = new Thread(this); thread.start();/*from w w w. j av a 2s . c o m*/ }
From source file:com.jredrain.startup.Bootstrap.java
private void await() throws Exception { // Negative values - don't wait on port - redrain is embedded or we just don't like ports if (port == -2) { return;/*from ww w. j a va 2 s . c o m*/ } if (port == -1) { try { awaitThread = Thread.currentThread(); while (!stopAwait) { try { Thread.sleep(10000); } catch (InterruptedException ex) { // continue and check the flag } } } finally { awaitThread = null; } return; } // Set up a server socket to wait on try { awaitSocket = new ServerSocket(RedrainProperties.getInt("redrain.shutdown")); } catch (IOException e) { logger.error("[redrain] agent .await: create[{}] ", RedrainProperties.getInt("redrain.shutdown"), e); return; } try { awaitThread = Thread.currentThread(); // Loop waiting for a connection and a valid command while (!stopAwait) { ServerSocket serverSocket = awaitSocket; if (serverSocket == null) { break; } // Wait for the next connection Socket socket = null; StringBuilder command = new StringBuilder(); try { InputStream stream; long acceptStartTime = System.currentTimeMillis(); try { socket = serverSocket.accept(); socket.setSoTimeout(10 * 1000); // Ten seconds stream = socket.getInputStream(); } catch (SocketTimeoutException ste) { // This should never happen but bug 56684 suggests that // it does. logger.warn("[redrain] agentServer accept.timeout", Long.valueOf(System.currentTimeMillis() - acceptStartTime), ste); continue; } catch (AccessControlException ace) { logger.warn("[redrain] agentServer .accept security exception: {}", ace.getMessage(), ace); continue; } catch (IOException e) { if (stopAwait) { break; } logger.error("[redrain] agent .await: accept: ", e); break; } // Read a set of characters from the socket int expected = 1024; // Cut off to avoid DoS attack while (expected < shutdown.length()) { if (random == null) { random = new Random(); } expected += (random.nextInt() % 1024); } while (expected > 0) { int ch = -1; try { ch = stream.read(); } catch (IOException e) { logger.warn("[redrain] agent .await: read: ", e); ch = -1; } if (ch < 32) // Control character or EOF terminates loop break; command.append((char) ch); expected--; } } finally { try { if (socket != null) { socket.close(); } } catch (IOException e) { } } boolean match = command.toString().equals(shutdown); if (match) { break; } else { logger.warn("[redrain] agent .await: Invalid command '" + command.toString() + "' received"); } } } finally { ServerSocket serverSocket = awaitSocket; awaitThread = null; awaitSocket = null; // Close the server socket and return if (serverSocket != null) { try { serverSocket.close(); } catch (IOException e) { // Ignore } } } }