List of usage examples for java.net Socket setSoLinger
public void setSoLinger(boolean on, int linger) throws SocketException
From source file:com.sun.grizzly.http.jk.common.ChannelNioSocket.java
private void setSocketOptions(Socket s) throws SocketException { if (socketTimeout > 0) { s.setSoTimeout(socketTimeout);//w w w.j a va2 s . c o m } s.setTcpNoDelay(tcpNoDelay); // set socket tcpnodelay state if (linger > 0) { s.setSoLinger(true, linger); } }
From source file:com.cws.esolutions.agent.processors.impl.ServiceCheckProcessorImpl.java
public ServiceCheckResponse runSystemCheck(final ServiceCheckRequest request) throws ServiceCheckException { final String methodName = IServiceCheckProcessor.CNAME + "#runSystemCheck(final ServiceCheckRequest request) throws ServiceCheckException"; if (DEBUG) {/*w ww. java 2 s. com*/ DEBUGGER.debug(methodName); DEBUGGER.debug("ServiceCheckRequest: {}", request); } int exitCode = -1; Socket socket = null; File sourceFile = null; CommandLine command = null; BufferedWriter writer = null; ExecuteStreamHandler streamHandler = null; ByteArrayOutputStream outputStream = null; ServiceCheckResponse response = new ServiceCheckResponse(); final DefaultExecutor executor = new DefaultExecutor(); final ExecuteWatchdog watchdog = new ExecuteWatchdog(CONNECT_TIMEOUT * 1000); final DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); try { switch (request.getRequestType()) { case NETSTAT: sourceFile = scriptConfig.getScripts().get("netstat"); if (DEBUG) { DEBUGGER.debug("sourceFile: {}", sourceFile); } if (!(sourceFile.canExecute())) { throw new ServiceCheckException( "Script file either does not exist or cannot be executed. Cannot continue."); } command = CommandLine.parse(sourceFile.getAbsolutePath()); if (request.getPortNumber() != 0) { command.addArgument(String.valueOf(request.getPortNumber()), true); } if (DEBUG) { DEBUGGER.debug("CommandLine: {}", command); } outputStream = new ByteArrayOutputStream(); streamHandler = new PumpStreamHandler(outputStream); executor.setWatchdog(watchdog); executor.setStreamHandler(streamHandler); if (DEBUG) { DEBUGGER.debug("ExecuteStreamHandler: {}", streamHandler); DEBUGGER.debug("ExecuteWatchdog: {}", watchdog); DEBUGGER.debug("DefaultExecuteResultHandler: {}", resultHandler); DEBUGGER.debug("DefaultExecutor: {}", executor); } executor.execute(command, resultHandler); resultHandler.waitFor(); exitCode = resultHandler.getExitValue(); if (DEBUG) { DEBUGGER.debug("exitCode: {}", exitCode); } writer = new BufferedWriter(new FileWriter(LOGS_DIRECTORY + "/" + sourceFile.getName() + ".log")); writer.write(outputStream.toString()); writer.flush(); response.setResponseData(outputStream.toString()); if (executor.isFailure(exitCode)) { response.setRequestStatus(AgentStatus.FAILURE); } else { response.setRequestStatus(AgentStatus.SUCCESS); } break; case REMOTEDATE: response.setRequestStatus(AgentStatus.SUCCESS); response.setResponseData(System.currentTimeMillis()); break; case TELNET: response = new ServiceCheckResponse(); int targetPort = request.getPortNumber(); String targetServer = request.getTargetHost(); if (DEBUG) { DEBUGGER.debug("Target port: {}", targetPort); DEBUGGER.debug("Target server: {}", targetServer); } if (targetPort == 0) { throw new ServiceCheckException("Target port number was not assigned. Cannot action request."); } final String CRLF = "\r\n"; final String TERMINATE_TELNET = "^]"; synchronized (new Object()) { InetSocketAddress socketAddress = new InetSocketAddress(targetServer, targetPort); socket = new Socket(); socket.setSoTimeout(IServiceCheckProcessor.CONNECT_TIMEOUT); socket.setSoLinger(false, 0); socket.setKeepAlive(false); try { socket.connect(socketAddress, IServiceCheckProcessor.CONNECT_TIMEOUT); if (!(socket.isConnected())) { throw new ConnectException("Failed to connect to host " + targetServer + " on port " + request.getPortNumber()); } PrintWriter pWriter = new PrintWriter(socket.getOutputStream(), true); pWriter.println(TERMINATE_TELNET + CRLF); pWriter.flush(); pWriter.close(); response.setRequestStatus(AgentStatus.SUCCESS); response.setResponseData("Telnet connection to " + targetServer + " on port " + request.getPortNumber() + " successful."); } catch (ConnectException cx) { response.setRequestStatus(AgentStatus.FAILURE); response.setResponseData("Telnet connection to " + targetServer + " on port " + request.getPortNumber() + " failed with message: " + cx.getMessage()); } } break; case PROCESSLIST: sourceFile = scriptConfig.getScripts().get("processList"); if (DEBUG) { DEBUGGER.debug("sourceFile: {}", sourceFile); } if (!(sourceFile.canExecute())) { throw new ServiceCheckException( "Script file either does not exist or cannot be executed. Cannot continue."); } command = CommandLine.parse(sourceFile.getAbsolutePath()); if (request.getPortNumber() != 0) { command.addArgument(String.valueOf(request.getPortNumber()), true); } if (DEBUG) { DEBUGGER.debug("CommandLine: {}", command); } outputStream = new ByteArrayOutputStream(); streamHandler = new PumpStreamHandler(outputStream); executor.setWatchdog(watchdog); executor.setStreamHandler(streamHandler); if (DEBUG) { DEBUGGER.debug("ExecuteStreamHandler: {}", streamHandler); DEBUGGER.debug("ExecuteWatchdog: {}", watchdog); DEBUGGER.debug("DefaultExecuteResultHandler: {}", resultHandler); DEBUGGER.debug("DefaultExecutor: {}", executor); } executor.execute(command, resultHandler); resultHandler.waitFor(); exitCode = resultHandler.getExitValue(); if (DEBUG) { DEBUGGER.debug("exitCode: {}", exitCode); } writer = new BufferedWriter(new FileWriter(LOGS_DIRECTORY + "/" + sourceFile.getName() + ".log")); writer.write(outputStream.toString()); writer.flush(); response.setResponseData(outputStream.toString()); if (executor.isFailure(exitCode)) { response.setRequestStatus(AgentStatus.FAILURE); } else { response.setRequestStatus(AgentStatus.SUCCESS); } break; default: // unknown operation throw new ServiceCheckException("No valid operation was specified"); } } catch (UnknownHostException uhx) { ERROR_RECORDER.error(uhx.getMessage(), uhx); throw new ServiceCheckException(uhx.getMessage(), uhx); } catch (SocketException sx) { ERROR_RECORDER.error(sx.getMessage(), sx); throw new ServiceCheckException(sx.getMessage(), sx); } catch (IOException iox) { ERROR_RECORDER.error(iox.getMessage(), iox); throw new ServiceCheckException(iox.getMessage(), iox); } catch (InterruptedException ix) { ERROR_RECORDER.error(ix.getMessage(), ix); throw new ServiceCheckException(ix.getMessage(), ix); } finally { try { if (writer != null) { writer.close(); } if ((socket != null) && (!(socket.isClosed()))) { socket.close(); } } catch (IOException iox) { ERROR_RECORDER.error(iox.getMessage(), iox); } } return response; }
From source file:org.apache.blur.console.util.NodeUtil.java
public static Map<String, Object> getZookeeperStatus() throws IOException { String[] connections = Config.getBlurConfig().get("blur.zookeeper.connection").split(","); Set<String> onlineZookeepers = new HashSet<String>(); Set<String> offlineZookeepers = new HashSet<String>(); for (String connection : connections) { Socket socket = null; InputStream response = null; OutputStream question = null; try {//from ww w . ja v a 2s . co m URI parsedConnection = new URI("my://" + connection); String host = parsedConnection.getHost(); int port = parsedConnection.getPort() >= 0 ? parsedConnection.getPort() : 2181; byte[] reqBytes = new byte[4]; ByteBuffer req = ByteBuffer.wrap(reqBytes); req.putInt(ByteBuffer.wrap("ruok".getBytes()).getInt()); socket = new Socket(); socket.setSoLinger(false, 10); socket.setSoTimeout(20000); parsedConnection.getPort(); socket.connect(new InetSocketAddress(host, port)); response = socket.getInputStream(); question = socket.getOutputStream(); question.write(reqBytes); byte[] resBytes = new byte[4]; response.read(resBytes); String status = new String(resBytes); if (status.equals("imok")) { onlineZookeepers.add(connection); } else { offlineZookeepers.add(connection); } socket.close(); response.close(); question.close(); } catch (Exception e) { offlineZookeepers.add(connection); } finally { if (socket != null) { socket.close(); } if (response != null) { response.close(); } if (question != null) { question.close(); } } } Map<String, Object> data = new HashMap<String, Object>(); data.put("online", onlineZookeepers); data.put("offline", offlineZookeepers); return data; }
From source file:org.apache.http.impl.conn.HttpClientConnectionOperator.java
public void connect(final ManagedHttpClientConnection conn, final HttpHost host, final InetSocketAddress localAddress, final int connectTimeout, final SocketConfig socketConfig, final HttpContext context) throws IOException { final Lookup<ConnectionSocketFactory> registry = getSocketFactoryRegistry(context); final ConnectionSocketFactory sf = registry.lookup(host.getSchemeName()); if (sf == null) { throw new UnsupportedSchemeException(host.getSchemeName() + " protocol is not supported"); }// w w w .j a v a 2 s.c om final InetAddress[] addresses = this.dnsResolver.resolve(host.getHostName()); final int port = this.schemePortResolver.resolve(host); for (int i = 0; i < addresses.length; i++) { final InetAddress address = addresses[i]; final boolean last = i == addresses.length - 1; Socket sock = sf.createSocket(context); sock.setReuseAddress(socketConfig.isSoReuseAddress()); conn.bind(sock); final InetSocketAddress remoteAddress = new InetSocketAddress(address, port); if (this.log.isDebugEnabled()) { this.log.debug("Connecting to " + remoteAddress); } try { sock.setSoTimeout(socketConfig.getSoTimeout()); sock = sf.connectSocket(connectTimeout, sock, host, remoteAddress, localAddress, context); sock.setTcpNoDelay(socketConfig.isTcpNoDelay()); sock.setKeepAlive(socketConfig.isSoKeepAlive()); final int linger = socketConfig.getSoLinger(); if (linger >= 0) { sock.setSoLinger(linger > 0, linger); } conn.bind(sock); if (this.log.isDebugEnabled()) { this.log.debug("Connection established " + conn); } return; } catch (final SocketTimeoutException ex) { if (last) { throw new ConnectTimeoutException(ex, host, addresses); } } catch (final ConnectException ex) { if (last) { final String msg = ex.getMessage(); if ("Connection timed out".equals(msg)) { throw new ConnectTimeoutException(ex, host, addresses); } else { throw new HttpHostConnectException(ex, host, addresses); } } } if (this.log.isDebugEnabled()) { this.log.debug("Connect to " + remoteAddress + " timed out. " + "Connection will be retried using another IP address"); } } }
From source file:org.apache.http2.impl.conn.DefaultClientConnectionOperator.java
/** * Performs standard initializations on a newly created socket. * * @param sock the socket to prepare * @param context the context for the connection * @param params the parameters from which to prepare the socket * * @throws IOException in case of an IO problem *///from w w w . j a v a2 s . c om protected void prepareSocket(final Socket sock, final HttpContext context, final HttpParams params) throws IOException { sock.setTcpNoDelay(HttpConnectionParams.getTcpNoDelay(params)); sock.setSoTimeout(HttpConnectionParams.getSoTimeout(params)); int linger = HttpConnectionParams.getLinger(params); if (linger >= 0) { sock.setSoLinger(linger > 0, linger); } }
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>//ww w .j a v a2s.co 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:org.apache.jcs.auxiliary.remote.server.RemoteCacheServerFactory.java
/** * Starts up the remote cache server on this JVM, and binds it to the registry on the given host * and port./*from w w w.ja va 2s.c om*/ * A remote cache is either a local cache or a cluster cache * @param host * @param port * @param propFile * @throws IOException */ public static void startup(String host, int port, String propFile) throws IOException { if (remoteCacheServer != null) { throw new IllegalArgumentException("Server already started."); } synchronized (RemoteCacheServer.class) { if (remoteCacheServer != null) { return; } if (log.isInfoEnabled()) { log.info("ConfigFileName = [" + propFile + "]"); } try { // 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(DEFAULT_RMI_SOCKET_FACTORY_TIMEOUT_MS); socket.setSoLinger(false, 0); return socket; } public ServerSocket createServerSocket(int port) throws IOException { return new ServerSocket(port); } }); } catch (Exception e) { log.error("Problem setting custom RMI Socket Factory.", e); } // TODO: make automatic RemoteCacheServerAttributes rcsa = new RemoteCacheServerAttributes(); rcsa.setConfigFileName(propFile); Properties prop = RemoteUtils.loadProps(propFile); // Properties prop = PropertyLoader.loadProperties( propFile ); String servicePortStr = prop.getProperty(REMOTE_CACHE_SERVICE_PORT); int servicePort = -1; try { servicePort = Integer.parseInt(servicePortStr); rcsa.setServicePort(servicePort); log.debug("Remote cache service uses port number " + servicePort + "."); } catch (NumberFormatException ignore) { log.debug("Remote cache service port property " + REMOTE_CACHE_SERVICE_PORT + " not specified. An anonymous port will be used."); } String lccStr = prop.getProperty(REMOTE_LOCAL_CLUSTER_CONSISTENCY); if (lccStr == null) { lccStr = "true"; } boolean lcc = Boolean.valueOf(lccStr).booleanValue(); rcsa.setLocalClusterConsistency(lcc); String acgStr = prop.getProperty(REMOTE_ALLOW_CLUSTER_GET); if (acgStr == null) { acgStr = "true"; } boolean acg = Boolean.valueOf(acgStr).booleanValue(); rcsa.setAllowClusterGet(acg); if (log.isInfoEnabled()) { log.info("Creating server with these attributes " + rcsa); } // CREATE SERVER remoteCacheServer = new RemoteCacheServer(rcsa); if (host == null) { host = ""; } // Register the RemoteCacheServer remote object in the registry. serviceName = prop.getProperty(REMOTE_CACHE_SERVICE_NAME, REMOTE_CACHE_SERVICE_VAL).trim(); if (log.isInfoEnabled()) { log.info("Binding server to " + host + ":" + port + " with the name " + serviceName); } try { Naming.rebind("//" + host + ":" + port + "/" + serviceName, remoteCacheServer); } catch (MalformedURLException ex) { // impossible case. throw new IllegalArgumentException(ex.getMessage() + "; host=" + host + ", port=" + port); } } }
From source file:org.apache.jk.common.ChannelSocket.java
public void accept(MsgContext ep) throws IOException { if (sSocket == null) return;//from w w w.j a v a 2 s. co m Socket s = sSocket.accept(); ep.setNote(socketNote, s); if (log.isDebugEnabled()) log.debug("Accepted socket " + s); if (linger > 0) s.setSoLinger(true, linger); if (socketTimeout > 0) s.setSoTimeout(socketTimeout); s.setTcpNoDelay(tcpNoDelay); // set socket tcpnodelay state requestCount++; InputStream is = new BufferedInputStream(s.getInputStream()); OutputStream os; if (BUFFER_WRITE) os = new BufferedOutputStream(s.getOutputStream()); else os = s.getOutputStream(); ep.setNote(isNote, is); ep.setNote(osNote, os); ep.setControl(tp); }
From source file:org.apache.jk.common.ChannelSocket.java
public void destroy() throws IOException { running = false;/*from w ww. java2 s . c o m*/ try { /* If we disabled the channel return */ if (port == 0) return; tp.shutdown(); // Need to create a connection to unlock the accept(); Socket s; if (inet == null) { s = new Socket("127.0.0.1", port); } else { s = new Socket(inet, port); // setting soLinger to a small value will help shutdown the // connection quicker s.setSoLinger(true, 0); } s.close(); sSocket.close(); // XXX? if (tpOName != null) { Registry.getRegistry().unregisterComponent(tpOName); } } catch (Exception e) { log.info("Error shutting down the channel " + port + " " + e.toString()); if (log.isDebugEnabled()) log.debug("Trace", e); } }
From source file:org.apache.jmeter.protocol.tcp.sampler.TCPSampler.java
private Socket getSocket(String socketKey) { Map<String, Object> cp = tp.get(); Socket con = null; if (isReUseConnection()) { con = (Socket) cp.get(socketKey); if (con != null) { log.debug(this + " Reusing connection " + con); //$NON-NLS-1$ }//from w w w . j av a2 s. c om } if (con == null) { // Not in cache, so create new one and cache it try { closeSocket(socketKey); // Bug 44910 - close previous socket (if any) SocketAddress sockaddr = new InetSocketAddress(getServer(), getPort()); con = new Socket(); if (getPropertyAsString(SO_LINGER, "").length() > 0) { con.setSoLinger(true, getSoLinger()); } con.connect(sockaddr, getConnectTimeout()); if (log.isDebugEnabled()) { log.debug("Created new connection " + con); //$NON-NLS-1$ } cp.put(socketKey, con); } catch (UnknownHostException e) { log.warn("Unknown host for " + getLabel(), e);//$NON-NLS-1$ cp.put(ERRKEY, e.toString()); return null; } catch (IOException e) { log.warn("Could not create socket for " + getLabel(), e); //$NON-NLS-1$ cp.put(ERRKEY, e.toString()); return null; } } // (re-)Define connection params - Bug 50977 try { con.setSoTimeout(getTimeout()); con.setTcpNoDelay(getNoDelay()); if (log.isDebugEnabled()) { log.debug(this + " Timeout " + getTimeout() + " NoDelay " + getNoDelay()); //$NON-NLS-1$ } } catch (SocketException se) { log.warn("Could not set timeout or nodelay for " + getLabel(), se); //$NON-NLS-1$ cp.put(ERRKEY, se.toString()); } return con; }