List of usage examples for java.net Socket setReuseAddress
public void setReuseAddress(boolean on) throws SocketException
From source file:com.eviware.soapui.impl.wsdl.support.http.SoapUISSLSocketFactory.java
/** * @since 4.1/*from w w w.ja v a2 s.c o 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.gargoylesoftware.htmlunit.httpclient.HtmlUnitSSLConnectionSocketFactory.java
/** * Connect via socket.//from w w w .j av a2 s .c o m * @param connectTimeout the timeout * @param socket the socket * @param host the host * @param remoteAddress the remote address * @param localAddress the local address * @param context the context * @return the created/connected socket * @throws IOException in case of problems */ @Override public Socket connectSocket(final int connectTimeout, final Socket socket, final HttpHost host, final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpContext context) throws IOException { final HttpHost socksProxy = SocksConnectionSocketFactory.getSocksProxy(context); if (socksProxy != null) { final Socket underlying = SocksConnectionSocketFactory.createSocketWithSocksProxy(socksProxy); underlying.setReuseAddress(true); // TODO: commented out for HttpClient 4.3 // final int soTimeout = HttpConnectionParams.getSoTimeout(params); final SocketAddress socksProxyAddress = new InetSocketAddress(socksProxy.getHostName(), socksProxy.getPort()); try { //underlying.setSoTimeout(soTimeout); underlying.connect(remoteAddress, connectTimeout); } catch (final SocketTimeoutException ex) { throw new ConnectTimeoutException("Connect to " + socksProxyAddress + " timed out"); } final Socket sslSocket = getSSLSocketFactory().createSocket(underlying, socksProxy.getHostName(), socksProxy.getPort(), true); configureSocket((SSLSocket) sslSocket, context); return sslSocket; } try { return super.connectSocket(connectTimeout, socket, host, remoteAddress, localAddress, context); } catch (final IOException e) { if (useInsecureSSL_ && "handshake alert: unrecognized_name".equals(e.getMessage())) { setEmptyHostname(host); return super.connectSocket(connectTimeout, createSocket(context), host, remoteAddress, localAddress, context); } throw e; } }
From source file:org.eclipse.ecf.internal.provider.filetransfer.httpclient4.ECFHttpClientSecureProtocolSocketFactory.java
private void performConnection(final Socket socket, final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpParams params) throws SocketException, IOException { try {//from w w w. j av a 2s. com socket.setReuseAddress(HttpConnectionParams.getSoReuseaddr(params)); socket.bind(localAddress); int connectionTimeout = HttpConnectionParams.getConnectionTimeout(params); int socketTimeout = HttpConnectionParams.getSoTimeout(params); socket.connect(remoteAddress, connectionTimeout); socket.setSoTimeout(socketTimeout); } catch (SocketException e) { Trace.catching(Activator.PLUGIN_ID, DebugOptions.EXCEPTIONS_CATCHING, ECFHttpClientSecureProtocolSocketFactory.class, "performConnection", e); //$NON-NLS-1$ fireEvent(this.socketConnectListener, new SocketClosedEvent(source, socket, socket)); Trace.throwing(Activator.PLUGIN_ID, DebugOptions.EXCEPTIONS_THROWING, ECFHttpClientSecureProtocolSocketFactory.class, "performConnection", e); //$NON-NLS-1$ throw e; } catch (IOException e) { Trace.catching(Activator.PLUGIN_ID, DebugOptions.EXCEPTIONS_CATCHING, ECFHttpClientSecureProtocolSocketFactory.class, "performConnection", e); //$NON-NLS-1$ fireEvent(this.socketConnectListener, new SocketClosedEvent(source, socket, socket)); Trace.throwing(Activator.PLUGIN_ID, DebugOptions.EXCEPTIONS_THROWING, ECFHttpClientSecureProtocolSocketFactory.class, "performConnection", e); //$NON-NLS-1$ throw e; } }
From source file:at.gv.egovernment.moa.id.auth.validator.parep.client.szrgw.SZRGWSecureSocketFactory.java
/** * @see SecureProtocolSocketFactory#createSocket(java.lang.String,int,java.net.InetAddress,int,org.apache.commons.httpclient.params.HttpConnectionParams) *//*from w ww .j a v a 2s. c o m*/ public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort, HttpConnectionParams params) throws IOException, UnknownHostException, org.apache.commons.httpclient.ConnectTimeoutException { Socket socket = createSocket(host, port, clientHost, clientPort); if (socket != null) { // socket.setKeepAlive(false); if (params.getReceiveBufferSize() >= 0) socket.setReceiveBufferSize(params.getReceiveBufferSize()); if (params.getSendBufferSize() >= 0) socket.setSendBufferSize(params.getSendBufferSize()); socket.setReuseAddress(true); if (params.getSoTimeout() >= 0) socket.setSoTimeout(params.getSoTimeout()); } return socket; }
From source file:org.openqa.selenium.remote.ReusingSocketSocketFactory.java
public Socket connectSocket(Socket sock, String host, int port, InetAddress localAddress, int localPort, HttpParams params) throws IOException { if (host == null) { throw new IllegalArgumentException("Target host may not be null."); }// www . j a v a2 s .c om if (params == null) { throw new IllegalArgumentException("Parameters may not be null."); } if (sock == null) sock = createSocket(); sock.setReuseAddress(true); // This is the 1 line added by kristian if ((localAddress != null) || (localPort > 0)) { // we need to bind explicitly if (localPort < 0) localPort = 0; // indicates "any" InetSocketAddress isa = new InetSocketAddress(localAddress, localPort); sock.bind(isa); } int timeout = HttpConnectionParams.getConnectionTimeout(params); InetSocketAddress remoteAddress; if (this.nameResolver != null) { remoteAddress = new InetSocketAddress(this.nameResolver.resolve(host), port); } else { remoteAddress = new InetSocketAddress(host, port); } try { sock.connect(remoteAddress, timeout); } catch (SocketTimeoutException ex) { throw new ConnectTimeoutException("Connect to " + remoteAddress + " timed out"); } return sock; }
From source file:org.apache.chemistry.opencmis.client.bindings.spi.http.ApacheClientHttpInvoker.java
/** * Builds a SSL Socket Factory for the Apache HTTP Client. *//*w ww .j a v a2 s .c om*/ private SchemeLayeredSocketFactory getSSLSocketFactory(final UrlBuilder url, final BindingSession session) { // get authentication provider AuthenticationProvider authProvider = CmisBindingsHelper.getAuthenticationProvider(session); // check SSL Socket Factory final SSLSocketFactory sf = authProvider.getSSLSocketFactory(); if (sf == null) { // no custom factory -> return default factory return org.apache.http.conn.ssl.SSLSocketFactory.getSocketFactory(); } // check hostame verifier and use default if not set final HostnameVerifier hv = (authProvider.getHostnameVerifier() == null ? new BrowserCompatHostnameVerifier() : authProvider.getHostnameVerifier()); if (hv instanceof X509HostnameVerifier) { return new org.apache.http.conn.ssl.SSLSocketFactory(sf, (X509HostnameVerifier) hv); } // build new socket factory return new SchemeLayeredSocketFactory() { @Override public boolean isSecure(Socket sock) { return true; } @Override public Socket createSocket(HttpParams params) throws IOException { return sf.createSocket(); } @Override public Socket connectSocket(final Socket socket, final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpParams params) throws IOException { Socket sock = socket != null ? socket : createSocket(params); 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) { closeSocket(sock); throw new ConnectTimeoutException("Connect to " + remoteAddress + " timed out!"); } String host; if (remoteAddress instanceof HttpInetSocketAddress) { host = ((HttpInetSocketAddress) remoteAddress).getHttpHost().getHostName(); } else { host = remoteAddress.getHostName(); } SSLSocket sslSocket; if (sock instanceof SSLSocket) { sslSocket = (SSLSocket) sock; } else { int port = remoteAddress.getPort(); sslSocket = (SSLSocket) sf.createSocket(sock, host, port, true); } verify(hv, host, sslSocket); return sslSocket; } @Override public Socket createLayeredSocket(final Socket socket, final String host, final int port, final HttpParams params) throws IOException { SSLSocket sslSocket = (SSLSocket) sf.createSocket(socket, host, port, true); verify(hv, host, sslSocket); return sslSocket; } }; }
From source file:orca.ektorp.client.ContextualSSLSocketFactory.java
/** * @since 4.1// w ww . j av a 2 s . com * @param socket socket * @param remoteAddress remote address * @param localAddress local address * @param params HTTP params * @throws IOException in case of IO error * @throws UnknownHostException in case of unknonwn host * @throws ConnectTimeoutException in case of connect timeout * @return returns the socket */ 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"); } //Here! Socket sock = socket != null ? socket : this.socketfactory.createSocket(); 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 + " timed out"); } String hostname; if (remoteAddress instanceof HttpInetSocketAddress) { hostname = ((HttpInetSocketAddress) remoteAddress).getHttpHost().getHostName(); } else { hostname = remoteAddress.getHostName(); } SSLSocket sslsock; // Setup SSL layering if necessary if (sock instanceof SSLSocket) { sslsock = (SSLSocket) sock; } else { int port = remoteAddress.getPort(); sslsock = (SSLSocket) this.socketfactory.createSocket(sock, hostname, port, true); prepareSocket(sslsock); } if (this.hostnameVerifier != null) { try { this.hostnameVerifier.verify(hostname, 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.clavain.munin.MuninNode.java
public void run() { b_isRunning = true;/*from w ww.j ava2s . c o m*/ if (this.str_via.equals("unset")) { logger.info(getHostname() + " Monitoring job started"); } else { logger.info(getHostname() + " (VIA: " + this.str_via + ") Monitoring job started"); } int iCurTime = getUnixtime(); int iPluginRefreshTime = last_plugin_load + Integer.parseInt(p.getProperty("plugin.refreshtime")); try { // update plugins, maybe we have some new :) // double try to load plugins if fail if (getPluginList().size() > 0) { if (!is_init) { logger.info("[Job: " + getHostname() + "] Updating Database"); // update graphs in database too for (MuninPlugin it_pl : getPluginList()) { if (it_pl.getGraphs().size() > 0) { //logger.info(it_pl.getPluginName()); dbUpdatePluginForNode(getNode_id(), it_pl); } } // delete now missing plugins dbDeleteMissingPlugins(getNode_id(), getPluginList()); logger.info("[Job: " + getHostname() + "] Databaseupdate Done"); is_init = true; } else { if (iCurTime > iPluginRefreshTime) { logger.info("Refreshing Plugins on " + this.getHostname()); this.loadPlugins(); dbUpdateAllPluginsForNode(this); } } } else { this.loadPlugins(); } Socket clientSocket = new Socket(); clientSocket.setSoTimeout(com.clavain.muninmxcd.socketTimeout); clientSocket.setKeepAlive(false); clientSocket.setReuseAddress(true); if (this.str_via.equals("unset")) { clientSocket.connect(new InetSocketAddress(this.getHostname(), this.getPort()), com.clavain.muninmxcd.socketTimeout); } else { clientSocket.connect(new InetSocketAddress(this.getStr_via(), this.getPort()), com.clavain.muninmxcd.socketTimeout); } lastSocket = clientSocket; SocketCheck sc = new SocketCheck(clientSocket, getUnixtime()); if (p.getProperty("kill.sockets").equals("true")) { sc.setHostname(this.getHostname()); com.clavain.muninmxcd.v_sockets.add(sc); } this.i_lastRun = getUnixtime(); // track packages? if (this.track_pkg) { updateTrackPackages(clientSocket); } // gather essentials? if (this.essentials) { updateEssentials(clientSocket); } // update graphs for all plugins Iterator it = this.getLoadedPlugins().iterator(); while (it.hasNext()) { MuninPlugin l_mp = (MuninPlugin) it.next(); if (logMore) { logger.info(getHostname() + " fetching graphs for " + l_mp.getPluginName().toUpperCase()); } // snmp support if (!str_via.equals("unset")) { l_mp.updateAllGraps(this.getStr_via(), this.getPort(), clientSocket, getQueryInterval()); } else { l_mp.updateAllGraps(this.getHostname(), this.getPort(), clientSocket, getQueryInterval()); } // add all graphs to insertion queue for mongodb queuePluginFetch(l_mp.returnAllGraphs(), l_mp.getPluginName()); } clientSocket.close(); if (p.getProperty("kill.sockets").equals("true")) { com.clavain.muninmxcd.v_sockets.remove(sc); } sc = null; } catch (Exception ex) { logger.fatal("Error in thread for host: " + getHostname() + " : " + ex.getLocalizedMessage()); ex.printStackTrace(); } int iRunTime = getUnixtime() - iCurTime; dbUpdateLastContact(this.getNode_id()); logger.info(getHostname() + " Monitoring job stopped - runtime: " + iRunTime); }
From source file:monasca.api.integration.docker.ITInfluxDBTest.java
private void waitForPortReady(String host, int port) { System.out.println("waiting to connect to host [" + host + "] on port [" + port + "]"); Socket s = null; boolean isPortReady = false; int tryCount = 0; while (!isPortReady) { if (tryCount >= MAX_CONNECT_PORT_TRIES) { System.err.println("Failed to connect to host [" + host + "] on port [" + port + "] in " + "[" + tryCount + "] tries"); tearDown();/*from w w w . j a va 2s . co m*/ System.exit(-1); } try { s = new Socket(); s.setReuseAddress(true); SocketAddress sa = new InetSocketAddress(host, port); s.connect(sa, 50000); isPortReady = true; System.out.println( "Took " + tryCount + " tries to connect to host [" + host + "] on port" + "[" + port + "]"); } catch (Exception e) { tryCount++; } } if (s != null) { try { s.close(); } catch (Exception e) { System.err.print(e); } } }
From source file:com.clavain.munin.MuninNode.java
/** * Will load the plugin list from munin-node *//* w w w . j a v a 2 s.c o m*/ 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; }