List of usage examples for java.net Socket setSoLinger
public void setSoLinger(boolean on, int linger) throws SocketException
From source file:com.cws.esolutions.core.utils.NetworkUtils.java
/** * Creates an telnet connection to a target host and port number. Silently * succeeds if no issues are encountered, if so, exceptions are logged and * re-thrown back to the requestor./*from w ww . j a va 2 s .c o m*/ * * If an exception is thrown during the <code>socket.close()</code> operation, * it is logged but NOT re-thrown. It's not re-thrown because it does not indicate * a connection failure (indeed, it means the connection succeeded) but it is * logged because continued failures to close the socket could result in target * system instability. * * @param hostName - The target host to make the connection to * @param portNumber - The port number to attempt the connection on * @param timeout - The timeout for the connection * @throws UtilityException {@link com.cws.esolutions.core.utils.exception.UtilityException} if an error occurs processing */ public static final synchronized void executeTelnetRequest(final String hostName, final int portNumber, final int timeout) throws UtilityException { final String methodName = NetworkUtils.CNAME + "#executeTelnetRequest(final String hostName, final int portNumber, final int timeout) throws UtilityException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug(hostName); DEBUGGER.debug("portNumber: {}", portNumber); DEBUGGER.debug("timeout: {}", timeout); } Socket socket = null; try { synchronized (new Object()) { if (InetAddress.getByName(hostName) == null) { throw new UnknownHostException("No host was found in DNS for the given name: " + hostName); } InetSocketAddress socketAddress = new InetSocketAddress(hostName, portNumber); socket = new Socket(); socket.setSoTimeout((int) TimeUnit.SECONDS.toMillis(timeout)); socket.setSoLinger(false, 0); socket.setKeepAlive(false); socket.connect(socketAddress, (int) TimeUnit.SECONDS.toMillis(timeout)); if (!(socket.isConnected())) { throw new ConnectException("Failed to connect to host " + hostName + " on port " + portNumber); } PrintWriter pWriter = new PrintWriter(socket.getOutputStream(), true); pWriter.println(NetworkUtils.TERMINATE_TELNET + NetworkUtils.CRLF); pWriter.flush(); pWriter.close(); } } catch (ConnectException cx) { throw new UtilityException(cx.getMessage(), cx); } catch (UnknownHostException ux) { throw new UtilityException(ux.getMessage(), ux); } catch (SocketException sx) { throw new UtilityException(sx.getMessage(), sx); } catch (IOException iox) { throw new UtilityException(iox.getMessage(), iox); } finally { try { if ((socket != null) && (!(socket.isClosed()))) { socket.close(); } } catch (IOException iox) { // log it - this could cause problems later on ERROR_RECORDER.error(iox.getMessage(), iox); } } }
From source file:com.subgraph.vega.internal.http.proxy.VegaHttpServerConnection.java
public void bind(final Socket socket, final HttpParams params) throws IOException { if (socket == null) { throw new IllegalArgumentException("Socket may not be null"); }//from w ww .j a v a 2 s . c om 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); } super.bind(socket, params); }
From source file:com.cws.esolutions.core.utils.NetworkUtils.java
/** * Creates an telnet connection to a target host and port number. Silently * succeeds if no issues are encountered, if so, exceptions are logged and * re-thrown back to the requestor./*from www . j av a2s.c o m*/ * * If an exception is thrown during the <code>socket.close()</code> operation, * it is logged but NOT re-thrown. It's not re-thrown because it does not indicate * a connection failure (indeed, it means the connection succeeded) but it is * logged because continued failures to close the socket could result in target * system instability. * * @param hostName - The target host to make the connection to * @param portNumber - The port number to attempt the connection on * @param timeout - How long to wait for a connection to establish or a response from the target * @param object - The serializable object to send to the target * @return <code>Object</code> as output from the request * @throws UtilityException {@link com.cws.esolutions.core.utils.exception.UtilityException} if an error occurs processing */ public static final synchronized Object executeTcpRequest(final String hostName, final int portNumber, final int timeout, final Object object) throws UtilityException { final String methodName = NetworkUtils.CNAME + "#executeTcpRequest(final String hostName, final int portNumber, final int timeout, final Object object) throws UtilityException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug(hostName); DEBUGGER.debug("portNumber: {}", portNumber); DEBUGGER.debug("timeout: {}", timeout); DEBUGGER.debug("object: {}", object); } Socket socket = null; Object resObject = null; try { synchronized (new Object()) { if (StringUtils.isEmpty(InetAddress.getByName(hostName).toString())) { throw new UnknownHostException("No host was found in DNS for the given name: " + hostName); } InetSocketAddress socketAddress = new InetSocketAddress(hostName, portNumber); socket = new Socket(); socket.setSoTimeout((int) TimeUnit.SECONDS.toMillis(timeout)); socket.setSoLinger(false, 0); socket.setKeepAlive(false); socket.connect(socketAddress, (int) TimeUnit.SECONDS.toMillis(timeout)); if (!(socket.isConnected())) { throw new ConnectException("Failed to connect to host " + hostName + " on port " + portNumber); } ObjectOutputStream objectOut = new ObjectOutputStream(socket.getOutputStream()); if (DEBUG) { DEBUGGER.debug("ObjectOutputStream: {}", objectOut); } objectOut.writeObject(object); resObject = new ObjectInputStream(socket.getInputStream()).readObject(); if (DEBUG) { DEBUGGER.debug("resObject: {}", resObject); } PrintWriter pWriter = new PrintWriter(socket.getOutputStream(), true); pWriter.println(NetworkUtils.TERMINATE_TELNET + NetworkUtils.CRLF); pWriter.flush(); pWriter.close(); } } catch (ConnectException cx) { throw new UtilityException(cx.getMessage(), cx); } catch (UnknownHostException ux) { throw new UtilityException(ux.getMessage(), ux); } catch (SocketException sx) { throw new UtilityException(sx.getMessage(), sx); } catch (IOException iox) { throw new UtilityException(iox.getMessage(), iox); } catch (ClassNotFoundException cnfx) { throw new UtilityException(cnfx.getMessage(), cnfx); } finally { try { if ((socket != null) && (!(socket.isClosed()))) { socket.close(); } } catch (IOException iox) { // log it - this could cause problems later on ERROR_RECORDER.error(iox.getMessage(), iox); } } return resObject; }
From source file:com.linuxbox.enkive.mailprocessor.AbstractMailProcessor.java
@Override public void initializeProcessor(AbstractSocketServer server, Socket socket) { if (LOGGER.isTraceEnabled()) LOGGER.trace("in initializeProcessor"); this.server = server; this.socket = socket; closeInitiated = false;/*from w w w . j a v a 2 s . co m*/ // set the socket linger options, so the socket closes immediately when // closed try { socket.setSoLinger(false, 0); } catch (SocketException e) { if (LOGGER.isDebugEnabled()) LOGGER.debug("enkive session unable to set socket linger " + e); } if (isJmxEnabled()) { String type = getClass().getSimpleName(); String name = "Port " + socket.getPort(); mBeanName = MBeanUtils.registerMBean(this, type, name); if (LOGGER.isTraceEnabled()) LOGGER.trace("registered mbean " + mBeanName + " (" + type + "/" + name + ")"); } initialized = true; }
From source file:org.apache.axis2.transport.http.server.AxisHttpConnectionImpl.java
public AxisHttpConnectionImpl(final Socket socket, final HttpParams params) throws IOException { super();// w w w. j av a 2s . co m 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:com.epam.reportportal.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"); }//from w w w . j a va 2 s . c o m 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); 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.mycard.net.network.AndroidHttpClientConnection.java
/*** * Bind socket and set HttpParams to AndroidHttpClientConnection * @param socket outgoing socket/*from www.j a v a2 s . c om*/ * @param params HttpParams * @throws IOException */ public void bind(final Socket socket, final HttpParams params) throws IOException { if (socket == null) { throw new IllegalArgumentException("Socket may not be null"); } if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } assertNotOpen(); socket.setTcpNoDelay(HttpConnectionParams.getTcpNoDelay(params)); socket.setSoTimeout(HttpConnectionParams.getSoTimeout(params)); int linger = HttpConnectionParams.getLinger(params); if (linger >= 0) { socket.setSoLinger(linger > 0, linger); } this.socket = socket; int buffersize = HttpConnectionParams.getSocketBufferSize(params); this.inbuffer = new SocketInputBuffer(socket, buffersize, params); this.outbuffer = new SocketOutputBuffer(socket, buffersize, params); maxHeaderCount = params.getIntParameter(CoreConnectionPNames.MAX_HEADER_COUNT, -1); maxLineLength = params.getIntParameter(CoreConnectionPNames.MAX_LINE_LENGTH, -1); this.requestWriter = new HttpRequestWriter(outbuffer, null, params); this.metrics = new HttpConnectionMetricsImpl(inbuffer.getMetrics(), outbuffer.getMetrics()); this.open = true; }
From source file:net.lightbody.bmp.proxy.jetty.util.ThreadedServer.java
/** * Accept socket connection. May be overriden by derived class to create specialist * serversockets (eg SSL)./*from w w w . j a v a 2 s.c om*/ * * @param serverSocket * @param timeout The time to wait for a connection. Normally passed the ThreadPool maxIdleTime. * @return Accepted Socket */ protected Socket acceptSocket(int timeout) { try { Socket s = null; if (_listen != null) { if (_soTimeOut != timeout) { _soTimeOut = timeout; _listen.setSoTimeout(_soTimeOut); } s = _listen.accept(); try { if (getMaxIdleTimeMs() >= 0) s.setSoTimeout(getMaxIdleTimeMs()); if (_lingerTimeSecs >= 0) s.setSoLinger(true, _lingerTimeSecs); else s.setSoLinger(false, 0); } catch (Exception e) { LogSupport.ignore(log, e); } } return s; } catch (java.net.SocketException e) { // TODO - this is caught and ignored due strange // exception from linux java1.2.v1a LogSupport.ignore(log, e); } catch (InterruptedIOException e) { LogSupport.ignore(log, e); } catch (IOException e) { log.warn(LogSupport.EXCEPTION, e); } return null; }
From source file:com.clavain.munin.MuninNode.java
/** * Will load the plugin list from munin-node *//* ww w .j a v a 2 s. c om*/ public boolean loadPlugins() { setLoadedPlugins(new CopyOnWriteArrayList<MuninPlugin>()); String l_lastProceeded = ""; try { Socket cs = new Socket(); cs.setKeepAlive(false); cs.setSoLinger(true, 0); cs.setReuseAddress(true); cs.setSoTimeout(com.clavain.muninmxcd.socketTimeout); if (!str_via.equals("unset")) { cs.connect(new InetSocketAddress(this.getStr_via(), this.getPort()), com.clavain.muninmxcd.socketTimeout); } else { cs.connect(new InetSocketAddress(this.getHostname(), this.getPort()), com.clavain.muninmxcd.socketTimeout); } if (p.getProperty("kill.sockets").equals("true")) { SocketCheck sc = new SocketCheck(cs, getUnixtime()); sc.setHostname(this.getHostname()); com.clavain.muninmxcd.v_sockets.add(sc); } PrintStream os = new PrintStream(cs.getOutputStream()); BufferedReader in = new BufferedReader(new InputStreamReader(cs.getInputStream())); String s = in.readLine(); if (s != null) { // Set version os.println("version"); Thread.sleep(150); s = in.readLine(); String version = s.substring(s.indexOf(":") + 1, s.length()).trim(); this.str_muninVersion = version; if (authpw != null) { // if authpw is set, verify if (!authpw.trim().equals("")) { os.println("config muninmxauth"); Thread.sleep(150); String apw = in.readLine(); s = in.readLine(); if (!apw.trim().equals(this.getAuthpw())) { logger.error("Invalid muninmxauth password for host: " + this.getHostname()); cs.close(); return false; } } } // check anyway if muninmxauth plugin is present else { os.println("config muninmxauth"); Thread.sleep(100); String apw = in.readLine(); if (!apw.trim().equals("# Unknown service")) { logger.error( "no auth password given, but muninmxauth plugin present on " + this.getHostname()); cs.close(); return false; } s = in.readLine(); } // get list of available plugins if (str_via.equals("unset")) { os.println("list"); } else { os.println("list " + str_hostname); } Thread.sleep(250); s = in.readLine(); // if response is empty and host is not via, do a list $hostname if (s.trim().equals("") && str_via.equals("unset")) { logger.info("Plugin Response Empty on " + this.getHostname() + " trying to load with list $hostname"); os.println("list " + this.getHostname()); Thread.sleep(250); s = in.readLine(); } String l_tmp; StringTokenizer l_st = new StringTokenizer(s, " "); // create plugin MuninPlugin l_mp = new MuninPlugin(); // negative support ArrayList<String> tmp_negatives = new ArrayList<String>(); while (l_st.hasMoreTokens()) { String l_strPlugin = l_st.nextToken(); // check for track_pkg and muninmx essentials if (l_strPlugin.equals("muninmx_trackpkg")) { this.setTrack_pkg(true); continue; } // got essentials? if (l_strPlugin.equals("muninmx_essentials")) { this.setEssentials(true); continue; } if (isPluginIgnored(l_strPlugin.toUpperCase())) { continue; } l_mp.setPluginName(l_strPlugin); os.println("config " + l_strPlugin); // create graphs for plugin int l_iGraphsFound = 0; int l_iTmp = 0; MuninGraph l_mg = new MuninGraph(); l_mg.setQueryInterval(this.getQueryInterval()); while ((l_tmp = in.readLine()) != null) { if (l_tmp.startsWith(".")) { break; } // collect graphs only for plugin String l_strName; String l_strType; String l_strValue; if (!l_tmp.contains("graph_") && !l_tmp.trim().equals("") && !l_tmp.contains("host_name") && !l_tmp.contains("multigraph") && !l_tmp.trim().equals("graph no") && !l_tmp.trim().equals("# Bad exit") && !l_tmp.trim().contains("info Currently our peer") && !l_tmp.trim().startsWith("#") && !l_tmp.trim().contains("Bonding interface errors")) { l_lastProceeded = l_tmp; l_strName = l_tmp.substring(0, l_tmp.indexOf(".")); l_strType = l_tmp.substring(l_tmp.indexOf(".") + 1, l_tmp.indexOf(" ")); l_strValue = l_tmp.substring(l_tmp.indexOf(" ") + 1, l_tmp.length()); //System.err.println("Name: " + l_strName + " Type: " + l_strType + " Value: " + l_strValue); if (l_strType.equals("label")) { l_iTmp++; if (l_iTmp > 1) { l_mp.addGraph(l_mg); l_mg = new MuninGraph(); l_mg.setQueryInterval(this.getQueryInterval()); } l_mg.setGraphName(l_strName); l_mg.setGraphLabel(l_strValue); } else if (l_strType.equals("draw")) { l_mg.setGraphDraw(l_strValue); } else if (l_strType.equals("type")) { l_mg.setGraphType(l_strValue); } else if (l_strType.equals("info")) { l_mg.setGraphInfo(l_strValue); } else if (l_strType.equals("negative")) { // add to temporary negative list to set negatives later tmp_negatives.add(l_strValue); } //System.out.println(l_strName); //System.out.println(l_strType); //System.out.println(l_strValue); } else { // set plugin title if (l_tmp.contains("graph_title")) { l_mp.setPluginTitle(l_tmp.substring(12, l_tmp.length())); } // set plugin info, if any if (l_tmp.contains("graph_info")) { l_mp.setPluginInfo(l_tmp.substring(11, l_tmp.length())); } // set graph category if (l_tmp.contains("graph_category")) { l_mp.setPluginCategory(l_tmp.substring(15, l_tmp.length())); } // set graph vlabel if (l_tmp.contains("graph_vlabel")) { l_mp.setPluginLabel(l_tmp.substring(13, l_tmp.length())); } // set plugin title if (l_tmp.contains("graph_mxdraw")) { l_mp.setStr_LineMode(l_tmp.substring(13, l_tmp.length())); } } } // add to pluginlist l_mp.addGraph(l_mg); Iterator it = l_mp.getGraphs().iterator(); while (it.hasNext()) { MuninGraph l_mpNg = (MuninGraph) it.next(); if (tmp_negatives.contains(l_mpNg.getGraphName())) { l_mpNg.setNegative(true); } } // add plugin if it got valid graphs and add nodeid (req. for alerts) if (l_mp.getGraphs().size() > 0) { l_mp.set_NodeId(this.getNode_id()); getLoadedPlugins().add(l_mp); } // flush temporary negatives tmp_negatives.clear(); l_mp = null; l_mp = new MuninPlugin(); //String l_strGraphTitle = s.substring(s.indexOf("graph_title") + 11,s.length()); //System.out.println(" - " + l_strGraphTitle); } cs.close(); in.close(); os.close(); last_plugin_load = getUnixtime(); //System.out.println(s); } else { cs.close(); in.close(); os.close(); logger.warn("Error loading plugins on " + str_hostname + " (" + this.getNode_id() + "). Check connectivity or munin-node"); } /* for (MuninPlugin l_mn : getLoadedPlugins()) { i_GraphCount = i_GraphCount + l_mn.getGraphs().size(); logger.debug(l_mn.getGraphs().size() + " graphs found for plugin: " + l_mn.getPluginName().toUpperCase() + " on node: " + this.getNodename()); }*/ } catch (Exception ex) { logger.error("Error loading plugins on " + str_hostname + " (" + this.getNode_id() + ") : " + ex.getMessage()); ex.printStackTrace(); return false; } return true; }
From source file:com.sun.grizzly.http.jk.common.ChannelSocket.java
private void unLockSocket() throws IOException { // Need to create a connection to unlock the accept(); Socket s; InetAddress ladr = inet;/* ww w .ja va2s . c o m*/ if (port == 0) { return; } if (ladr == null || "0.0.0.0".equals(ladr.getHostAddress())) { ladr = InetAddress.getLocalHost(); } s = new Socket(ladr, port); // setting soLinger to a small value will help shutdown the // connection quicker s.setSoLinger(true, 0); s.close(); }