List of usage examples for java.net Socket setSoTimeout
public synchronized void setSoTimeout(int timeout) throws SocketException
From source file:com.googlecode.xremoting.core.commonshttpclient.ssl.AuthSSLProtocolSocketFactory.java
/** * Attempts to get a new socket connection to the given host within the given time limit. * <p>//from w w w .j a v a 2 s. c o m * To circumvent the limitations of older JREs that do not support connect timeout 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 * determined */ public Socket createSocket(final String host, final int port, final InetAddress localAddress, final int localPort, final HttpConnectionParams params) throws IOException, UnknownHostException, ConnectTimeoutException { if (params == null) { throw new IllegalArgumentException("Parameters may not be null"); } int timeout = params.getConnectionTimeout(); SocketFactory socketfactory = getSSLContext().getSocketFactory(); if (timeout == 0) { Socket socket = socketfactory.createSocket(host, port, localAddress, localPort); doPreConnectSocketStuff(socket); return socket; } else { Socket socket = socketfactory.createSocket(); doPreConnectSocketStuff(socket); SocketAddress localaddr = new InetSocketAddress(localAddress, localPort); SocketAddress remoteaddr = new InetSocketAddress(host, port); if (timeout > 0 && socket.getSoTimeout() == 0) { // force SO timeout if not set so we don't freeze forever // during a handshake socket.setSoTimeout(timeout); } socket.bind(localaddr); socket.connect(remoteaddr, timeout); return socket; } }
From source file:com.raddle.tools.ClipboardTransferMain.java
private Object doInSocket(SocketCallback callback) { Socket socket = null; try {//from ww w .j ava2 s . c o m String address = serverAddrTxt.getText(); String[] ipport = address.split(":"); if (ipport.length != 2) { updateMessage("????"); return null; } socket = new Socket(); SocketAddress socketAddress = new InetSocketAddress(ipport[0], Integer.parseInt(ipport[1])); socket.connect(socketAddress, 2000); socket.setSoTimeout(10000); return callback.connected(socket); } catch (Exception e) { e.printStackTrace(); updateMessage("?" + e.getMessage()); return null; } finally { if (socket != null) { try { socket.getInputStream().close(); } catch (IOException e) { } try { socket.getOutputStream().close(); } catch (IOException e) { } try { socket.close(); } catch (IOException e) { } } } }
From source file:com.hp.it.spf.wsrp.axis.transport.http.HTTPSender.java
/** * Creates a socket connection to the SOAP server * * @param protocol "http" for standard, "https" for ssl. * @param host host name/*w w w .j av a2 s . c o m*/ * @param port port to connect to * @param otherHeaders buffer for storing additional headers that need to be sent * @param useFullURL flag to indicate if the complete URL has to be sent * * @throws IOException */ protected void getSocket(SocketHolder sockHolder, MessageContext msgContext, String protocol, String host, int port, int timeout, StringBuffer otherHeaders, BooleanHolder useFullURL) throws Exception { Hashtable options = getOptions(); if (timeout > 0) { if (options == null) { options = new Hashtable(); } options.put(DefaultSocketFactory.CONNECT_TIMEOUT, Integer.toString(timeout)); } SocketFactory factory = SocketFactoryFactory.getFactory(protocol, options); if (factory == null) { throw new IOException(Messages.getMessage("noSocketFactory", protocol)); } Socket sock = factory.create(host, port, otherHeaders, useFullURL); if (log.isDebugEnabled()) log.debug("sppmsg:getSocket -> Socket created for Host = " + host + " Port = " + port + " Protocol = " + protocol); if (timeout > 0) { sock.setSoTimeout(timeout); } sockHolder.setSocket(sock); }
From source file:org.apache.chemistry.opencmis.client.bindings.spi.http.ApacheClientHttpInvoker.java
/** * Builds a SSL Socket Factory for the Apache HTTP Client. *///from ww w. jav a 2s . c o m 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/*from w w w.j ava2 s .c o m*/ * @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:net.lightbody.bmp.proxy.jetty.http.ajp.AJP13Listener.java
/** * Handle Job. Implementation of ThreadPool.handle(), calls * handleConnection.//from www .ja v a 2s. c o m * * @param socket * A Connection. */ public void handleConnection(Socket socket) throws IOException { // Check acceptable remote servers if (_remoteServers != null && _remoteServers.length > 0) { boolean match = false; InetAddress inetAddress = socket.getInetAddress(); String hostAddr = inetAddress.getHostAddress(); String hostName = inetAddress.getHostName(); for (int i = 0; i < _remoteServers.length; i++) { if (hostName.equals(_remoteServers[i]) || hostAddr.equals(_remoteServers[i])) { match = true; break; } } if (!match) { log.warn("AJP13 Connection from un-approved host: " + inetAddress); return; } } // Handle the connection socket.setTcpNoDelay(true); socket.setSoTimeout(getMaxIdleTimeMs()); AJP13Connection connection = createConnection(socket); try { connection.handle(); } finally { connection.destroy(); } }
From source file:com.clavain.munin.MuninNode.java
/** * Will load the plugin list from munin-node *//*from w w w . ja va 2 s. co 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; }
From source file:org.openqa.selenium.server.ProxyHandler.java
protected HttpTunnel newHttpTunnel(HttpRequest request, HttpResponse response, InetAddress iaddr, int port, int timeoutMS) throws IOException { try {// w w w . ja v a 2 s . co m Socket socket = null; InputStream in = null; String chained_proxy_host = System.getProperty("http.proxyHost"); if (chained_proxy_host == null) { socket = new Socket(iaddr, port); socket.setSoTimeout(timeoutMS); socket.setTcpNoDelay(true); } else { int chained_proxy_port = Integer.getInteger("http.proxyPort", 8888).intValue(); Socket chain_socket = new Socket(chained_proxy_host, chained_proxy_port); chain_socket.setSoTimeout(timeoutMS); chain_socket.setTcpNoDelay(true); if (log.isDebugEnabled()) log.debug("chain proxy socket=" + chain_socket); LineInput line_in = new LineInput(chain_socket.getInputStream()); byte[] connect = request.toString().getBytes(org.openqa.jetty.util.StringUtil.__ISO_8859_1); chain_socket.getOutputStream().write(connect); String chain_response_line = line_in.readLine(); HttpFields chain_response = new HttpFields(); chain_response.read(line_in); // decode response int space0 = chain_response_line.indexOf(' '); if (space0 > 0 && space0 + 1 < chain_response_line.length()) { int space1 = chain_response_line.indexOf(' ', space0 + 1); if (space1 > space0) { int code = Integer.parseInt(chain_response_line.substring(space0 + 1, space1)); if (code >= 200 && code < 300) { socket = chain_socket; in = line_in; } else { Enumeration iter = chain_response.getFieldNames(); while (iter.hasMoreElements()) { String name = (String) iter.nextElement(); if (!_DontProxyHeaders.containsKey(name)) { Enumeration values = chain_response.getValues(name); while (values.hasMoreElements()) { String value = (String) values.nextElement(); response.setField(name, value); } } } response.sendError(code); if (!chain_socket.isClosed()) chain_socket.close(); } } } } if (socket == null) return null; return new HttpTunnel(socket, in, null); } catch (IOException e) { log.debug(e); response.sendError(HttpResponse.__400_Bad_Request); return null; } }
From source file:org.apache.hadoop.hdfs.DataStreamer.java
/** * Create a socket for a write pipeline//from w w w . j a v a 2s. c o m * * @param first the first datanode * @param length the pipeline length * @param client client * @return the socket connected to the first datanode */ static Socket createSocketForPipeline(final DatanodeInfo first, final int length, final DFSClient client) throws IOException { final String dnAddr = first.getXferAddr(client.getConf().connectToDnViaHostname); if (DFSClient.LOG.isDebugEnabled()) { DFSClient.LOG.debug("Connecting to datanode " + dnAddr); } final InetSocketAddress isa = NetUtils.createSocketAddr(dnAddr); SocketFactory socketFactory = new StandardSocketFactory(); final Socket sock = socketFactory.createSocket(); final int timeout = client.getDatanodeReadTimeout(length); NetUtils.connect(sock, isa, client.getRandomLocalInterfaceAddr(), client.getConf().socketTimeout); sock.setSoTimeout(timeout); sock.setSendBufferSize(HdfsConstants.DEFAULT_DATA_SOCKET_SIZE); if (DFSClient.LOG.isDebugEnabled()) { DFSClient.LOG.debug("Send buf size " + sock.getSendBufferSize()); } return sock; }
From source file:android.core.SSLSocketTest.java
/** * Does a number of HTTPS requests on some host and consumes the response. * We don't use the HttpsUrlConnection class, but do this on our own * with the SSLSocket class. This gives us a chance to test the basic * behavior of SSL./*from w ww . j a v a2 s .co m*/ * * @param host The host name the request is being sent to. * @param port The port the request is being sent to. * @param path The path being requested (e.g. "/index.html"). * @param outerLoop The number of times we reconnect and do the request. * @param innerLoop The number of times we do the request for each * connection (using HTTP keep-alive). * @param delay The delay after each request (in seconds). * @throws IOException When a problem occurs. */ private void fetch(SSLSocketFactory socketFactory, String host, int port, boolean secure, String path, int outerLoop, int innerLoop, int delay, int timeout) throws IOException { InetSocketAddress address = new InetSocketAddress(host, port); for (int i = 0; i < outerLoop; i++) { // Connect to the remote host Socket socket = secure ? socketFactory.createSocket() : new Socket(); if (timeout >= 0) { socket.setKeepAlive(true); socket.setSoTimeout(timeout * 1000); } socket.connect(address); // Get the streams OutputStream output = socket.getOutputStream(); PrintWriter writer = new PrintWriter(output); try { DataInputStream input = new DataInputStream(socket.getInputStream()); try { for (int j = 0; j < innerLoop; j++) { android.util.Log.d("SSLSocketTest", "GET https://" + host + path + " HTTP/1.1"); // Send a request writer.println("GET https://" + host + path + " HTTP/1.1\r"); writer.println("Host: " + host + "\r"); writer.println("Connection: " + (j == innerLoop - 1 ? "Close" : "Keep-Alive") + "\r"); writer.println("\r"); writer.flush(); int length = -1; boolean chunked = false; String line = input.readLine(); if (line == null) { throw new IOException("No response from server"); // android.util.Log.d("SSLSocketTest", "No response from server"); } // Consume the headers, check content length and encoding type while (line != null && line.length() != 0) { // System.out.println(line); int dot = line.indexOf(':'); if (dot != -1) { String key = line.substring(0, dot).trim(); String value = line.substring(dot + 1).trim(); if ("Content-Length".equalsIgnoreCase(key)) { length = Integer.valueOf(value); } else if ("Transfer-Encoding".equalsIgnoreCase(key)) { chunked = "Chunked".equalsIgnoreCase(value); } } line = input.readLine(); } assertTrue("Need either content length or chunked encoding", length != -1 || chunked); // Consume the content itself if (chunked) { length = Integer.parseInt(input.readLine(), 16); while (length != 0) { byte[] buffer = new byte[length]; input.readFully(buffer); input.readLine(); length = Integer.parseInt(input.readLine(), 16); } input.readLine(); } else { byte[] buffer = new byte[length]; input.readFully(buffer); } // Sleep for the given number of seconds try { Thread.sleep(delay * 1000); } catch (InterruptedException ex) { // Shut up! } } } finally { input.close(); } } finally { writer.close(); } // Close the connection socket.close(); } }