List of usage examples for java.net Socket setSoTimeout
public synchronized void setSoTimeout(int timeout) throws SocketException
From source file:com.clavain.munin.MuninNode.java
public void run() { b_isRunning = true;/* w w w. ja v a 2 s . c om*/ 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:net.lightbody.bmp.proxy.jetty.util.ThreadedServer.java
/** * Accept socket connection. May be overriden by derived class to create specialist * serversockets (eg SSL)./*from ww w .j a va2s.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:org.cloudata.core.commitlog.CommitLogClient.java
public void open() throws UnmatchedLogException, CommitLogInterruptedException, IOException { pipeKey = generateUniqueKey();//from w w w .j a va 2 s .c om if (LOG.isDebugEnabled()) { String msg = ""; for (String addr : ipAddressList) { msg = msg + addr + ", "; } LOG.debug("Open new pipe with timeout[" + this.timeout + "], key [" + pipeKey + "], -> " + msg); } String ret = null; Socket s = null; try { sc = SocketChannel.open(); s = sc.socket(); s.setTcpNoDelay(true); s.setSoTimeout(timeout); int addressIndex = 0; if (verifiedAddressIndex >= 0) { addressIndex = verifiedAddressIndex; } LOG.debug("open pipe to " + pipeAddressList[addressIndex]); sc.connect(pipeAddressList[addressIndex]); } catch (ClosedByInterruptException e) { internalClose(); throw new CommitLogInterruptedException(); } catch (IOException e) { throw new CommitLogShutDownException(e); } try { byte[] body = buildBody(); currentStream = new DataOutputStream(new BufferedOutputStream(s.getOutputStream(), 8192)); checkInputStream = new DataInputStream(s.getInputStream()); currentStream.write(MAGIC_KEY); currentStream.writeInt(0); currentStream.writeInt(body.length); currentStream.write(body); currentStream.flush(); DataInputStream dis = new DataInputStream(s.getInputStream()); byte[] key = new byte[MAGIC_KEY.length]; if (dis.read(key) < 0) { throw new IOException("Fail to establish pipe connection to " + getPipeAddressListStr()); } if (!Arrays.equals(MAGIC_KEY, key)) { throw new IOException( "Fail to establish pipe connection to " + getPipeAddressList() + "due to wrong magic key"); } int opCode = dis.readInt(); int replyLength = dis.readInt(); body = new byte[replyLength]; dis.read(body); ret = new String(body); } catch (ClosedByInterruptException e) { internalClose(); throw new CommitLogInterruptedException(); } catch (IOException e) { LOG.warn("Fail to establish pipe to " + getPipeAddressListStr() + " due to " + e, e); internalClose(); throw new IOException("Fail to establish pipe connection to " + getPipeAddressListStr(), e); } if (!ret.equals(Constants.PIPE_CONNECTED)) { internalClose(); if (ret.equals("Log files are unmatched among commit log servers")) { throw new UnmatchedLogException("Log files are unmatched among commit log servers"); } throw new IOException( "Fail to establish pipe connection to " + getPipeAddressListStr() + ". response : " + ret); } else { closed = false; } }
From source file:org.apache.hadoop.hdfs.DataStreamer.java
/** * Create a socket for a write pipeline/*w w w .j ava2s.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 DfsClientConf conf = client.getConf(); final String dnAddr = first.getXferAddr(conf.isConnectToDnViaHostname()); if (LOG.isDebugEnabled()) { LOG.debug("Connecting to datanode " + dnAddr); } final InetSocketAddress isa = NetUtils.createSocketAddr(dnAddr); final Socket sock = client.socketFactory.createSocket(); final int timeout = client.getDatanodeReadTimeout(length); NetUtils.connect(sock, isa, client.getRandomLocalInterfaceAddr(), conf.getSocketTimeout()); sock.setSoTimeout(timeout); sock.setSendBufferSize(HdfsConstants.DEFAULT_DATA_SOCKET_SIZE); if (LOG.isDebugEnabled()) { LOG.debug("Send buf size " + sock.getSendBufferSize()); } return sock; }
From source file:org.gcaldaemon.core.http.HTTPListener.java
public final void run() { // Variables//from w ww .j a va 2 s.c o m Socket socket = null; Request request = null; Response response = null; try { // Loop for (;;) { // Accept connection socket = serverSocket.accept(); socket.setSoTimeout(5000); // Access control try { checkAccess(socket); } catch (Exception securityError) { log.debug("Connection refused!", securityError); try { socket.close(); } catch (Exception igonre) { } socket = null; } // Parse request request = null; if (socket != null) { try { request = readRequest(socket); log.debug("Processing " + request.method + " method..."); } catch (Exception readError) { log.warn("Unable to read request!", readError); request = null; } } // Create response response = null; if (request != null) { if (request.url != null && request.url.endsWith(".ics")) { int i = request.url.indexOf('@'); if (i != -1) { request.url = request.url.substring(0, i) + "%40" + request.url.substring(i + 1); } i = request.url.indexOf("googlemail.com"); if (i != -1) { request.url = request.url.substring(0, i) + "gmail.com" + request.url.substring(i + 14); } } try { if (GET_METHOD.equals(request.method)) { response = doGet(request); } else { if (PUT_METHOD.equals(request.method)) { response = doPut(request); } else { response = doUnsupportedMethod(request); } } } catch (Exception processingError) { log.warn("Unable to process request!", processingError); response = null; } } // Write response if (response != null) { log.trace("Response processed with status code " + response.status + "."); try { writeResponse(socket, request, response); } catch (Exception writeError) { log.warn("Unable to write response!", writeError); response = null; } } request = null; // Close socket if (socket != null) { try { socket.close(); } catch (Exception closeError) { log.warn("Unable to close socket!", closeError); socket = null; } } } } catch (SocketException socketException) { // Check message String msg = socketException.getMessage(); if (msg == null || msg.indexOf("close") == -1) { log.fatal("Fatal HTTP server error!", socketException); } } catch (Exception fatalError) { // Service stopped log.fatal("Fatal service error!", fatalError); } finally { // Close resources if (serverSocket != null && !serverSocket.isClosed()) { try { serverSocket.close(); } catch (Exception ignore) { } } if (socket != null) { try { socket.close(); } catch (Exception igonre) { } socket = null; } } log.info("HTTP server stopped."); }
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 va 2 s . c om*/ 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:hornet.framework.clamav.service.ClamAVCheckService.java
/** * Cette mthode permet l'envoie d'une commande ClamAV et retourne le rsultat sous la forme d'une * chaine de caractre./*from www . j a v a 2 s .co m*/ * * @param command * - la commade transmettre * @param strEndDetection * - la chaine de caractre permettant de dtecter la dernire ligne du retour. * @return La rponse de clamAV sans traitement * @throws ClamAVException * the clam av exception */ private ClamAvResponse callClamAV(final TypeResponse command, final String strEndDetection) throws ClamAVException { ClamAvResponse result; final StringBuilder resultat = new StringBuilder(); final Date dateDebut = new Date(); Socket socket = null; BufferedReader buffer = null; try { socket = this.connect(command); if (socket == null) { result = ClamAvResponse.createNoServiceResponse(); } else { // timeout pour l'ensemble des oprations sur la // socket socket.setSoTimeout(this.timeout); final InputStream input = socket.getInputStream(); final OutputStream ouput = socket.getOutputStream(); // envoi de la commande clamAV ouput.write(("n" + command.toString() + "\n").getBytes(UTF_8)); // Attente et traitement de la rponse buffer = new BufferedReader(new InputStreamReader(input, UTF_8)); String retour = ""; int indexResultat = -1; while (retour != null && indexResultat == -1) { retour = buffer.readLine(); if (retour != null) { indexResultat = retour.indexOf(strEndDetection); resultat.append(retour); resultat.append('\n'); } } ClamAVCheckService.LOGGER.debug("Retour ClamAV (en {} ms) :\n{}", new Date().getTime() - dateDebut.getTime(), resultat); result = this.traitementReponseClamAV(resultat.toString(), command); } } catch (final UnknownHostException e) { ClamAVCheckService.LOGGER.error(String.format(ERROR_ON_COMMAND, command), e); throw new ClamAVException(ERR_TEC_CLAMAV_01, new String[] { e.getMessage() }, e); } catch (final IOException e) { ClamAVCheckService.LOGGER.error(String.format(ERROR_ON_COMMAND, command), e); throw new ClamAVException(ERR_TEC_CLAMAV_01, new String[] { e.getMessage() }, e); } finally { this.safeClose(command, socket, buffer); } return result; }
From source file:it.jnrpe.client.JNRPEClient.java
/** * Inovoke a command installed in JNRPE. * /* w w w. ja v a2 s . c om*/ * @param sCommandName * The name of the command to be invoked * @param arguments * The arguments to pass to the command (will substitute the * $ARGSx$ parameters) * @return The value returned by the server * @throws JNRPEClientException * Thrown on any communication error. */ public final ReturnValue sendCommand(final String sCommandName, final String... arguments) throws JNRPEClientException { SocketFactory socketFactory; Socket s = null; try { if (!useSSL) { socketFactory = SocketFactory.getDefault(); } else { SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); sslContext.init(null, new TrustManager[] { getTrustManager() }, new SecureRandom()); socketFactory = sslContext.getSocketFactory(); } s = socketFactory.createSocket(); if (weakCipherSuitesEnabled) { SSLSocket ssl = (SSLSocket) s; ssl.setEnabledCipherSuites(ssl.getSupportedCipherSuites()); } s.setSoTimeout((int) TimeUnit.SECOND.convert(communicationTimeout)); s.connect(new InetSocketAddress(serverIPorURL, serverPort)); JNRPERequest req = new JNRPERequest(sCommandName, arguments); s.getOutputStream().write(req.toByteArray()); InputStream in = s.getInputStream(); JNRPEResponse res = new JNRPEResponse(in); return new ReturnValue(Status.fromIntValue(res.getResultCode()), res.getMessage()); } catch (RuntimeException re) { throw re; } catch (Exception e) { throw new JNRPEClientException(e); } finally { if (s != null) { try { s.close(); } catch (IOException e) { // Ignore } } } }
From source file:org.mule.transport.tcp.TcpConnector.java
public void configureSocket(boolean client, Socket socket) throws SocketException { // There is some overhead in setting socket timeout and buffer size, so we're // careful here only to set if needed if (newValue(getReceiveBufferSize(), socket.getReceiveBufferSize())) { socket.setReceiveBufferSize(getReceiveBufferSize()); }//from ww w . ja va 2 s.c om if (newValue(getSendBufferSize(), socket.getSendBufferSize())) { socket.setSendBufferSize(getSendBufferSize()); } if (client) { if (newValue(getClientSoTimeout(), socket.getSoTimeout())) { socket.setSoTimeout(getClientSoTimeout()); } } else { if (newValue(getServerSoTimeout(), socket.getSoTimeout())) { socket.setSoTimeout(getServerSoTimeout()); } } if (newValue(getSocketSoLinger(), socket.getSoLinger())) { socket.setSoLinger(true, getSocketSoLinger()); } try { socket.setTcpNoDelay(isSendTcpNoDelay()); } catch (SocketException e) { // MULE-2800 - Bug in Solaris } socket.setKeepAlive(isKeepAlive()); }
From source file:com.syncedsynapse.kore2.jsonrpc.HostConnection.java
/** * Auxiliary method to open the TCP {@link Socket}. * This method calls connect() so that any errors are cathced * @param hostInfo Host info//from ww w.j a v a 2 s.com * @return Connection set up * @throws ApiException */ private Socket openTcpConnection(HostInfo hostInfo) throws ApiException { try { LogUtils.LOGD(TAG, "Opening TCP connection on host: " + hostInfo.getAddress()); Socket socket = new Socket(); final InetSocketAddress address = new InetSocketAddress(hostInfo.getAddress(), hostInfo.getTcpPort()); // We're setting a read timeout on the socket, so no need to explicitly close it socket.setSoTimeout(TCP_READ_TIMEOUT); socket.connect(address, connectTimeout); return socket; } catch (IOException e) { LogUtils.LOGW(TAG, "Failed to open TCP connection to host: " + hostInfo.getAddress()); throw new ApiException(ApiException.IO_EXCEPTION_WHILE_CONNECTING, e); } }